cs604 P
cs604 P
CS 604P
You are required to describe how the following code created in the C program works.
Execute the program in C first, then determine how it works from its output. Also,
attach screenshots of the output.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[BUFFER_SIZE];
int nbytes;
// Create pipe
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
return 0;
}
Ans :
Include necessary libraries: The program includes standard C libraries for input/output
operations, handling errors, creating processes, and inter-process communication.
Define constants: BUFFER_SIZE is defined as 256, indicating the size of the buffer used
for storing messages.
Main function:
It declares necessary variables including an array pipefd for storing file descriptors of
the pipe, a process ID pid, and a character array buffer for storing messages.
It creates a pipe using the pipe() function. If the creation of the pipe fails, it prints an
error message and exits the program.
It forks a child process using fork(). This creates a new process that is a copy of the
current process. The return value of fork() in the parent process is the process ID of the
child process, and in the child process, it returns 0.
In the child process:
It closes the write end of the pipe (pipefd[1]) since it only wants to read from the pipe.
It reads from the pipe (pipefd[0]) and stores the received message in the buffer. If the
read operation fails, it prints an error message and exits.
It prints the received message.
It closes the read end of the pipe (pipefd[0]) after reading.
It exits successfully.
In the parent process:
It closes the read end of the pipe (pipefd[0]) since it only wants to write to the pipe.
It prompts the user to enter a message to send to the child process.
It reads the message from the user using fgets() and writes it to the pipe (pipefd[1]).
It closes the write end of the pipe (pipefd[1]) after writing.
It waits for the child process to finish using wait(NULL).
It exits successfully.
Execution:
When the program runs, it prompts the user to enter a message.
The user enters a message which is sent to the child process through the pipe.
The child process receives the message, prints it, and exits.
The parent process waits for the child process to finish and then exits.
The screenshots of the program execution will show the user input prompt, the message
entered by the user, and the message received and printed by the child process.
In the following table, write the details for the given Linux commands.