Professional Documents
Culture Documents
Sheet #3
If-else or switch syntax (based on return value of fork() ) is used to execute separate code for parent and
child.
If(!fork() { child body} else {parent body} rest of programme common to both
switch(fork){case 0:child codes;break; default: parent code;}rest of programme common to both
vfork() - similar to fork() except parent blocks until child terminates. It shares data space where is in
fork() both processes run concurrently but does not share memory.
The exec() family of functions replaces the current process image with a new process image.
Problem
Q1
(a) write basic fork programme where each child and parent execute following code separately-
{ for(n=0;n<5;n++){x++;
printf("\nchild id %d, father %d x=%d",getpid(),getppid(),x);
sleep(1);
}
{ for(n=0;n<5;n++){x++;
printf("\nparent id %d, father %d x=%d",getpid(),getppid(),x);
sleep(1);
}
where x and n are integers.
(b) repeat above with child n<5 and parent n<3;
(c) repeat above with child n<3 and parent n<6;
If parent process survives child then still child process remains in system as parent may call child's exit
code. So child is called zombie process or defunct that is no longer running but still holding system
resources. If parent terminated abnormally (before removing child) child become orphan and its ppid
becomes 1. init() will clean up orphan processes until child hold resources and affects the system
performance.
RUN the following programme in back ground and then run ps command (fast) many time (at leat 5
times) to see defunct message.
(d) write programme that gives orphaned or defunct process.
(use sleep(10); in parent
(e) repeat part (a) with vfork and verify parent blocks and data modified in child reflects in parent code..
Q2
(a) include following code in parent after loop
childpid=wait(&status);
printf("\n*****\n child finished id %d",childpid);
if(WIFEXITED(status)) printf("\n child exit code %d",WEXITSTATUS(status));
and
exit(m); // common to both (outside if-else)
where m is exit code assigned in child part of the code
and childpid and m are integers.
Q3