Fork () child and parent processes

I am trying to create a program that uses fork () to create a new process. The result of the selection should look like this:

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

This is how I encoded my program:

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

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

    return 0;
}

The result is the result:

This is a child process. My pid is 22163 and my parent id is 0.
This is a child process. My pid is 22162 and my parent id is 22163.

Why does this print the expression twice and how can I make it show the parent id correctly after the child id is displayed 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 id is %d.\n", getpid(), getppid());
}
else {
    printf("This is the parent process. My pid is %d and my parent id is %d.\n", getpid(), pid);
}

return 0;
}
+5
5

fork man, getppid/getpid man.

fork's

PID , 0 - . , -1 , , errno .

, -

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

:

. pid 22163, 0.

. pid 22162, id 22163.

fork() printf. , , . printf . fork() 0 pid .

, :

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

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

~

, , pid. - , (22162) (22163).

+10

, , . 0

- :

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent id is %d.\n", getpid(),getppid());
 else 
    printf("This is the parent process. My pid is %d and my parent id is %d.\n", getpid(), getppid() );
+2

, printf, fork. () printf.

0

.... childs 1, , pid = 1 .

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

fork() if, else. :

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}
0

All Articles