守护(后台)进程的创建

来源:互联网 发布:涉密网络保密检查标准 编辑:程序博客网 时间:2024/05/21 22:57
/*功能:守护进程的创建后台进程的创建思想:首先父进程创建一个子进程,然后子进程杀死父进程。信号处理所有的工作由子进程来处理。*/#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <stdio.h>#include <errno.h>#include <fcntl.h>#include <signal.h>#define MAIL "/var/spool/mail/zcm"#define SLEEP_TIME 8int main(){pid_t child;if((child = fork()) == -1){printf("Fork Error: %s\n", strerror(errno));return 1;}else if(child > 0)// parent processwhile(1);else// child process{if(kill(getppid(), SIGTERM) == -1)// kill parent process{printf("Kill Parent Error: %s\n", strerror(errno));return 1;}int mailfd;while(1){/*if((mailfd = open(MAIL, O_RDONLY)) != -1){fprintf(stderr, "%s", "\007");close(mailfd);}*///fprintf(stderr, "%s", "\007");fprintf(stdout, "Hello world baby\n");sleep(SLEEP_TIME);}}return 0;}