我正在尝试使用 O_NONBLOCK 模式创建命名管道,并在单独的线程中使用“SELECT”方法侦听读取事件。当我在主线程中休眠一段时间后尝试关闭程序时出现问题。我希望当命名管道的文件描述符使用 close 方法关闭时,选择操作应该立即停止并返回一些值。但不幸的是,当文件描述符关闭并且执行选择方法的线程只是挂起时,选择操作没有反应......
任何想法如何解决它?示例代码如下。
#include <pthread.h>
#include <limits.h>
#include <cctype>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/shm.h>
#include <sys/time.h>
#include <sys/timeb.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <exception>
#define BUFFER PIPE_BUF
#define LPVOID void *
#define BOOL int
#define TRUE 1
#define CONST const
#define CHAR char
class CPipeTest
{
public:
int fd;
int nfd;
fd_set rfd;
pthread_t t;
CPipeTest() {};
~CPipeTest() {};
static LPVOID fnExecuteThread(LPVOID lpParam)
{
((CPipeTest*)lpParam)->fnRunThread();
return NULL;
}
BOOL fnRunThread()
{
printf("Going to listen...\r\n");
select(nfd, &rfd, NULL, NULL, NULL);
printf("Close listener...\r\n");
return TRUE;
}
void fnInit()
{
CONST CHAR * name = "./test_fifo1";
mkfifo(name, 0777);
fd = open(name, O_NONBLOCK | O_RDONLY);
nfd = fd + 1;
FD_ZERO(&rfd);
FD_SET(fd, &rfd);
pthread_create( &t, NULL, fnExecuteThread, (LPVOID)this);
sleep(30);
printf("Close file descriptor - listener should be closed automatically and immediately\r\n");
close(fd);
printf("Descriptor closed wait for thread to to be closed\r\n");
pthread_join(t, NULL);
printf("Thread is closed - everything is fine\r\n");
}
};
int main()
{
CPipeTest pi;
pi.fnInit();
return 0;
}