In: Computer Science
Write a program to print 2 strings. One string must be written by parent process and another string must be written by a child process
In language C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
//variable declaration
int pid;
//array declaration and initialization
char childStr[] = "Child Process Id: ";
char parentStr[] = "Parent Process Id: ";
pid = fork();
//child process
if(pid==0)
{
//display child process id
printf( "%s%d\n",childStr, getpid() );
}
//parent process
else
{
//display main porecess or parent process id
printf( "%s%d\n", parentStr, getpid());
}
return 0;
}
OUTPUT:
Parent Process Id: 9852
Child Process Id: 9853
Explanation:
fork() system call:
The fork() system call is used to create the child process and the child process is a copy of the parent process that will be run concurrently with the parent process. It returns an integer value and this value may be of three types:
1. Zero
The zero value is returned to the newly created process.
2. Positive value
The positive value is the process id and this value is returned to the parent process.
3. Negative value
If the child process is not created successfully then the negative value is returned.