【发布时间】:2011-04-14 04:27:43
【问题描述】:
我在进行进程分叉练习时遇到问题。我想分叉一个子进程,并在宣布它被分叉后挂起,并等待信号终止,之后父进程必须宣布它正在终止然后退出。
我可以让进程分叉并让父进程等待挂起的子进程被信号杀死,但它似乎也杀死了父进程。我尝试通过其 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。你不需要两次
<unistd.h>,现在你不需要<sys/types.h>(尽管在一些早期版本的POSIX中,它是必需的)。 -
这不会编译,即使编译也没有多大意义。
tempPID完全未声明,并在仅在父进程中使用的信号处理程序中读取,尽管它仅在子进程中设置。至少解决这个问题,我们会看看我们可以从哪里找到你。