Operating System- CS604
Assignment # 1
Solution
Fall 2010
Marks: 20
Due Date
Your assignment must be uploaded before or on 8thNov 2010.
Objective
The objective of this assignment is to familiarize
with the fork ( ), exit ( ) and wait ( ) system calls.
Instructions
Ø
Avoid Plagiarism. No marks will be given in case of cheating
or copying from the internet or from other students.
Ø Submit
the assignment through your account on VULMS. No assignment will be accepted
through email after the due date.
Ø If
you have any problem related to assignment, feel free to discuss it by email at
cs604@vu.edu.pk
Question # 1:
Understand
the below program carefully and explain each line accordingly.
#include
<stdio.h>
void
main ( )
1………………… {
2……………………….int pid, status;
3……………………….pid = fork ( );
4……………………….if (pid = = -1)
5……………………… {
6……………………………printf(“fork
failed\n”);
7……………………………exit(1) ;
8……………………….}
9………………………if (pid = = 0)
10……………………… {
11………………………... printf( “Child here
! \n”);
12………………………... exit (0);
13……………………….}
14……………………….else
15……………………… {
16………………………… wait (&status);
17………………………… printf(“well done kid
!\n”);
18………………………… exit (0);
19……………………….}
20………………….}
1
|
{
|
Starting
the main ( ) function.
|
2
|
int pid, status;
|
Declaring two integer variables pid
& status.
|
3
|
pid = fork ( );
|
The fork
( ) method will call and store the integer value in the pid variable. In case
of Child “0” value returned while the parent will store the “process id” of
the child. In case when fork fails it will be initialized by -1
|
4
|
if (pid = = -1)
|
This condition will be only true
when fork failed.
|
5
|
{
|
Starting the if block (when fork
failed)
|
6
|
printf(“fork failed\n”);
|
“fork failed “ message will be printed
on screen.
|
7
|
exit(1) ;
|
The exit
(1) system call will terminate the process and will return 1 to the parent
process to indicate the abnormal termination.
|
8
|
}
|
if block ends.
|
9
|
if (pid = = 0)
|
This condition will be only true
in case of Child Process because fork will return 0.
|
10
|
{
|
Starting the if block
|
11
|
printf( “Child here ! \n”);
|
“Child here!” message on screen
|
12
|
exit (0);
|
The exit
(0) system call will terminate the process normally and will return 0 to
parent process.
|
13
|
}
|
if block ends.
|
14
|
else
|
This block of code will be
executed in the case of Parent Process only because fork returns ID of
Child Process to parent process, which is not 0.
|
15
|
{
|
else block starts.
|
16
|
wait (&status);
|
Wait system call will suspend the
parent process until the child process is terminated and returns 0 value
through exit system call status and the parameter passed by child process 0
will be stored in status variable.
|
17
|
printf(“well done kid !\n”);
|
“well done kid!”
message on screen
|
18
|
exit (0);
|
The exit (0) system call will
terminate the parent process normally.
|
19
|
}
|
else block ends.
|
20
|
}
|
main ( ) function ends.
|
No comments:
Post a Comment