c - 子进程在 C 中终止后,父进程未完成

标签 c process fork parent

我在处理进程 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/

相关文章:

c - gcc 编译 c++ 时不带任何标志

c - 为什么我的编译器不接受 fork(),尽管我包含了 <unistd.h>?

c++ - 如何在最后一个子 fork() 下打印一次子进程及其名称和 pid

c - 此代码片段如何不会导致 SIGSEGV 或类似的情况

c - 如何用 C 语言实现包含 PIC 函数调用的堆栈

node.js - 无法使用 Windows 读取 $process.env.NODE_ENV

c++ - 如果 stdin 被另一个进程的管道替换,则 std::getline 中断

c# - 如何在 C# 中获取给定服务的子进程列表?

c++ - setitimer 信号似乎只在 fork 之后才有效

c - 有什么办法可以达到 "undo"C中#line的效果吗?