//main.cpp
#include
#include
#include
#include
#include
#include
int foo(void) {
int fd = 0;
fd = open("1.log",O_RDWR | O_CREAT | O_APPEND,0644); /* 1.log的文件描述符是fd */
if( -1 == fd) {
printf("open 1.log file failed
");
return -1;
}
close(STDERR_FILENO); /* 关闭STDERR_FILENO描述符 */
dup2(fd,STDERR_FILENO); /* 复制文件描述符fd到STDERR_FILENO */
close(fd); /* 关闭文件描述符fd */
openlog("1.log",LOG_PERROR,LOG_DAEMON); /* 根据LOG_PERROR,将日志输出STDERR_FILENO定向到1.log */
return 0;
}
int main () {
int ret = 0;
ret = foo();
if (0 != ret) {
printf("error
");
}
syslog(LOG_DEBUG,"hello world
");
return 0;
}
/*
g++ main.cpp
./a.out
cat 1.log
1.log: hello world
*/