I am using socketpair() system call for IPC and it returns 0,1 or 2 file descriptor if any of them is available. Using write() system call for fd 0 writes to the STDIN thereby messing up the output of my application. Is there something I can do to prevent the socketpair() from returning 0,1 or 2 as fd ?
Don't close standard input, standard output or standard error before using socketpair()
. If necessary, open /dev/null
for those file descriptors.
When file descriptors are allocated (by any system call — open()
, socket()
, socketpair()
, accept()
, pipe()
, dup()
, etc), the number used is always the lowest available (unopen) number. If you're getting 0, 1 or 2 allocated by socketpair()
, it means you must have closed the corresponding descriptor — but why did you do that? Never mind; don't do it.
Or fix it by opening /dev/null
. Remember that 0 should be readable and 1 and 2 should be writable (and that it doesn't matter if 0 is writable and 1 and 2 are readable; indeed, when a shell is started in a terminal, all three are often readable and writable).