0

我正在创建访问设备驱动程序的用户程序。多个线程必须打开设备?(每个线程都有一个设备本身的文件描述符)。或者可以从主体打开,所有线程都得到文件描述符的副本?

访问设备的原子性会发生什么?

4

1 回答 1

1

Linux 中作为进程的线程是通过系统调用创建的clone。从其文档中

 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.

假设您正在使用库来创建像pthread这样的线程。创建pthread_create的线程与进程中的所有其他线程(不仅仅是父线程)共享文件描述符。这是无法改变的。fork使用获取文件描述符副本创建的进程。您必须注意到共享文件描述符和拥有副本是两件不同的事情。如果您有一个副本(例如使用 创建的fork),则必须在文件处理程序明确关闭之前关闭所有副本。如果一个文件描述符在不同的线程之间共享,一旦一个线程关闭它,这个文件描述符将对所有线程关闭。同样,如果其中一个进程更改其关联标志(使用fcntl),则另一个进程也会受到影响。

于 2013-10-31T20:24:48.383 回答