Read the following program carefully and write the output
of the program. Explain each
line of code according to given numbering.

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

1……………… int main (void)
{
pid_t pid;
2………………………… pid = fork();
3…………………………. if (pid > 0)
{
int i;
4………………………… for (i = 0; i < 5; i++)
{
5………………… …………… printf(" I AM VU : %d\n", i);
6………………… …………… sleep(1);
}
exit(0);
}
7………………… ……… else if (pid == 0) {
int j;
for (j = 0; j < 5; j++)
{
8……………………………… printf(" I have no child: %d\n", j);
sleep(1);
}
_exit(0);
}
else
{
9………………………………fprintf(stderr, "can't fork, error %d\n",
errno);
10……………… … ………… exit (EXIT_FAILURE);
}
}

Answer Posted / saith

1 int main (void) Starts the main function
2 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
3 if (pid > 0) This condition will be only true when fork
failed.
4 for (i = 0; i < 5; i++) Limmitations of for loop are
declared and the loop starts

5 printf(" I AM VU : %d\n", i);
Prints I AM VU and the value of I message on screen
6 sleep(1); Process sleeps
7 else if (pid == 0) Now this blok of code executes in
parent process since fork returns the ID to the parent
process from child. which is not 0.
8 printf(" I have no child: %d\n", j);
“I have no child” is printed on the screen
9 fprintf(stderr, "can't fork, error %d\n", errno);
If the given conditions are not true then this error
message is send
10 exit (EXIT_FAILURE); system call will terminate the
process abnormally as it fails.

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is a far pointer? where we use it?

617


Write about c++ storage classes?

752


What is function overloading in C++?

730


Do you know the problem with overriding functions?

574


Can c++ do everything c can?

601






What are references in c++?

662


What does new do in c++?

637


What is microsoft c++ redistributable 2013?

575


How does atoi function work?

626


Explain the use of virtual destructor?

626


What are special characters c++?

566


What are friend classes?

616


Evaluate as true or false: !(1 &&0 || !1) a) True b) False c) Invalid statement

637


What are the basic data types used in c++?

555


Which bit wise operator is suitable for turning off a particular bit in a number?

645