Search code examples
cpipeexecl

Print pipe content to screen


I am using the execlp() to execute commands on child process and save into a pipe to be read by parent as such for example

int pipefd[2];
if (pipe(pipefd)) {
    perror("pipe");
    exit(127);
}
if(!fork()){
    close(pipefd[0]);
    dup2(pipefd[1], 1);
    close(pipefd[1]);
    execlp("ls", "ls", NULL);
} else {
    close(pipefd[1]);
    dup2(pipefd[0], 0);
    close(pipefd[0]);
    execlp("wc", "wc", NULL);
}

In some cases, parent doesn't have to execute anything, but rather just print out content of the pipe on the screen, how can I print pipe on screen (possibly without storing into a variable due to unknown output size).


Solution

  • how can I print [the content of the] pipe on [the] screen

    read() from the pipe byte by byte and printf("%d\n", byte); it until the pipe is empty, that is until read() returned 0.

    If you can asure it's just text coming through the pipe don't print the byte as int (one per line as shown above) but as char in a row using printf("%c", byte);