fork() in
C
·
Fork system call use for creates a
new process, which is called child process.
· This child process runs concurrently
with Parent process (The Process
from which fork() is called).
· After a new child process created,
both processes will execute the next instruction following the fork() system
call.
· A child process use same PC(program
counter), same CPU registers, same open files which use in parent process.
Argument: 0
Return
Value:
Negative
Value: Creation
of a child process was unsuccessful.
Zero: Returned to the newly created child process.
Positive value: Returned to parent or caller. The value contains process ID of newly created child process.
Zero: Returned to the newly created child process.
Positive value: Returned to parent or caller. The value contains process ID of newly created child process.
1. Predict
the Output of the following program.
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
//
make two process which run same
//
program after this instruction
fork();
printf("Hello
world!\n");
return
0;
}
|
Output:
Hello world!
Hello world!
2. Calculate number of times hello is
printed.
#include
<stdio.h>
#include
<sys/types.h>
int main()
{
fork();
fork();
fork();
printf("hello\n");
return
0;
}
|
Output:
hello
hello
hello
hello
hello
hello
hello
hello
Number of
times hello printed is equal to number of process created. Total Number of
Processes = 2n where n is number of fork system calls. So here n =
3, 23 = 8
Comments
Post a Comment