Reputation: 12378
I'm running a program that does piping. The command I want to run is ls | cat.
int cmd(char** w, int* pipe, int action){
... some code up here
...
int fd;
if(child_pid == 0) {
if (pipe != 0) {
if (action == 0){
fd = dup2(pipe[0], STDIN_FILENO);
close(pipe[0]);
close(pipe[1]);
//close(fd);
}
else if (action == 1){
fd = dup2(pipe[1], STDOUT_FILENO);
close(pipe[0]);
close(pipe[1]);
//close(fd);
}
}
execvp(w[0], w);
printf("Unknown command\n");
exit(0);
}
... some code down here
When I run the code, the command ls | cat runs fine except that the cat doesn't end(i.e. the pipe doesn't close and just waits there doing nothing). I think it's because I didn't close a stream or something, but I'm not familiar enough with C/IO to know for sure. Am I doing this right?
the code that runs this function is like
int fd[2];
int p = pipe(fd);
cmd(w, fd, 1);
cmd(w, fd, 0);
edit: ur right, fatalerror, i mistyped on the arguement
thxs, looks like i just needed to close pipe[1] in the parent
Upvotes: 1
Views: 4125
Reputation: 215193
The parent process also needs to close both ends of the pipe after the two cmd
calls.
Upvotes: 3