简体   繁体   中英

Why make stdin, stdout and stderr to a single fd?

I saw this code snippet from APUE

dup2(fd,0); dup2(fd,1); dup2(fd, 2); if (fd > 2) close(fd);

In my understanding, it makes stdin, stdout and stderr all point to fd. It says that lots program contain this code, why? What's it functionality?

I'm going to add to the comments and answer here because even though they're correct, I would still have a hard time understanding exactly when and why this sequence of calls were needed.

This sequence of function calls is typically used when a process will run as a daemon. In that case, among other things, the daemon doesn't want to have the standard I/O file descriptors attached to the terminal (or other resources). To 'detach' those descriptors, something like the following might occur:

int fd;  

fd = open("/dev/null",O_RDWR);  // missing from APUE exercise 3.4 example

if (fd != -1)   
{     
  dup2 (fd, 0);  // stdin  
  dup2 (fd, 1);  // stdout
  dup2 (fd, 2);  // stderr

  if (fd > 2) close (fd);  
}  

What this does is bind /dev/null' to each of the standard I/O descriptors and closes the temporary descriptor used to open /dev/null` in the first place (as long as that open didn't end up using one of the descriptors usually used for the standard I/O descriptors for some reason).

Now the daemon has valid stdin/stdout/stderr descriptors, but they aren't referring to a file or device that might interfere with another process.

This is mostly used in daemon programs because the daemon not connected with the terminal or tty. so for that we need maintain the error or printed statements in one file. for that only we were using this statements. In our system File descriptor 0,1,2 is already allocated for the standard buffers like stdin,etc...

Dup2 function is something different from dup function. In dup2 function we no need to close already using file descriptor.

In this dup2 function itself if the second argument file descriptors is already using means without close() function dup2 is closed the second argument fd and allocated a dup of first argument fd.

Then first argument fd is connected to second fd and do the first fd works

For example dup2(fd,1) means the file descriptor works are copied to the stdout. fd is contains any the statements is print the stdout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM