user623990
user623990

Reputation:

Should I be terminating a forked child process with exit()?

I'm working on some stuff using fork() in C. This is my first contact with the concept of forking processes.

Basically, I have something like this:

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());
}

Before, I hadn't put the exit(0) in the child process' code. I was getting seemingly tons of duplicate processes. I added the exit(0) and now I'm only spawning one child. However, I want to know if this is proper practise or just a bandaid. Is this the correct thing to do. How should a child "stop" when its done?

Upvotes: 3

Views: 8222

Answers (2)

Prashant Anuragi
Prashant Anuragi

Reputation: 390

Well if you want that parent process works only after child process finishes then you can use wait function.Here is the example:

#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);
    }
}

Upvotes: 1

ooga
ooga

Reputation: 15501

Usually the child either has it's own code with an exit or calls one of the exec functions to replace its process's image with another program. So the exit is okay. But the parent and child could execute at least some of the same code, something like this:

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

Upvotes: 5

Related Questions