Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: dup() & sockets
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: dup() & sockets



At 12:29 -0700 10/8/03, Duane Murphy wrote:
If I need more than one socket, for example one per ethernet port, can I
dup() the one returned from the authenticated process and use it separately?

I don't think so. There's an extra level of fan-in at the descriptor level you're not accounting for. Each process has a descriptor table, and each entry in the descriptor table points to a filedesc structure which in turn points to the socket structure. When you dup a descriptor, both descriptors end up pointing to the same filedesc structure, which continues to point to the one socket structure. Given that the socket-specific information (such as the address that you're bound to) hangs off the socket structure, changes made via one of the dup'd descriptors will be visible in the other.

This is easy to demonstrate for file descriptors. The following program prints 1024, not 0 as you might expect.

#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>

int main (int argc, const char * argv[])
{
int fd;
int fd2;
off_t off;
fprintf(stderr, "Hello Cruel World!\n");
fd = open("/mach_kernel", O_RDONLY, 0);
assert(fd > 0);

fd2 = dup(fd);
assert(fd2 > 0);

off = lseek(fd2, 0, SEEK_CUR);
fprintf(stderr, "off before = %qd\n", off);
off = lseek(fd, 1024, SEEK_SET);
assert(off == 1024);
off = lseek(fd2, 0, SEEK_CUR);
fprintf(stderr, "off after = %qd\n", off);

return 0;
}

S+E
--
Quinn "The Eskimo!" <http://www.apple.com/developer/>
Apple Developer Technical Support * Networking, Communications, Hardware
_______________________________________________
macnetworkprog mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/macnetworkprog
Do not post admin requests to the list. They will be ignored.

References: 
 >dup() & sockets (From: "Duane Murphy" <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.