【发布时间】:2017-07-25 04:08:42
【问题描述】:
代码如下:
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
int ntimes = 0;
int main()
{
int pid,ppid;
int p_action(),c_action();
/* set parent process SIGUSR1 */
signal(SIGUSR1,p_action);
switch(pid=fork()){
case -1: /* fork failed */
perror("synchro");
exit(1);
case 0: /* child process mode */
/* set child process SIGUSR1 */
signal(SIGUSR1,c_action);
/* get parent process */
ppid = getppid();
for(;;){
sleep(1);
kill(ppid,SIGUSR1);
pause();
}
/* dead loop */
break;
default: /* parent process mode */
for(;;){
pause();
sleep(1);
kill(pid,SIGUSR1);
}
/* dead loop*/
}
return 0;
}
p_action()
{
printf("Parent caught signal #%d\n",++ntimes);
}
c_action()
{
printf("Child caught signal #%d\n",++ntimes);
}
输出是:
父捕获信号 #1 孩子捕捉到信号 #1 父母捕获信号#2 孩子捕捉到信号 #2 父母捕获信号 #3 孩子捕捉到信号 #3 . . .
为什么 child 的 ntimes 与 parent 相同但不是 ++1,例如 parent-1、child-2、parent-3、child-4、...
谢谢!
【问题讨论】:
-
顺便说一句,所示代码没有使用任何循环,因此您提供的输出是由其他来源创建的。
标签: c linux operating-system fork