C:如何在 flock 上添加超时?

C: How to add timeout on flock?

在C编程中,有没有办法实现flock()超时?

谢谢。

#include <sys/file.h>

int flock(int fd, int operation);

您可以使用 SIG_ALARM 来完成。 http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html 不过这有点棘手,尤其是当您处理多个线程时。您必须确保您的系统始终将 sig 警报传递给设置它的线程,但情况可能并非如此……在这种情况下,您需要使用 pthread_sigmask http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_sigmask.html 确保只有你的线程启用了信号......但是如果 2 个线程同时阻塞在 flock 上怎么办?您需要为此添加某种互斥包装器。