我应该使用exit()终止分叉的子进程吗?

时间:2014-02-01 05:53:22

标签: c fork parent-child

我在C中使用fork()处理一些事情。这是我第一次接触分叉过程的概念。

基本上,我有类似的东西:

int pid;

pid = fork();
if (pid < 0) {
    fprintf(stderr, "Fork Failed");
    exit(-1);
} else if (pid == 0) {
    fprintf(stderr, "Inside child %d\n", getpid());
    // do some other stuff
    exit(0);
} else {
    fprintf(stderr, "Inside parent %d\n", getpid());
}

之前,我没有将exit(0)放在子进程代码中。我看起来似乎有很多重复的过程。我添加了exit(0),现在我只生了一个孩子。但是,我想知道这是正确的做法还是只是一个绑带。这是正确的做法。孩子完成后应该如何“停止”?

2 个答案:

答案 0 :(得分:4)

通常孩子拥有自己的代码exit或调用其中一个exec函数来用其他程序替换其进程的图像。所以退出是好的。但是父和子可以至少执行一些相同的代码,如下所示:

int pid = fork();
if (pid < 0) {
    fprintf(stderr, "Fork Failed");
    exit(-1);
} else if (pid == 0) {
    // child code
} else {
   // parent code
}
// shared code

答案 1 :(得分:1)

如果您希望父进程在子进程完成后才能工作,那么您可以使用wait函数。以下是示例:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h> //fork() is defined in this header file
#include<sys/wait.h>//wait() is defined in this header file
int main()
{
    int pid,a,b;
    printf("\nPlease enter two numbers\n");
    scanf("%d%d",&a,&b);
    pid=fork();
    if(pid<0)
    {
        printf("\nfork failed\n");
        exit(1);
    }
    if(pid==0)
    {
        //you are in chiled process
        //getting child process id
        printf("\n[child %d]: sum of %d and %d is %d\n",getpid(),a,b,a+b);
    }
    else
    {
        //waiting for child process to finish
        wait(NULL);
        //getting parent id
        printf("\n[parent %d]:difference of %d and %d is %d\n",pa_pid,a,b,a-b);
        exit(0);
    }
}
相关问题