所以我一直在阅读StackOverflow和fork man-page上的帖子,我只是没有看到我看到的行为,可能是因为我只是在寻找我期望的。在简单的C子/父程序中意外终止
它是一个简单的程序,它接受一个文件名,产生一个子文件,在该文件上运行stat(),然后将SIGUSR1或2返回到循环中的父代。父母只想知道它的1或2 ... 我得到的是“用户定义的信号2”,然后程序退出。但父母是在一个while循环对吗?
无论如何,我真的希望有人能解释为什么我没有得到预期的输出,具体来说,循环不断要求一个文件名并每次产生一个孩子,父母知道孩子返回什么信号与杀()。
pid_t pid;
while(1) {
if(pid == 0) // i am the child
{
FILE *fp = fopen(fname, "r");
if(fp == NULL){
printf("%d] Child cannot find [%s].", msg++, fname);
fclose(fp);
}
else {
stat(fname, &st);
n = st.st_size;
printf("%d] Child read %d chars.\n", msg++, n);
if(n%2) kill(pid, SIGUSR1);
else kill(pid, SIGUSR2);
}
}
else // im the parent
{
if(signal(SIGUSR1,NULL)) // Code never gets here because it ends
printf("%s is odd\n", fname);
if(signal(SIGUSR2, NULL))
printf("$s is even\n", fname);
printf("%d] Enter filenames until you're happy. 'die' to end.\n", msg++);
scanf("%s", fname);
pid = fork();
}
}
return 0;
因为父进程可以在子进程发送信号给父进程之前终止。 –
为什么父母如果在一个while循环中结束? – MatUtter
对不起,我错了!你不会初始化'pid_t pid;' –