practical examples use dup or dup2

前端 未结 5 1497
滥情空心
滥情空心 2020-11-29 16:49

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

Any practical examples?

Thanks.

5条回答
  •  一向
    一向 (楼主)
    2020-11-29 17:12

    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.

提交回复
热议问题