Search code examples
clinuxforkexecpopen

How to grab output from execlp command that imitates pipe?


I have a C program that should emulate the same thing as calling:

popen("ls | grep som")

Right now I have two processes that each execute one part of this command and the firsts' output is the second ones' input. When I execute the program I see the correct line being prompted in the terminal but I can't seem to save the output to a string. I always end up with the first thing ls command prints out.

Example: if ls prints out: one two three

the string is always equal to "one".

This is what the code looks like:

int fd[2];
pipe(fd);
pid_t pid1, pid2;
FILE *f;

int pid1 = fork();
if (pid1 == 0) {
dup2(fd[1], STDOUT_FILENO);
close(fd[1]);
close(fd[0]);
execlp("ls", "ls", NULL);
}

int pid2 = fork();
if (pid2 == 0) {
dup2(fd[0], STDIN_FILENO);
close(fd[1]);
close(fd[0]);
execlp("grep", "grep", "som",NULL);
}

f = fdopen(fd[0] ,"r");
// then I read the output with snprintf

//and once again I close fd's
close(fd[0]);
close(fd[1]);

waitpid(// first process)
waitpid(// second process)

Solution

  • Add another pipe for grep's stdout and read from it from you main process.