简体   繁体   中英

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:

<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). 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. 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. 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.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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