apue中等待子进程都有哪些方法或技巧?
摘要:前言 谈到等待子进程,首先想到的就是 SIGCHLD 信号与 wait 函数族,本文试图厘清二者的方方面面,以及组合使用时可能的坑。 单独使用 SIGCHLD 的场景 使用 signal 捕获信号 下面是一段典型的代码片段: 1 #incl
前言
谈到等待子进程,首先想到的就是 SIGCHLD 信号与 wait 函数族,本文试图厘清二者的方方面面,以及组合使用时可能的坑。
单独使用 SIGCHLD 的场景
使用 signal 捕获信号
下面是一段典型的代码片段:
1 #include "../apue.h"
2 #include <sys/wait.h>
3
4 #define CLD_NUM 2
5 static void sig_cld (int signo)
6 {
7 pid_t pid = 0;
8 int status = 0;
9 printf ("SIGCHLD received\n");
10 if (signal (SIGCHLD, sig_cld) == SIG_ERR)
11 perror ("signal error");
12 if ((pid = wait (&status)) < 0)
13 perror ("wait(in signal) error");
14 printf ("pid (wait in signal) = %d\n", pid);
15 }
16
17 int main ()
18 {
19 pid_t pid = 0;
20 __sighandler_t ret = signal (SIGCHLD, sig_cld);
21 if (ret == SIG_ERR)
22 perror ("signal error");
23 else
24 printf ("old handler %x\n", ret);
25
26 for (int i=0; i<CLD_NUM; ++ i)
27 {
28 if ((pid = fork ()) < 0)
29 perror ("fork error");
30 else if (pid == 0)
31 {
32 sleep (3);
33 printf ("child %u exit\n", getpid ());
34 _exit (0);
35 }
36
37 sleep (1);
38 }
39
40 for (int i=0; i<CLD_NUM; ++ i)
41 {
42 pause ();
43 printf ("wake up by signal %d\n", i);
44 }
45
46 printf ("parent exit\n");
47 return 0;
48 }
父进程启动了两个子进程,在 SIGCHLD 信号处理器中调用 wait 等待已结束的子进程,回收进程信息,防止产生僵尸进程 (zombie)。
