简体   繁体   English

在多线程程序中关闭文件描述符

[英]Closing file descriptor in multithreaded program

I have a thread I made to accept incoming connections with: 我有一个线程可以接受传入的连接:

pthread_t thread;

pthread_create(&thread, NULL, worker_func, NULL);
pthread_detach(thread);

Then worker_func does: 然后worker_func执行:

<snip>
fd = accept(GlobalFD, NULL, NULL);
<snip>

However, If I try to close GlobalFD in my original thread, accept will still block (I want it to fail if GlobalFD is closed). 但是,如果我尝试在原始线程中关闭GlobalFD ,则accept仍然会阻塞(如果关闭GlobalFD ,我希望它失败)。 I've looked online and at other questions and can't seem to find the answer to my particular problem. 我在网上看过其他问题,但似乎找不到我特定问题的答案。

Any ideas? 有任何想法吗? Thanks 谢谢

Different threads of the same program share memory, including file descriptor tables. 同一程序的不同线程共享内存,包括文件描述符表。 If one thread closes an FD then it is closed for all other threads, too. 如果一个线程关闭了FD,那么其他所有线程也都关闭了。 This is one of the differences between using multiple threads and using multiple processes. 这是使用多个线程和使用多个进程之间的区别之一。 Therefore, do not allow one thread to close a file descriptor that another is relying upon to remain open. 因此,不允许一个线程关闭另一个依赖的文件描述符以保持打开状态。

More generally, however, you must take great care about modifying shared data. 但是,更一般而言,您必须非常注意修改共享数据。 Generally speaking, you must synchronize access via a semaphore, a condition variable, or some other construct or action with significance for synchronization. 一般来说,您必须通过信号量,条件变量或其他对同步有意义的构造或操作来同步访问。 Program behavior is otherwise not well defined. 否则,程序行为将无法很好地定义。 In particular, you cannot expect that closing a file descriptor will cause an active I/O function running in a different thread to terminate. 特别是,您不能期望关闭文件描述符会导致在其他线程中运行的活动I / O函数终止。 Send the target thread a signal instead. 向目标线程发送信号。

In general, closing a file-descriptor in one thread isn't guaranteed to cause a function that's waiting on that file-descriptor in another thread to return. 通常,不能保证在一个线程中关闭文件描述符会导致正在另一个线程中等待该文件描述符的函数返回。

Your options are 1) install a signal handler and use pthread_kill() (don't forget to check the return-code of the blocked function) and 2) create a "termination file-descriptor" that is also passed to the select() or poll() function and either close it or write to it in the other thread. 您的选择是1)安装信号处理程序并使用pthread_kill()(不要忘记检查被阻止函数的返回码),以及2)创建“终止文件描述符”,该文件也将传递给select()或poll()函数,然后在另一个线程中将其关闭或写入。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM