我正在尝试在单个监听器进程中处理 4 个不同的命名 unix 管道。
我尝试使用 select 来处理管道的文件描述符。我以非阻塞模式打开了所有命名管道
我遇到了一个问题,select 根本没有休眠。不断循环运行。
我不知道我的代码哪里有问题。我在下面粘贴了我的代码。
始终保留 select 调用中的最后一个文件描述符,即使它在管道中没有内容。
请指出代码中有什么问题?
代码
管道打开调用(在构造函数中调用)
diag_fd = open(DIAG_PIPE , O_RDONLY | O_NONBLOCK );
主循环
while(1)
{
FD_ZERO(&fds);
FD_SET(cp_fd, &fds);
FD_SET(diag_fd, &fds);
FD_SET(err_fd, &fds);
FD_SET(perf_fd, &fds);
if (select(cp_fd+1, &fds, NULL, NULL, &tv) < 0)
{
perror("select");
return ;
}
for (int fd = diag_fd; fd <= cp_fd; fd++)
{
if (FD_ISSET(fd, &fds))
{
if (fd == diag_fd)
{
ProcessDiagLogs();
}
else if (fd == err_fd)
{
ProcessErrLogs();
}
else if (fd == perf_fd)
{
ProcessPerfLogs();
}
else if (fd == cp_fd)
{
ProcessCPLogs();
}
}
}
读取单个文件描述符中的调用:
ProcessDiagLogs()
do
{
if ((num = read(diag_fd, s, BUF_LENGTH)) == -1)
perror("read");
else {
s[num] = '\0';
fputs(s, filed);
fflush(filed);
}
} while (num > 0);
最佳答案
select() 允许您监视一个或多个文件描述符,等待其中一个变为“就绪”,即数据可用于。
const struct timespec *timeout
,tv
,在你的例子中指定了超时时间,或者他选择的日志如何等待数据返回(这表现得像一个 sleep )。如果超时为 0,则 select 立即返回,如果为 NULL
,则它可以无限期地阻塞。
您没有在代码中显示如何初始化电视,但我猜它为零,因此您看到的行为。
尝试在调用 select 之前初始化超时,看看是否有帮助:
tv.tv_sec = 1;//or any other value you see fit
tv.tv_usec= 0;
关于c - unix select 没有休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30234033/