进程
1. fork , waitpid
1 #include2 #include 3 #include 4 #include 5 6 int main(void) 7 { 8 pid_t pid = fork(); // 创建一个进程 9 10 if(pid<0){11 perror("fork");12 exit(1);13 }14 15 else if(pid==0){16 sleep(3);17 printf("child proc\n");18 }19 20 else if(pid>0){21 sleep(1);22 printf("parent proc\n");23 waitpid(pid,NULL,0); // 阻塞等待回收子进程 不回收成为孤儿进程,24 //waitpid(pid,NULL,WNOHANG); //非阻塞回收子进程25 26 printf("子进程回收成功 !\n");27 28 }29 30 return 0 ;31 }
测试:
2. 守护进程:
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 8 void daemon_init(void) 9 {10 // 1.创建子进程,终止父进程11 pid_t pid = fork();12 if(pid<0){13 perror("fork");14 exit(0);15 }16 else if(pid>0) // 父退出17 exit(0); 18 else if(pid==0){19 20 // 2.在子进程创建会话,setsid()21 setsid();22 23 // 3.忽略SIGHUP信号24 signal(SIGHUP,SIG_IGN);25 26 // 4.再创建进程,终止父进程27 pid=fork();28 if(pid<0){29 perror("fork two");30 exit(1);31 }32 else if(pid>0)33 exit(0);34 35 // 5.关闭文件描述符36 int i,fd_max = sysconf(_SC_OPEN_MAX);37 for(i=0;i<=fd_max;i++)38 close(i);39 40 // 6.将子进程工作目录改为“/”,chdir()41 chdir("/");42 43 // 7.文件权限掩码为0,umask()44 umask(0);45 46 // 8.添加新的文件描述符47 int fd = open("/dev/null",O_RDWR); 48 dup(fd);49 dup(fd);50 }51 }52 53 int main(void)54 {55 56 daemon_init();57 while(1){58 printf("I am daemon \n");59 sleep(2);60 }61 62 return 0;63 }