我在进行分叉练习时遇到问题。我想分叉一个子进程,并在声明它已经分叉后让它挂起,等待一个信号终止,之后父进程必须宣布它正在终止然后退出。在C中终止子进程后,父进程未完成
我可以得到进程分叉,并让父母等待悬挂的孩子被信号杀死,但它似乎也杀死了父母。我试图通过PID来杀死儿童进程,但没有成功。
感谢您的帮助!
代码:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
void catchInt (int signum)
{
printf("\nMy sincerest apologies, master\n");
/*kill(0, SIGINT);*/
exit(0);
}
void ignoreInt (int signum)
{
wait(NULL);
}
int main() {
pid_t pid;
/* fork process */
pid = fork();
if (pid < 0) /* error handler */
{
fprintf(stderr, "Fork Failed");
exit(-1);
}
else if (pid == 0) /* child */
{
printf("Child reporting in\n");
signal(SIGINT, catchInt);
for (;;)
pause();
}
else /* parent */
{
/* parent will wait for the child to complete */
signal(SIGINT, ignoreInt);
wait(NULL);
printf("You're welcome\n");
exit(0);
}
}
您显示的代码无法编译 - 您尚未定义tempPID。你不需要''两次,而现在你不需要''(尽管在一些早期版本的POSIX中,它是需要的)。 –
2010-09-18 20:23:00
这不能编译,即使它做了也没什么意义。 'tempPID'完全没有声明,并且只在父进程中使用的信号处理程序中读取,尽管它只在子进程中设置。至少解决这个问题,我们会看到我们可以从那里获得你的位置。 – 2010-09-18 20:24:43