linux - 关于 pthread_create 和文件描述符,我可以假设什么?

标签 linux pthreads posix file-descriptor

我刚调试了一个程序,大致做了:

pthread_create(...);
close(0);
int t = open("/named_pipe");
assert(t == 0);

有时它会失败,因为 pthread_create 实际上会在新线程上短暂地打开文件描述符——特别是 /sys/devices/system/cpu/online——如果你在上面的 closeopen 之间发生了不幸,使得 t 不是 0。

执行此操作最安全的方法是什么?如果关于文件描述符的 pthread_create 有任何保证怎么办?我是否可以保证如果在我调用 pthread_create 之前打开了 3 个文件描述符,那么当它返回并且控制权已传递到新线程上的我的函数时也会有 3 个打开?

最佳答案

在多线程程序中,需要使用dup2 or dup3替换文件描述符。 close 后立即重用的旧技巧不再有效,因为其他线程随时创建文件描述符。此类文件描述符甚至可以由 glibc 隐式创建(和关闭),因为许多内核接口(interface)都使用文件描述符。

dup2 是标准接口(interface)。 Linux 也有 dup3,您可以使用它自动创建带有 O_CLOEXEC 标志集的文件描述符。否则,仍然会存在竞争条件,并且如果进程 fork 并执行新程序,则描述符可能会泄漏到子进程。

关于linux - 关于 pthread_create 和文件描述符,我可以假设什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51073449/

相关文章:

c++ - 在 64 位 Ubuntu 中使用 pthread 从 void* 转换为 int

c - 使用 int 到 void * 转换避免竞争条件

linux - bash_profile 中的更改未反射(reflect)在 linux 中

c - 为什么 Linux 在目录上使用 getdents() 而不是 read()?

C++ - 在后台 POSIX 线程上以固定增量时间循环

android - pthread_cond_wait 是完全信号安全的吗?

c - putwchar/getwchar 编码?

windows - 配置 Visual Studio 2008 以编译 Posix 应用程序

c - 如何检查套接字的另一端是否已被接受?

linux - shell脚本中的 sleep 间隔