我在处理进程 fork 练习时遇到了问题。我想 fork 一个子进程并在宣布它已 fork 后挂起它,并等待信号终止,之后父进程必须宣布它正在终止然后退出。
我可以让进程 fork 并让父进程等待挂起的子进程被信号杀死,但它似乎也杀死了父进程。我尝试专门通过 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),也存在问题:
- 您让 child 休眠,直到信号到达。
- 您将父项设置为等到子项死亡。
因此,您处于两个进程都不会再做任何事情的状态。
您可能需要 parent 向 child 发送信号:
kill(pid, SIGINT);
- 不清楚您是否需要父级设置信号处理程序。
- 您可能希望 child 设置信号处理程序。
- 您可能不希望 child 中出现无限循环。
- 哦,还有
void main()
不正确 -int main()
或int main(void)
或int main(int argc, char **argv)
是main()
的批准声明. - 如果从
main()
返回值 (0) 会更简洁. C99 标准确实允许您放弃main()
的末尾并将其视为返回零,但前提是函数被正确声明为返回int
. wait()
的 header POSIX 中的亲戚是<sys/wait.h>
.
而且,因为我是个笨蛋,这里的代码可以编译,甚至可以做你想做的事:
#include <stdio.h>
#include <signal.h>
#include <unistd.h> /* getpid() */
#include <stdlib.h>
#include <sys/wait.h>
void catchInt(int signum)
{
printf("Child's PID is %d\n", (int)getpid());
printf("My sincerest apologies, master\n");
exit(1);
}
int main()
{
pid_t 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);
pause();
}
else /* parent */
{
sleep(1);
kill(pid, SIGINT);
wait(NULL);
printf("You're welcome\n");
}
return(0);
}
关于c - 子进程在 C 中终止后,父进程未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743305/