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

Fork a Process The following code can fork a child process. Both parent and chil

ID: 3854299 • Letter: F

Question

Fork a Process

The following code can fork a child process. Both parent and child process can all print out 50 lines. Please modify the code to make parent process print out the even number of lines among the 50 lines, and the child process will only print out the odd number of lines. In your output message, please specify if the process is a parent process or a child process. And also output the process id. Please submit your C language source code

#include <stdio.h>

#include <string.h>

#include <sys/types.h>

#define   MAX_COUNT 50

#define   BUF_SIZE   100

void main(void)

{

     pid_t pid;

     int    i;

     char   buf[BUF_SIZE];

     fork();

     pid = getpid();

     for (i = 1; i <= MAX_COUNT; i++) {

          sprintf(buf, "This line is from pid %d, value = %d ", pid, i);

          write(1, buf, strlen(buf));

     }

}

Explanation / Answer

Please find the modified code below:

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

#define MAX_COUNT 50
#define BUF_SIZE 100
void main(void)
{
pid_t pid;
int i;
char buf[BUF_SIZE];
fork();
pid=getpid();
for(i=1;i<=MAX_COUNT;i++)
{
if(pid==0 && (i%2!=0)) //Checking condtion for child process and odd number lines
{
sprintf(buf, "Child Process: pid %d, value = %d ", pid, i);
write(1,buf, strlen(buf));
}
else if(pid>0 && (i%2==0)) //Checking condtion for parent process and even number lines
{
sprintf(buf, "Parent Process: pid %d, value = %d ", pid, i);
write(1,buf, strlen(buf));
}
}
}

It it does not work properly, kindly try with the below code. I have implement this code.

#include<stdio.h>
#include<string.h>
#include<sys/types.h>

#define MAX_COUNT 50
#define BUF_SIZE 100

void ChildProcess(void); /* child process prototype */
void ParentProcess(void); /* parent process prototype */

void main(void)
{
char buf[BUF_SIZE];
pid_t pid;
pid=fork();
if(pid==0)
ChildProcess();
else
ParentProcess();
}

void ChildProcess(void)
{
int i;
for(i=1;i<= MAX_COUNT;i++)
{
if(i%2!=0) //Checking condtion for and odd number of lines
{
sprintf(buf, "Child process: pid %d, value = %d ", pid, i);
write(1, buf, strlen(buf));
}
}   
}

void ParentProcess(void)
{
int i;
for(i=1;i<=MAX_COUNT;i++)
{
if(i%2==0) //Checking condtion for even number of lines
{
sprintf(buf, "Parent process: pid %d, value = %d ", pid, i);
write(1, buf, strlen(buf));
}
}
}

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