Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Creating a New Thread Duplicate File Descriptors and Socket Descriptors in Linux?

Everyone knows the classic model of a process listening for connections on a socket and forking a new process to handle each new connection. Normal practice is for the parent process to immediately call close on the newly created socket, decrementing the handle count so that only the child has a handle to the new socket.

I've read that the only difference between a process and a thread in Linux is that threads share the same memory. In this case I'm assuming spawning a new thread to handle a new connection also duplicates file descriptors and would also require the 'parent' thread to close it's copy of the socket?

like image 707
Robert S. Barnes Avatar asked Oct 05 '09 19:10

Robert S. Barnes


People also ask

Do Threads share the same file descriptors?

The file descriptors are shared between the threads. If you want "thread specific" offsets, why not have each thread use a different file descriptor ( open(2) multiple times) ?

What are the differences between sockets and file descriptors?

The system returns an integer, the socket descriptor (sd), that the application uses every time it wants to refer to that socket. The main difference between sockets and files is that the operating system binds file descriptors to a file or device when the open() call creates the file descriptor.

Are file descriptors thread safe?

Any system level (syscall) file descriptor access is thread safe in all mainstream UNIX-like OSes.

What is the role of file descriptors during socket creation?

A file descriptor is a number that uniquely identifies an open file in a computer's operating system. It describes a data resource, and how that resource may be accessed. When a program asks to open a file — or another data resource, like a network socket — the kernel: Grants access.


1 Answers

In principle, Linux clone() can implement not only a new process (like fork()), or a new thread (like pthread_create perhaps), but also anything in between.

In practice, it is only ever used for one or the other. Threads created with pthread_create share the file descriptors with all other threads in the process (not just the parent). This is non-negotiable.

Sharing a file descriptor and having a copy is different. If you have a copy (like fork()) then all copies must be closed before the file handle goes away. If you share the FD in a thread, once one closes it, it's gone.

like image 122
MarkR Avatar answered Oct 17 '22 01:10

MarkR