Last active
December 13, 2020 23:39
-
-
Save hrlou/723d0a05d990a99d12f688eb44b9b756 to your computer and use it in GitHub Desktop.
Example of how to pipe the stdout of a child process into the parent process and read it into a buffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <sys/wait.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#define PROCESS "/bin/ls" | |
#define ARGV "ls", "-la" | |
void main(void) { | |
// fd is the file descriptor for input and output | |
// fd[1] is the input side | |
// fd[0] is the output side | |
int fd[2], nbytes; | |
pid_t pid; | |
char readbuffer[256]; | |
pipe(fd); | |
// for if forking fails | |
if ((pid = fork()) == -1) { | |
perror("fork"); | |
exit(1); | |
} | |
if (pid == 0) { | |
// child process closes output side of pipe | |
close(fd[0]); | |
// redirect the child's stdout to the input side; fd[1] | |
dup2(fd[1], 1); | |
// execute the child | |
execlp(PROCESS, ARGV, NULL); | |
// kill the child | |
exit(0); | |
} | |
else { | |
// wait for child to exit | |
waitpid(pid,0,0); | |
// parent process closes input side of pipe | |
close(fd[1]); | |
// read in the stdout from the pipe | |
nbytes = read(fd[0], readbuffer, sizeof(readbuffer)); | |
// append with terminator | |
readbuffer[nbytes] = '\0'; | |
printf("Received Start\n%s\nRecived Finish\n", readbuffer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment