C program with the parent process and a child process communicating with a pipe
Lab 8 – pipe
Write a C program with the parent process and a child process communicating with a pipe. The
child process will execute the shell command provided by the user via command line arguments.
The result of executing this shell command is passed to the parent process using a pipe. The
parent process will write the result into a file called result.txt and acknowledge the user on the
screen with the shell command and the total number of bytes in the result.
For simplicity, the shell command contains only the command name, no argument.
You can only use read, write, close for pipe operation.
Sample run:
Answer:
#include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/wait.h> #include <stdlib.h> void main(int argc, char *argv[]){ int fd[2]; pid_t pid; char ch; pipe(fd); if (pipe(fd) == -1) exit(1); pid=fork(); if (pid == 0){ //child close (fd[0]); //close read side, child only writes to pipe dup2(fd[1], 1); close(fd[1]); //close the write side execlp(argv[1],argv[1],argv[2], (char*)NULL); printf ("Unable to execute...\n"); } else{ close (fd[1]); int count=0; int fd1= open("result.txt", O_CREAT |O_RDWR | O_TRUNC ,0755); while(0!=read(fd[0],&ch,1)){ //read one letter at a time from pipe write(fd1,&ch,1); count++; } waitpid (pid, NULL, 0); /* suspend processing until child finish */ printf ("The result of %s is written into result.txt with total %d bytes.\n",argv[1],count); close(fd[0]);//we're done } }
Leave a reply