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 ?
-
2Using `write()` to FD 0 writes to whaever 0 is connected to. If it's a socket, it isn't `stdin`, and it can't 'mess up the output of your application'. It isn't clear that you have a problem to solve. – user207421 Feb 19 '17 at 06:59
-
1The returnvalue from socketpair is **not** a file descriptor, it is a status code (-1 or 0), meaning failure or success. – wildplasser Feb 19 '17 at 15:18
-
My bad, I meant to say that the socket is allocated the file descriptor 0,1 or 2. – Shekhar Bhandakkar Feb 20 '17 at 08:08
1 Answers
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).

- 730,956
- 141
- 904
- 1,278
-
You are right, I was never closing the STD*. The problem was somewhere else. – Shekhar Bhandakkar Feb 19 '17 at 06:50