Reputation: 1671
I'm trying to get acquainted with pipes and I have written a pretty stupid parrot program that basically takes in the input from the keyboard and then displays the exact same thing:
if (pipe(fd) < 0) {
perror("Pipe");
exit(1);
}
if ( ( pid = fork() < 0 ) ) {
perror("Fork");
exit(1);
}
if ( pid > 0 ) //If I'm the parent...
{
printf("Parent!");
close(fd[0]);
//as long as something is typed in and that something isn't
// the word "stop"
while (((n = read(STDIN_FILENO, buffer, BUFFERSIZE)) > 0) &&
(strncmp(buffer, "stop", 4) != 0))
{
//shove all the buffer content into the pipe
write(fd[1], buffer, BUFFERSIZE);
}
}
else //If I am the child...
{
printf("Child!");
close(fd[1]);
//as long as there's something to read
while (pipe_read = read(fd[0], buf, sizeof(buf)) > 0)
{
//display on the screen!
write(STDOUT_FILENO, buf, pipe_read);
}
}
I get why this program doesn't get engaged in the loop, that is because the parent never executes and as a result I get Child! Child!
as output and I can't figure out why.
Upvotes: 1
Views: 75
Reputation: 2793
Change
if ( ( pid = fork() < 0 ) )
with
if ( (pid = fork()) < 0 )
Without the right parentheses pid
was being set to (fork() < 0)
, which was 0
.
Upvotes: 7