我在進行分叉練習時遇到問題。我想分叉一個子進程,並在聲明它已經分叉後讓它掛起,等待一個信號終止,之後父進程必須宣佈它正在終止然後退出。在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