Simple Fork Example – Checking Return Value
1 Answers
#include <unistd.h>
#include <stdio.h>
int main() {
 pid_t ret;
 printf("welcome..pid=%d\n", getpid());
 ret = fork();
 if (ret < 0) {
   perror("fork");
   exit(1);
 }
 if (ret == 0) {
printf("Hello, this is child process\n");
   printf("child--welcome,pid=%d,ppid=%d\n", getpid(), getppid());
   exit(0);
 } else // ret>0
 {
printf("Hello, this is parent process\n");
   printf("parent--hello,pid=%d,ppid=%d\n", getpid(), getppid());
   sleep(1);
 }
 // printf("thank you,pid=%d,ppid=%d\n", getpid(),getppid());
 return 0;
}
Notes
- Creates a new process known as child process
- New pid, PCB/PD will be allocated to child (new entry in process table)
- Duplicates resources from parent to child
- fork returns zero to child, non zero to parent
- Child resumes from next statement after fork
- Parent & child run concurrently
Observations and Understanding
- Can you distinguish between parent and child in above code, and control over which process should execute which code?
- Mapping child’s ppid with parent’s pid
- What is parent’s ppid, to which process it belongs to?
- Check the pid, ppid values from the output of ps, pstree commands (Ensure program won’t terminate by using sleep/getchar)
- What is the meaning of +ve ret value returned to parent process?
- When do fork fails with negative return value
- What if any code written unconditionally outside if-else
- Create an array before fork, try modifying in one process (whichever executes first, may be parent) and check the values in other.
- What is your observation, whether array is shared between parent and child or two copies are maintained.