
Aero T.
asked 07/23/21Write a C program where two child processes are created using fork().
Write a C program where two child processes are created using fork(). The parent process and the two child processes communicate with each other via a pipe. More specifically, the first child process writes 5 random number in the range of 0-99 to the pipe, and the second child process also writes another 5 random number in the same range to the pipe. The order of which child process writes to the pipe does not matter and the 10 random numbers could be interleaved between the two child processes. The parent process reads out the 10 random numbers from the pipe and print them out on the display (terminal).
1 Expert Answer

Shanek K. answered 08/13/21
Computer Science Professional Tutor
Here you go....
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main() {
int pipefds[2];
int returnstatus;
int pid,pid1;
int readmessage[1];
returnstatus = pipe(pipefds);
if (returnstatus == -1) {
printf("Unable to create pipe\n");
return 1;
}
pid = fork();
// Child process
if (pid != 0){
pid1 = fork();
if (pid1 != 0) {
for (int i =0;i<10;i++){
read(pipefds[0],readmessage, sizeof(readmessage));
printf("%d is the number read by parent\n",readmessage[0]);
}}
else {
for (int i =0; i<5;i++)
{
int rand_n = rand()%100;
printf("Child Process 2 - Writing to pipe - Message 1 is %d\n", rand_n);
write(pipefds[1], &rand_n, sizeof(rand_n));
}
}
} else {
for (int i =0; i<5;i++)
{
int rand_n = rand()%100;
printf("Child Process 1- Writing to pipe - Message 1 is %d\n", rand_n);
write(pipefds[1], &rand_n, sizeof(rand_n));
}
}
return 0;
}
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Patrick B.
I'm interested, but only have cygwin unix emulator and Dev C++, and a shabby one at best, which do not support this type of IPC. The best I can offer is IPC via sockets using Java.07/23/21