Skip to content

Instantly share code, notes, and snippets.

@jiangzc
Created April 21, 2020 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiangzc/ecf6775d455814b7abc149810e0f9fb8 to your computer and use it in GitHub Desktop.
Save jiangzc/ecf6775d455814b7abc149810e0f9fb8 to your computer and use it in GitHub Desktop.
get sub process's output in parent process using pipe redirection
// 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