Search code examples
clinuxforkexecexecl

What will happen if I fork and exec in parent and child?


Here is my sample code called server.c (have removed include's to keep it simple).

int main()
{
    for(int i = 0; i < 10; i++) {
        fork();
        execl("./client", "./client", NULL);
    }
    if (wait(NULL) == -1)
        perror("error with wait");
    return 0;
}

And this is the client code that gets exec'd from the above program.

int main()
{
    printf("This is the child with pid = %d from parent %d", getpid(), getppid());
    return 0;
}

Now let me explain what I think will happen and what I am actually getting as an output.

In server, we enter the for loop. In the first iteration, we hit fork(). At this point there are two processes namely the parent and the first child. Now we exec a program named "client" from both of these processes. This client code just prints some information. So when I run this server program, I should end up getting two lines right? One line from parent and the other from the child? But I only get one line printed and after using strace I found that only parent is printing out stuff, not the child. So why is this?

Is it because the child can no longer be collected since parent is dead(is this the right term?) since it was exec'd? If so, what would happen to the child? It becomes a zombie right? and will it be collected by init? Even so, why won't it print out that line before ending up like a zombie?


Solution

  • If stdout is connected to a terminal, it should be line-buffered, so there's no need to flush. And all streams are flushed automatically when they're closed, which happens when the program finishes.

    Maybe you see both print in the same line? Try this code:

    #include <stdio.h>
    int main(int argc, char **argv) {
      printf("This is the child with pid = %d from parent %d\n", getpid(), getppid());
      return 0;
    }
    

    By the way, you are missing a %d in printf.