Question

I am creating user programs that access a device driver. Multiple threads must open the device? (each thread has a file descriptor of the device itself). Or can be opened from the principal and all the threads get a copy of the file descriptor?

What happens to the atomicity in access to the device?

Was it helpful?

Solution

A thread in Linux as a process is created via the system call clone. From its documentation :

 If CLONE_FILES is set, the calling process and the child
          process share the same file descriptor table.  Any file
          descriptor created by the calling process or by the child
          process is also valid in the other process.  Similarly, if one
          of the processes closes a file descriptor, or changes its
          associated flags (using the fcntl(2) F_SETFD operation), the
          other process is also affected.

          If CLONE_FILES is not set, the child process inherits a copy
          of all file descriptors opened in the calling process at the
          time of clone().  (The duplicated file descriptors in the
          child refer to the same open file descriptions (see open(2))
          as the corresponding file descriptors in the calling process.)
          Subsequent operations that open or close file descriptors, or
          change file descriptor flags, performed by either the calling
          process or the child process do not affect the other process.

Assuming that you are using a library to create a thread like pthread. Threads created with pthread_create share the file descriptors with all other threads in the process (not just the parent). This cannot be changed. While process created with fork get a copy of the file descriptor. You must notice that sharing a file descriptor and having a copy are two different things. If you have a copy ( for example created with fork) then all copies must be closed before the file handler is definitely closed. If a file descriptor is shared among different threads, once one thread closes it, this file descriptor will be closed for all thread. Similarly, if one of the processes changes its associated flags (using the fcntl), the other process is also affected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top