本文共 1325 字,大约阅读时间需要 4 分钟。
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <time.h> #include <syslog.h> #include <signal.h> static int daemon_init(char *name, int dochdir, int doclosefd) { pid_t pid, sid, deadChildPid; time_t timebuf; int fd = -1; if(name == NULL) { return -1; } pid = fork(); if (pid < 0) { perror( "fork "); return -1; } //father process exit if(pid > 0) { exit(0); } //child continues //become session leader if((sid = setsid()) < 0) { perror( "setsid "); exit(1); } //change working directory if(dochdir) { if((chdir("/")) < 0) { perror( "chdir "); exit(2); } } //clear our file mode creation mask umask(0); //将标准输入输出重定向到空设备 if(doclosefd) { fd = open ("/dev/null", O_RDWR, 0); if (fd != -1) { dup2 (fd, STDIN_FILENO); dup2 (fd, STDOUT_FILENO); dup2 (fd, STDERR_FILENO); if (fd > 2) close (fd); } } if((pid=fork()) == 0) { return 0; } else if(pid > 0) { deadChildPid = wait(NULL); printf("create a new process !\n"); if(execl(name, name, "executed by execl", NULL)<0) perror("Err on execl"); } exit(0); } int main(int argc, char *argv[]) { daemon_init("./test", 0, 0); while(1) { printf("The process ID is %d\n", (int)getpid()); printf("The parent process ID is %d\n", (int)getppid()); sleep(5); } return 0; }转载地址:http://vsprj.baihongyu.com/