By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,750 Members | 1,159 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,750 IT Pros & Developers. It's quick & easy.

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

P: 1
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");
exit(EXIT_FAILURE);
}

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

execlp("od", "od", "-c", (char *)0);
exit(EXIT_FAILURE);
}
else {
close(file_pipes[0]);
data_processed = write(file_pipes[1], some_data,
strlen(some_data));
close(file_pipes[1]);
printf("%d - wrote %d bytes\n", (int)getpid(), data_processed);
}
}
exit(EXIT_SUCCESS);
}
Oct 3 '06 #1
Share this Question
Share on Google+
1 Reply


100+
P: 144
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);
  3.  
  4. // Reassign STDIN to be the stream pointed at by file_pipes[0]
  5. dup(file_pipes[0]);
  6.  
  7. // Close our orignal read stream
  8. close(file_pipes[0]);
  9.  
  10. // Close our orignal write stream
  11. close(file_pipes[1]);
  12.  
  13. // The "od' command will now receive info written to the pipe through STDIN
  14.  
Oct 3 '06 #2

Post your reply

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