Reputation: 9
I'm trying to recreate pipe for a homemade shell and I can make the pipe work in this case:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int stat_loc;
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if(pid != 0)
{
waitpid(pid, &stat_loc, WUNTRACED);
close(pipefd[1]);
dup2(pipefd[0], 0);
close(pipefd[0]);
execlp("cat", "cat", "-e", NULL);
}
else
{
close(pipefd[0]);
dup2(pipefd[1], 1);
close(pipefd[1]);
execlp("ls", "ls", NULL);
}
//do something else
printf("out to parent");
return 0;
}
I would use the functional one above but I need to keep the parent process working.
But when I add one more fork, and the process gets stuck in
execlp("cat", "cat", "-e", NULL);
This is the full attempt that gets stuck:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int stat_loc;
int pipefd[2];
pipe(pipefd);
pid_t pid1 = fork();
if (pid1 == 0)
{
pid_t pid = fork();
if(pid != 0)
{
waitpid(pid, &stat_loc, WUNTRACED);
close(pipefd[1]);
dup2(pipefd[0], 0);
close(pipefd[0]);
execlp("cat", "cat", "-e", NULL);
}
else
{
close(pipefd[0]);
dup2(pipefd[1], 1);
close(pipefd[1]);
execlp("ls", "ls", NULL);
}
}
waitpid(pid1, &stat_loc, WUNTRACED);
//do something else
printf("out to parent");
return 0;
}
Thanks for the help!!
Upvotes: 1
Views: 128
Reputation: 782529
You need to close all the pipe FDs in the parent process as well. Otherwise, cat
will never read EOF from its input pipe.
Add:
close(pipefd[0]);
close(pipefd[1]);
before:
waitpid(pid1, &stat_loc, WUNTRACED);
Upvotes: 1