[英]Parent process doesn't complete after child is terminated in 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),也存在問題:
因此,您處於一種狀態,其中任何一個進程都不會做任何其他事情。
您可能需要父母向孩子發送信號:
kill(pid, SIGINT);
void main()
是不正確的int main()
或int main(void)
或int main(int argc, char **argv)
是main()
的認可聲明。 main()
返回值(0),則會更整潔。 C99標准確實允許您刪除main()
的末尾,並將其視為返回零,但前提是該函數正確地聲明為返回int
。 wait()
和親戚的標頭是<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);
}
剛弄清楚我在做什么錯,我應該意識到SIGINT被發送到了每個進程,因此父級只是被發送了一個未處理的SIGINT,導致它退出。 感謝所有幫助(我對松散的代碼表示歉意,我真的不應該等到程序完成后再清理它),代碼已在上面進行了編輯並可以正常工作。
再次感謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.