如果我有两个线程(Linux,NPTL),其中一个正在轮询一个或多个文件描述符,另一个正在关闭其中一个文件描述符,这是合理的行为吗?我在MT环境中做了一些不应该做的事情吗?
我考虑这样做的主要原因是,我不必与轮询线程通信、中断它等,我只想出于任何原因关闭描述符,并且当轮询线程唤醒时,我希望revents包含POLLNVAL,这将表明下一次轮询前线程应该丢弃文件描述符。
我已经编写了一个简单的测试,确实显示POLLNVAL正是会发生的情况。然而,在这种情况下,只有当超时到期时才设置POLLNVAL,关闭套接字似乎不使poll()返回。如果是这样,我可以杀死线程使poll()重新启动并返回。
我考虑这样做的主要原因是,我不必与轮询线程通信、中断它等,我只想出于任何原因关闭描述符,并且当轮询线程唤醒时,我希望revents包含POLLNVAL,这将表明下一次轮询前线程应该丢弃文件描述符。
我已经编写了一个简单的测试,确实显示POLLNVAL正是会发生的情况。然而,在这种情况下,只有当超时到期时才设置POLLNVAL,关闭套接字似乎不使poll()返回。如果是这样,我可以杀死线程使poll()重新启动并返回。
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <poll.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
static pthread_t main_thread;
void * close_some(void*a) {
printf("thread #2 (%d) is sleeping\n", getpid());
sleep(2);
close(0);
printf("socket closed\n");
// comment out the next line to not forcefully interrupt
pthread_kill(main_thread, SIGUSR1);
return 0;
}
void on_sig(int s) {
printf("signal recieved\n");
}
int main(int argc, char ** argv) {
pthread_t two;
struct pollfd pfd;
int rc;
struct sigaction act;
act.sa_handler = on_sig;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGUSR1, &act, 0);
main_thread = pthread_self();
pthread_create(&two, 0, close_some, 0);
pfd.fd = 0;
pfd.events = POLLIN | POLLRDHUP;
printf("thread 0 (%d) polling\n", getpid());
rc = poll(&pfd, 1, 7000);
if (rc < 0) {
printf("error : %s\n", strerror(errno));
} else if (!rc) {
printf("time out!\n");
} else {
printf("revents = %x\n", pfd.revents);
}
return 0;
}