Reputation: 31
I am trying to create server which accepts multiple clients using c socket prog. but manytimes when client connects, sockfd=accept()
returns 0 (zero) which is stdin
fd.
As far as I know file descriptor returns minimum value which not in use, so it may returning 0 . But when I try to listen on sockfd (which is 0) or send()
to sockfd
it do nothing and both returns 0.
How can I overcome this?
I am working on RaspberryPi Raspbian (debian).
Upvotes: 3
Views: 4307
Reputation: 133899
It is behaviour on POSIX that the file descriptor returned from a function is the smallest available file descriptor. If you've closed STDIN_FILENO
or stdin
, then 0
could be available, and would be the one returned by connect
.
Note that there is nothing special about file descriptor 0; that it is used for standard input is just a convention only; and accept
(2) manual on Linux explicitly uses the word nonnegative which includes the possibility of it returning 0
:
RETURN VALUE
On success, these system calls return a nonnegative integer that is a descriptor for the accepted socket. On error, -1 is returned, and errno is set appropriately.
You can avoid this by not closing STDIN_FILENO
, but opening say /dev/null
for reading and dup2:n this file descriptor to STDIN_FILENO
(error checking omitted for brevity):
int fd = open("/dev/null", O_RDONLY);
dup2(fd, STDIN_FILENO);
close(fd);
(or closing STDIN_FILENO
and then immediately afterwards opening /dev/null
, but this is a bit obscure):
close(STDIN_FILENO);
open("/dev/null", O_RDONLY);
I am not sure what you mean by listen
; a connected TCP socket couldn't be listen
ed. Also, 0
from send
would mean that you're explicitly sending 0 bytes; because on error -1
would be returned instead.
Upvotes: 4