471,873 Members | 1,398 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,873 software developers and data experts.

pipe() and dup()... (stdin/stdout)

The following code is example code of the book "Beginning Linux Programming 3rd Edition" ....
I've compiled and ran it...it's work...
Can anyone tell me why the child process can read data from file_pipes[0] while thd file_pipes[0] was closed...

================================================== ====
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
int data_processed;
int file_pipes[2];
const char some_data[] = "123";
pid_t fork_result;

if (pipe(file_pipes) == 0) {
fork_result = fork();
if (fork_result == (pid_t)-1) {
fprintf(stderr, "Fork failure");

if (fork_result == (pid_t)0) {
close(file_pipes[0]); //Here!!!!...I don't know why?

execlp("od", "od", "-c", (char *)0);
else {
data_processed = write(file_pipes[1], some_data,
printf("%d - wrote %d bytes\n", (int)getpid(), data_processed);
Oct 3 '06 #1
1 18869
144 100+
What is happening is a bit subtle. The "dup" function is the strange culprit. What is basically happening is that the child process is closing stdin and then reassigning stdin to the pipe stream pointed to by file_pipes[0]. We now have 2 seperate file descriptors pointing at the pipe stream. Closing one doesn't close both. So, when you close file_pipes[0] the stdin stream can still be read from.

Expand|Select|Wrap|Line Numbers
  1. // Close STDIN
  2. close(0);
  4. // Reassign STDIN to be the stream pointed at by file_pipes[0]
  5. dup(file_pipes[0]);
  7. // Close our orignal read stream
  8. close(file_pipes[0]);
  10. // Close our orignal write stream
  11. close(file_pipes[1]);
  13. // The "od' command will now receive info written to the pipe through STDIN
Oct 3 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Jean-Pierre Bergamin | last post: by
1 post views Thread by Vincent Touquet | last post: by
1 post views Thread by Harry George | last post: by
1 post views Thread by Michael McGarry | last post: by
5 posts views Thread by Michael McGarry | last post: by
3 posts views Thread by Mike Finister | last post: by
5 posts views Thread by Martijn Brouwer | last post: by
2 posts views Thread by momotaro | last post: by
8 posts views Thread by subramanian100in | last post: by
reply views Thread by YellowAndGreen | last post: by
reply views Thread by zermasroor | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.