I'm trying to run this command ps -j | more
. I think i've set up the pipes correctly, but for some reason it just hangs:
I'm calling a fork that runs ps -j
and a second fork that runs more
and connecting them with pipes.
For some reason this is still not working as intended.
Code below:
#define BUF_SIZE 100
int main() {
pid_t pid1, pid2;
int save_stdin, save_stdout;
int fd[2];
char *argv1[] = { "/bin/ps", "-j", NULL };
char *argv2[] = { "/bin/more", NULL };
char prompt[] = "Press enter: ";
char buffer[BUF_SIZE];
write(STDOUT_FILENO, prompt, sizeof(prompt) - 1);
ssize_t readIn = readIn = read(STDIN_FILENO, buffer, BUF_SIZE);
buffer[readIn - 1] = '\0';
printf("readIn: %d\n", readIn);
pipe(fd);
pid1 = fork();
if (pid1 == 0) { // child
close(fd[0]);
save_stdout = dup(1);
dup2(fd[1], STDOUT_FILENO);
execvp(argv1[0], argv1);
close(fd[1]);
} else { // parent
pid2 = fork();
if(pid2 == 0) {
save_stdin = dup(0);
dup2(fd[0], STDIN_FILENO);
execvp(argv2[0], argv2);
close(fd[0]);
} else {
}
}
dup2(save_stdin, 0);
dup2(save_stdout, 1);
close(save_stdin);
close(save_stdout);
int i = 1;
do {
wait(NULL);
} while (i-- > 0);
exit(0);
}
Any help greatly appreciated!
EDIT:
I've tried closing the pipes after dup2()
but before execvp()
, but it's still hanging:
pipe(fd);
pid1 = fork();
if (pid1 == 0) { // child
dup2(fd[1], STDOUT_FILENO);
close(fd[1]);
close(fd[0]);
int res1 = execvp(argv1[0], argv1);
printf("exec1: %d\n", res1);
} else { // parent
pid2 = fork();
if(pid2 == 0) {
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
int res2 = execvp(argv2[0], argv2);
printf("exec2: %d\n", res2);
} else {
}
}
close(fd[1]);
close(fd[0]);
printf("finished\n");
int i = 1;
do {
wait(NULL);
} while (i-- > 0);