代码示例_进程

进程


 1. fork ,  waitpid

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <sys/wait.h>
 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
");
18     }
19 
20     else if(pid>0){
21         sleep(1);
22         printf("parent proc
");
23         waitpid(pid,NULL,0);  // 阻塞等待回收子进程    不回收成为孤儿进程,
24         //waitpid(pid,NULL,WNOHANG); //非阻塞回收子进程
25 
26         printf("子进程回收成功 !
");
27 
28     }
29 
30     return 0 ;
31 }

测试:



2. 守护进程:

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <signal.h>
 4 #include <sys/stat.h>
 5 #include <stdlib.h>
 6 #include <fcntl.h>
 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 
");
59         sleep(2);
60     }
61 
62     return 0;
63 }

Stay hungry, stay foolish 待续。。。
原文地址:https://www.cnblogs.com/panda-w/p/11059799.html