Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is the codes #include <unistd.h> #include <stdlib.h> #include <stdio.h> sta

ID: 3866599 • Letter: T

Question

This is the codes

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

static void outputChar (char *);

int main(){
pid_t pid;

if ((pid = fork()) < 0){
printf("Fork failed. ");
}else if (pid = 0){
while(1) outputChar("output from child ");
} else{
while(1) outputChar("output from parent ");
}
exit(0);
}

static void outputChar(char *str){
char *ptr;
int c;

setbuf(stdout, NULL);
ptr=str;
while ((c=*ptr++) != 0)
putc(c, stdout);
}

This is the output window.

oomu ptapruetn ftr

oomu tppauretn t

output from fparroemn tp

aorutepnutt

ofurtopumt pfarroemn tp

aoruetntp

uotu tfpruotm f rpoamr epnatr

eontu

topuutt pfurto mf rpaorme npta

roeunttp

uotu ftrpoumt pfarroemn tp

aorutepnutt

ofurtopmu tp afrreonmt

poaurtpeuntt

foruotmpu tp afrreonmt

poaurtepntu

to uftrpoumt pfarroem npta

roeunttp

uoutt pfurtom fpraorme npt

aoruetnptu

to uftrpoumt pfarroemn tp

aourtepnutt

foruotmp upta frreonmt

poaurtepnt

output fromu tp afrreonmt

poaurtepnutt

ofutrpoumt pfarroem npta

roeuntt

pouutt pfurotm fpraorme npta

roeunttp

uotu tfpruotm frpoamr epnatr

enotu

topuuttp uftr formo mp apraernetn

The output is an infinite loop

Questions:

1. How many processes does the program have?

2. Why do the codes generate this kind of output? Document your analysis. (Please study the codes first and be thoughtful on this one)

Explanation / Answer

1)

The program has two processes. a) parent process and b) child process.

Fork works the following way.

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

So, a new child process is created on fork() while the parent is still running.

2)

In each of the process conditions there is while(1), which is always true so it never ends.

In the else if condition pid==0, i.e child process satisfy this and enters the body of else if.

as the while is always true, outputChar function is called with "output from child " as param,

In the same way, the parent process satisfy else condition and enters the body of else

as while condition is always true, outputChar funciton is called with "output from parent " as param

The two processes run parallely and outputChar prints only a character a time.

It prints one char from child process and another char from parent process based on process execution which is why we get to see this kind of output.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote