practical examples use dup or dup2

pierrotlefou picture pierrotlefou · Nov 12, 2009 · Viewed 91.6k times · Source

I know what dup / dup2 does, but I have no idea when it would be used.

Any practical examples?

Thanks.

Answer

Alfonso picture Alfonso · Nov 12, 2009

One example use would be I/O redirection. For this you fork a child process and close the stdin or stdout file descriptors (0 and 1) and then you do a dup() on another filedescriptor of your choice which will now be mapped to the lowest available file descriptor, which is in this case 0 or 1.

Using this you can now exec any child process which is possibly unaware of your application and whenever the child writes on the stdout (or reads from stdin, whatever you configured) the data gets written on the provided filedescriptor instead.

Shells use this to implement commands with pipes, e.g. /bin/ls | more by connecting the stdout of one process to the stdin of the other.