我正在创建访问设备驱动程序的用户程序。 多个线程必须打开设备? (每个线程都有一个设备本身的文件描述符)。或者可以从主体打开,所有线程都获得文件描述符的副本?
访问设备的原子性会发生什么变化?
答案 0 :(得分:1)
Linux中作为进程的线程是通过系统调用clone
创建的。来自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.
假设您正在使用库来创建 pthread 之类的线程。使用pthread_create
创建的线程与进程中的所有其他线程(不仅仅是父线程)共享文件描述符。这不能改变。使用fork
创建的进程获取文件描述符的副本。您必须注意共享文件描述符和拥有副本是两回事。如果您有一个副本(例如,使用fork
创建),则必须先关闭所有副本,然后才能关闭文件处理程序。如果文件描述符在不同的线程之间共享,一旦一个线程关闭它,该文件描述符将为所有线程关闭。同样,如果其中一个进程更改了其关联的标志(使用fcntl
),则另一个进程也会受到影响。