-1

I am trying to link the output of a child process into the input of a parent process; the parent process is to execute a system call or command using the child's output.

I have looked to the following threads for answer; however, I didn't quite get the answer I am looking for.

Pipe - C++ piping issue

Linux Pipes as Input and Output

The problem I am having is that the command in the parent process is not being printed to the terminal.

Why isn't the output being printed to the terminal? I have closed the ends of my pipe in both the parent and child processes. Furthermore, the parent's std_out isn't being modified.

Here is my code.

#include <sys/types.h>
#include <sys/wait.h>  
#include <stdio.h>     
#include <stdlib.h>   
#include <unistd.h>     
#include <iostream>     

using namespace std;

int main(int argc, const char * argv[])
{
    enum {RD, WR};
    int fd[2];
    pid_t pid;

    if (pipe(fd) < 0)
        perror("pipe error");
    else if ((pid = fork()) < 0)
        perror("fork error");
    else if (pid == 0) { //In child process
        close(fd[RD]);
        dup2(fd[WR], STDOUT_FILENO);
        close(fd[WR]);
        execlp("/bin/ps", "ps", "-A", NULL);
    }
    else { //In parent process
        close(fd[WR]);
        dup2(fd[RD], STDIN_FILENO);
        close(fd[RD]);
        wait(NULL);
        execlp("/bin/wc", "wc", "-l", NULL);
    }
    return 0;
}
Community
  • 1
  • 1
Tyler K
  • 110
  • 1
  • 11

1 Answers1

0

You don't check for the failure of execlp.

Are you sure all of your programs are where you think they are? Your program works for me if I just change "/bin/wc" to "/usr/bin/wc".

Sean
  • 29,130
  • 4
  • 80
  • 105
  • That did correct the problem of printing to the terminal; however, now it is only printing "0". Did you get the number of all your currently running processes as your output? – Tyler K Apr 13 '16 at 22:11
  • Yes, it printed `243` just now when I tried it. Are you checking for the failure of both `execlp` invocations? When I changed `"/bin/ps"` to `"/foo/bin/ps"` I see `0` as the main program's output. – Sean Apr 13 '16 at 23:33
  • No I am not. How should I do that? – Tyler K Apr 14 '16 at 03:17
  • Just put something like `perror("Child execlp failed");` after the first one and `perror("Parent execlp failed");` after the second. – Sean Apr 14 '16 at 04:10