- 论坛徽章:
- 0
|
最近看多进程编程,写了个超BT的Demo,代码如下:
6 void child_end(int signum)
7 {
8 int child_status;
9 int pid;
10 pid = wait(&child_status);
11 printf("child:%d exit status: %d\n", pid, child_status);
12 }
13
14 int main()
15 {
16 int child_pid;
17 if ( signal(SIGCHLD, child_end) == SIG_ERR )
18 {
19 return 1;
20 }
21 for ( int i = 0; i < 10; i++ )
22 {
23 child_pid = fork();
24 if ( child_pid == -1 )
25 {
26 printf("fork error \n");
27 return 2;
28 }
29 else if ( child_pid == 0 )//in child process
30 {
31 printf("hello word %d\n", getpid() );
32 exit(1);
33 }
34 }
35 printf("in parent process %d\n", getpid() );
36 for(int i = 1; i < 10; i++)
37 {
38 sleep(1);
39 }
40 return 0;
41 }
程序一开始就创建了10个子进程,输出了10个“hello word XXXX”,可见创建成功,但是只输出了3句“child:%d exit status: %d”
信息,为什么?父进程退出前ps可以看到N个僵死进程。有的子进程结束了,但是SIGCHLD信号没有被父进程捕捉到?
还有为什么我子进程exit(1)的话父进程得到的child_status就是256,exit(2)的话就是512???exit(10)得到的child_status就是2560??? |
|