Created
July 20, 2016 17:20
-
-
Save lstipakov/f5cfdcffb26a256abcf6fbc466d06777 to your computer and use it in GitHub Desktop.
This file contains 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 <stdio.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <string.h> | |
#define BUFSIZE 4096 | |
int main(int argc, char const *argv[]) { | |
int rc, status, filedes[2]; | |
pid_t pid; | |
if (pipe(filedes) == -1) { | |
printf("pipe() error %d\n", errno); | |
return 1; | |
} | |
pid = fork(); | |
if (pid > 0) { | |
// read output | |
printf("I am parent %d\n", getpid()); | |
// hangs if this is commented out!! | |
//close(filedes[1]); | |
size_t bytesRead; | |
char buf[BUFSIZE]; | |
memset(buf, '\0', BUFSIZE); | |
while ((bytesRead = read(filedes[0], buf, BUFSIZE - 1)) > 0) { | |
printf("%s", buf); | |
memset(buf, '\0', BUFSIZE); | |
} | |
int status; | |
wait(&status); | |
} else { | |
// write output | |
printf("I am child %d\n", getpid()); | |
//close(filedes[0]); | |
FILE* fp = popen("ls -l /usr/bin", "r"); | |
if (fp == NULL) { | |
printf("popen() fails %d\n", errno); | |
return 1; | |
} | |
size_t bytesRead; | |
char buf[BUFSIZE]; | |
while ((bytesRead = fread(buf, 1, BUFSIZE, fp)) > 0) { | |
// write to pipe | |
write(filedes[1], buf, bytesRead); | |
} | |
pclose(fp); | |
close(filedes[1]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment