dup2
doesn't return void
, it returns int
, so you should check its return code. If dup2
were failing for some reason and that was the problem then you wouldn't know about it. That being said, dup2
normally always works.
There is one corner case that could cause what you are seeing: if sockfd
is already 0. Then you'd be dup2
ing 0 to 0 and then closing 0, leaving you with no file descriptor at all. Therefore it's good practice before using dup2
to check whether or not the file descriptor you are trying to renumber is already numbered correctly. But again, this is not likely in your case than sockfd
is 0 to begin with.
That being also said, what you are trying to do should work. If it is not, then nobody can answer your question unless you clarify what you mean by "it is not working".