PROCESS CREATION

 

Syntax for process creation

int fork();

Returns 0 in child process and child process ID in parent process.

 

Other Related Functions

int getpid()               returns the current process ID int getppid()        returns the parent process ID

wait()                        makes a process wait for other process to complete

 

Virtual fork

vfork() function is similar to fork but both processes shares the same address space.

 

Q1. Find the output of the following program

#include <stdio.h>

#include<unistd.h>

int main()

{int a=5,b=10,pid;

printf("Before fork a=%d b=%d \n",a,b); pid=fork();

if(pid==0)

{a=a+1; b=b+1;

printf("In child a=%d b=%d \n",a,b);}

else

{sleep(1);

a=a-1;

b=b-1;

printf("In Parent a=%d b=%d \n",a,b);}

return 0;

}

 

Output :-


Q2. Rewrite the program in Q1 using vfork() and write the output

 

 

           Q3. Calculate the number of times the text “SRMIST” is printed.

 

#include <stdio.h> #include<unistd.h>

int main()

{

 

 

Output :

 


fork();

fork();

fork(); printf(“SRMIST\n”); return 0;

}


 Q4. Complete the following program as described below :

The child process calculates the sum of odd numbers and the parent process calculate the sum of even numbers up to the number ‘n’. Ensure the Parent process waits for the child process to finish.

 

#include <stdio.h>

#include<unistd.h>

int main()

{int pid,n,oddsum=0,evensum=0;

printf("Enter the value of n : ",a);

scanf(“%d”,&n);

pid=fork();

 

 

return 0;

}

 

Sample Output :

Enter the value of n                                      10

Sum of odd numbers                                    25

Sum of even numbers                                   30

 

Q5. How many child processes are created for the following code?

Hint : Check with small values of ‘n’.

for (i=0; i<n; i++)

fork();

 

Output :


 

Q6. Write a program to print the Child process ID and Parent process ID in both Child and Parent processes

#include <stdio.h> #include<unistd.h> int main(){

 

 

return 0;

}

Sample Output:

 

In Child Process

Parent Process ID                    :

 

18

Child Process ID                      :

20

In Parent Process

Parent Process ID                    :

 

18

Child Process ID                      :

20

 

Q7. How many child processes are created for the following code?

 

#include <stdio.h>

#include<unistd.h>

int main()

{fork(); fork()&&fork()||fork();fork(); printf(“Yes ”);

return 0;}

 

Output :

 

Post a Comment

Previous Post Next Post