linux - Usage of dup2() -


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

according book advanced programming in unix environment, if statement above necessary. book suggests work through considering happen if fd = 1 in 1 case, , if fd = 3 in another.

if fd = 1, 0 (stdin) closed , point @ stdout, 1 still point @ stdout (since dup2() doesn't close file descriptor if it's equal first argument, , return 1) , 2 point @ stdout.

if fd = 3, every file descriptor first closed , point @ whatever file 3 points at.

why necessary close descriptor if it's greater 2?

the purpose of dup2 call copy first file descriptor second. after 3 calls dup2, file descriptors 0, 1, , 2 open , copies of file descriptor fd. subsequent call close closes original file descriptor.

if didn't check fd > 2 prior calling close(fd), closing 1 of file descriptors opened. example, if fd 2 close(fd) same close(2).

it doesn't make close file descriptor right after opening , not doing it. that's why check necessary.


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -