Why piping doesn't work for the following code?
int p_fds[2];
pipe(p_fds);
int pid_left = fork();
if (pid_left == 0){
dup2(p_fds[1],STDOUT_FILENO);
close(p_fds[0]);
close(p_fds[1]);
execv("cat", (char*[]){ "cat", "afile" });//execlp("cat", "cat", "afile", NULL);
exit(1);
}
int pid_right = fork();
if (pid_right == 0){
dup2(p_fds[0], STDIN_FILENO);
close(p_fds[1]);
close(p_fds[0]);
execv("grep", (char*[]){ "grep", "something" });//execlp("grep", "grep", "something", NULL);
exit(1);
}
close(p_fds[0]);
close(p_fds[1]);
waitpid(pid_left, NULL, 0);
waitpid(pid_right, NULL, 0);
but it works with execlp
or any other exec* except execv
. What should be updated to make it work with execv
?
It is expected that this code print something in main stdout like cat afile | grep sth
.