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

Compile this in a Linux operating system #include <sys/types.h> #include < unist

ID: 657499 • Letter: C

Question

Compile this in a Linux operating system

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
pid_t pid;
char *message;
int n;

printf("fork program starting ");
pid = fork();
switch(pid)
{
case -1:
  perror("fork failed");
  exit(1);
case 0:
  message = "This is the child";
  n = 5;
  break;
default:
  message = "This is the parent";
  n = 3;
  break;
}

for(; n > 0; n--) {
  puts(message);
  sleep(1);
}
exit(1);
}

Compile and run the program.

>> cc Lab1.c -o Lab1.out (this will compile your program and output an executable file Lab1.out

>> ./ Lab1.out (this runs the compiled program)

This program runs as two processes. A child is created and prints a message five times. The original process (parent) prints a message only three times. The parent process finishes before the child has printed all of its messages, so we see the next shell prompt appear mixed in with the output.

Modify the codes so that parent process only print a message one time and child process prints messages three times.

A doc file with 4 screen shots: 1) one shows that you create the source code file, 2) one shows that the program is compiled and run, 3) one shows the modified new code, 4) output of the new program execution

Explanation / Answer

#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>

int var_glb; /* A global variable*/

int main(void)
{
pid_t childPID;
int var_lcl = 0;

childPID = fork();

if(childPID >= 0) // fork was successful
{
if(childPID == 0) // child process
{
var_lcl++;
var_glb++;
printf(" Child Process :: var_lcl = [%d], var_glb[%d] ", var_lcl, var_glb);
}
else //Parent process
{
var_lcl = 10;
var_glb = 20;
printf(" Parent process :: var_lcl = [%d], var_glb[%d] ", var_lcl, var_glb);
}
}
else // fork failed
{
printf(" Fork failed, quitting!!!!!! ");
return 1;
}

return 0;
}

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