- 论坛徽章:
- 0
|
问题描述很简单,写一个程序接收整数,根据该整数创立若干个进程,sleep一段时间,然后父进程报告每个子进程的退出。
我的代码有个问题我无法理解。先把正确的代码贴出来:- #include <stdio.h>
- #include <signal.h>
- #include <stdlib.h>
- int wait_pid=0;
- int main(int args,char *av[])
- {
- //signal(SIGCHLD,report_quit);
- if(args==1)
- {
- printf("You should declare the number of the child process that you want to build!");
- return 1;
- }
- else
- {
- int num_p=atoi(av[1]);
- int child_pid=1;
- int i=0;
- for(i=0;i<num_p;i++)
- {
- if(child_pid!=0)
- {
- child_pid=fork();
- printf("%d :%d \n",getpid(),child_pid);
- if(child_pid==0)
- {
- sleep(2);
- exit(17);
- }
- else if(child_pid==-1)
- {
- perror("fork error!");
- exit(2);
- }
- }
- }
- while((wait_pid=wait(NULL))!=-1)
- printf("the child process %d exited!\n",wait_pid);
- }
- return 0;
- }
复制代码 执行结果是:- 11240 :11241
- 11241 :0
- 11240 :11242
- 11242 :0
- 11240 :11243
- 11243 :0
- 11240 :11244
- 11244 :0
- the child process 11241 exited!
- the child process 11242 exited!
- the child process 11243 exited!
- the child process 11244 exited!
复制代码 而我想利用信号处理的方法:子进程结束时,调用exit时会向父进程发送一个SIGCHLD信号,让父进程捕捉这个信号来报告子进程的结束。代码中加入了一个处理函数:- #include <stdio.h>
- #include <signal.h>
- #include <stdlib.h>
- void report_quit();
- int wait_pid=0;
- int main(int args,char *av[])
- {
- signal(SIGCHLD,report_quit);
- if(args==1)
- {
- printf("You should declare the number of the child process that you want to build!");
- return 1;
- }
- else
- {
- int num_p=atoi(av[1]);
- int child_pid=1;
- int i=0;
- for(i=0;i<num_p;i++)
- {
- if(child_pid!=0)
- {
- child_pid=fork();
- printf("%d :%d \n",getpid(),child_pid);
- if(child_pid==0)
- {
- sleep(2);
- exit(17);
- }
- else if(child_pid==-1)
- {
- perror("fork error!");
- exit(2);
- }
- }
- }
- while(1)
- wait_pid=wait(NULL);
- // printf("the child process %d exited!\n",wait_pid);
- }
- return 0;
- }
- void report_quit()
- {
- printf("the child process %d exited.\n",wait_pid);
- }
复制代码 但是执行结果如下:- 11266 :11267
- 11267 :0
- 11266 :11268
- 11268 :0
- 11266 :11269
- 11269 :0
- 11266 :11270
- 11270 :0
- the child process 0 exited.
- the child process 11268 exited.
- the child process 11268 exited.
复制代码 我不明白为什么了。如果您知道,请讲一下,非常感谢。 |
|