Program 1 will open a named pipe (pick a name) and fork; the child will execute
ID: 3828972 • Letter: P
Question
Program 1 will open a named pipe (pick a name) and fork; the child will execute Program 2. In the parent, Program 1 will read from standard input pairs of integers and writes the sum and difference of the integers to the pipe. Finally it waits for the child to terminate, prints the child’s status code, and it terminates. Program 2 (pick a name) will open the named pipe and read pairs of integers. From these it will recover the original pair the Program 1 read and print the original pair to standard output. When it sees a pair of zeros, it will terminate and return the status code of the number of [non-zero] pairs it read.
Explanation / Answer
Given below is an implementation of Program1 (parent process) and Program2 (child process).
File: Program1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char **argv)
{
int num1;
int num2;
int sum;
int diff;
int pipe;
int pid;
int status;
// Create child process
pid = fork ();
if (pid == 0) {
// Child process
char *argv[1] = { NULL };
execvp ("./Program2", argv);
}
// Parent process
pipe = open("/tmp/myFIFO", O_WRONLY); // Open the named pipe in write mode
do
{
// Read a pair of integers from standard input
scanf("%d %d", &num1, &num2);
// Compute sum and difference of integers read
sum = num1 + num2;
diff = num1 - num2;
// Write sum and difference to named pipe
printf("[Program 1] %d %d ", sum, diff);
write(pipe, &sum, sizeof(sum));
write(pipe, &diff, sizeof(diff));
} while ((num1 != 0) || (num2 != 0));
// Wait for child process to complete
waitpid(pid, &status, 0);
printf("[Program 1] count = %d ", WEXITSTATUS(status));
close(pipe);
}
File: Program2.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char **argv)
{
int i, j;
int pipe;
int num1;
int num2;
int sum;
int diff;
int count = 0;
// Open the named pipe in read mode
pipe = open("/tmp/myFIFO", O_RDONLY);
do
{
// Read sum and difference of two integers
read(pipe, &sum, sizeof(sum));
read(pipe, &diff, sizeof(diff));
// Determine integers from sum and difference
num1 = (sum + diff) / 2;
num2 = sum - num1;
printf("[Program 2] %d %d ", num1, num2);
if ((num1 != 0) || (num2 != 0)) count++;
} while ((num1 != 0) || (num2 !=0));
close(pipe);
printf("[Program 2] count = %d ", count);
exit (count);
}
Compilation:
$ gcc -o Program1 Program1.c
$ gcc -o Program2 Program2.c
Create Named Pipe:
$ mkfifo /tmp/myFIFO
Sample Execution Output:
$ ./Program1 10 0
[Program 1] 10 10
[Program 2] 10 0
0 10
[Program 1] 10 -10
[Program 2] 0 10
0 0
[Program 1] 0 0
[Program 2] 0 0
[Program 2] count = 2
[Program 1] count = 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.