2

All, winter comes, plz keep warm and keep healthy. During the meditation about the work, I got some question about the function of fd dup2 . I create a socket server, and a client. the server send, the client receive data. But Now I want to dup2 the server socket fd to a file df in order to let the client read data directly from a file located in server. I write like

while(socketdf = accept(...))
{
 dup2(filefd , socketfd);
}

However, it doesnot work is this possible? Can you give me any advice on this? Thanx

StevenWang
  • 3,625
  • 4
  • 30
  • 40

1 Answers1

4

dup2() doesn't work like that -- what you're ending up doing here is closing socketfd and replacing it with a copy of filefd.

There is no way to directly plug a socket into a file like what you're trying to do here -- you will need to "pump" data from the file to the socket in your application. The sendfile() system call will simplify things considerably, though.

  • Sorry, `sendfile(2)` only works when the `in_fd` parameter supports `mmap(2)`-like operations -- no sockets allowed. – sarnold Nov 11 '11 at 05:29
  • Hrm, I interpreted the question the other way around -- I thought he wanted to let the server store data to a file that he could feed to clients at a later date. (By the way, cool dog graviwhatsit.) – sarnold Nov 11 '11 at 05:34
  • The critical wording I saw was "let the client read data directly from a file located in server". That part seems pretty unambiguous. –  Nov 11 '11 at 05:38
  • Hahaha, amazing, we both thought we had unambiguous interpretations that are polar opposites. I sure hope you're right, it'll be way easier for him if you are. :) – sarnold Nov 11 '11 at 05:42
  • Beware that `sendfile(2)` is `Not specified in POSIX.1-2001, or other standards. Other UNIX systems implement sendfile() with different semantics and prototypes. It should not be used in portable programs.` according to the man page. – glglgl Nov 11 '11 at 06:52
  • @duskwuff: hi, what if it is a shared memory fd? not a file fd – StevenWang Nov 11 '11 at 07:52
  • @Macroideal: whatever fd it would be, dup2() effectively does close(oldfd); copy(newfd, oldfd); and you will have your socket closed. No luck and no easy way here. – blaze Nov 11 '11 at 08:13