Created
April 21, 2020 08:27
-
-
Save jiangzc/ecf6775d455814b7abc149810e0f9fb8 to your computer and use it in GitHub Desktop.
get sub process's output in parent process using pipe redirection
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
// get sub process's output in parent process using pipe redirection | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <error.h> | |
#define BUFFSIZE 4000 | |
int main() | |
{ | |
int pipefd[2]; | |
pid_t pid; | |
if (pipe(pipefd) != 0) | |
{ | |
perror("cannot create pipe"); | |
} | |
pid = fork(); | |
if (pid == -1) | |
{ | |
perror("cannot fork"); | |
} | |
else if (pid == 0) | |
{ | |
// child process | |
close(pipefd[0]); | |
int res = dup2(pipefd[1], STDOUT_FILENO); | |
if (res != -1) | |
execlp("lsblk", "lsblk", "--fs", "-o", "+MODEL,SIZE", "-J", NULL); | |
else | |
{ | |
perror("cannot redirect"); | |
exit(1); | |
} | |
} | |
close(pipefd[1]); | |
int status = -1; | |
waitpid(pid, &status, 0); | |
char buff[BUFFSIZE]; | |
ssize_t count = 0; | |
count = read(pipefd[0], buff, BUFFSIZE - 1); | |
if (count > 0) | |
buff[count] = '\0'; | |
else | |
perror("read error"); | |
// is there left data ? | |
char test; | |
count = read(pipefd[0], &test, 1); | |
printf("%s\n", buff); | |
if (count == 1) | |
fprintf(stderr, "read incomplete data\n"); | |
close(pipefd[0]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment