Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork() child and parent processes

Tags:

c

fork

parent

I am trying to create a program that uses fork() to create a new process. The sample output should look like so:

This is the child process. My pid is 733 and my parent's id is 772.
This is the parent process. My pid is 772 and my child's id is 773.

This is how I coded my program:

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), fork());

    return 0;
}

This results in the output:

This is the child process. My pid is 22163 and my parent's id is 0.
This is the child process. My pid is 22162 and my parent's id is 22163.

Why is it printing the statement twice and how can I get it to properly show the parent's id after the child id displays in the first sentence?

EDIT:

#include <stdio.h>
#include <stdlib.h>

int main() {
int pid = fork();

if (pid == 0) {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
}
else {
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), pid);
}

return 0;
}
like image 243
raphnguyen Avatar asked Sep 01 '11 03:09

raphnguyen


1 Answers

Start by reading the fork man page as well as the getppid / getpid man pages.

From fork's

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

So this should be something down the lines of

if ((pid=fork())==0){
    printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
    printf("Dont yada yada me, im your parent with pid %u ", getpid());
}

As to your question:

This is the child process. My pid is 22163 and my parent's id is 0.

This is the child process. My pid is 22162 and my parent's id is 22163.

fork() executes before the printf. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork() will return 0 to the child process, and the pid of the child process to the parent process.

You get two running processes, each one will execute this instruction statement:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

and

printf ("... My pid is %d and my parent's id is %d",getpid(),22163);  

~

To wrap it up, the above line is the child, specifying its pid. The second line is the parent process, specifying its id (22162) and its child's (22163).

like image 55
Tom Avatar answered Sep 19 '22 05:09

Tom