0

I have one file descriptor(basically socket descriptor) example sockfd. I use dup2 to command (void) dup2(sockfd,0);

then i close the descriptor close(sockfd);

Now i try to receive message on receive recv(0,buf,sizeof(buf),0);

But it is not working whats wrong with it?

user
  • 2,694
  • 6
  • 24
  • 25
  • In addition to Celada's answer below, and slightly off-topic, but still important: You seem to have misunderstood what `sizeof(buf)` actually does. `buf` is a pointer to a buffer, so its size will mostly likely always be 4 (32 bit) or 8 (64 bit), and *not* the size allocated by the buffer. – ayekat Mar 19 '15 at 12:15
  • @ayekat `sizeof(buf)` will work fine if `buf` is, for example, an array local variable. For example, if it's declared in the same function as `char buf[30];` then `sizeof(buf)` will be 30. That's actually very common for buffers that are used with `read`, `recv`, etc... – Celada Mar 19 '15 at 12:27

1 Answers1

7

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 dup2ing 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".

Celada
  • 21,627
  • 4
  • 64
  • 78