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