//创建一个守护进程 每5秒钟向 /opt/nfs/test/log.txt 中输入 this is deamon 用 ps -ef 查看守护进程 #include<unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<string.h> #include<stdlib.h> #include<stdio.h> #include<sys/wait.h> int main() { int i,fd; pid_t pid; char *buf="this is deamon/n "; pid=fork(); if (pid<0) { perror("fork error"); exit (1); } else if (pid>0) exit (0); setsid(); //创建会话组 chdir("/"); //把当前目录改为根目录 umask(0);//把权限清空 for (i=0;i<65535;i++) //把这个子进程相关的STDIN STDERR STDOUT类似的进程全部关掉 释放资源 close (i); while (1) { fd=open("/opt/nfs/test/log.txt",O_CREAT|O_RDWR|O_APPEND,S_IRWXU); if (fd<0) { perror("open error"); exit (1); } write(fd,buf,strlen(buf)+1); close(fd); sleep(5); } }