[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAXFILE 65535
static void sig_handler_usr(int sig)
{
int len, fd;
char *buf = "This is a Daemon\n";
len = strlen(buf);
if(( fd = open("/tmp/dameon.log", O_CREAT|O_WRONLY|O_APPEND,0600)) < 0 ) {
perror("open");
exit(1);
}
write(fd, buf, len + 1);
close(fd);
}
int main()
{
pid_t pc;
int i;
pc = fork();
if( pc < 0 ) {
printf("error fork\n");
exit(1);
} else if ( pc > 0 )
exit(0); /*在父进程里,父进程退出*/
setsid();
chdir("/");
umask(0);
for( i = 0; i< MAXFILE; i++ )
close(i);
signal(SIGUSR1, sig_handler_usr); //安装信号
while(1) {
sleep(10);
}
}