Question

The code above does not give any warnings or errors, but the parent does not print the string passed with the pipe. Any idea?

pid_t pid;
int fd[2];
int num_bytes_read;
char buffer[80];
pipe (fd);
pid=fork();
if (pid == 0) {/*Son*/
    fclose(stdout);
    close(fd[0]);
    dup(fd[1]);
    printf ("write in pipe\n");
    fflush(stdout);
}
else { /*Parent*/
    close (fd[1]);
    num_bytes_read = read (fd[0], buffer, sizeof (buffer));
    printf ("The received string is: %s\n", buffer);
}
return (0);
Was it helpful?

Solution

In the child you are writing to FILE* which you have just closed (i.e. stdout). With dup you have assigned to fd == 0 the descriptor of the pipe, but the structure where stdout points remains "closed". Either write to pipe using write (as suggested by @chrk) or do close(STDOUT_FILENO) instead of fclose(stdout), or maybe you can also reassign to stdout a new value obtained from fdopen.

OTHER TIPS

In the child process, you use printf(3) which tries to write to stdout.

If you want to write to pipe, you can use write(2), just like you used read(2) to read from it for the parent process.

Use dup2. You are assuming that dup is returning 1, but you have no way of knowing that. Also, since you've already closed stdout, the call to printf is probably failing. Check the return value. Instead of fclosing stdout, you can close the underlying file descriptor, but that's not good practice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top