我如何等待n秒才能打开命名管道?

问题描述 投票:-4回答:1

我有一个程序,当我无法打开管道进行读取时,我想要退出,在N(比如说30秒)之后。

我的代码使用阻塞名称管道,我不能改变它。

我知道select()和poll()但是如果不把我的管道变成非阻塞的话我就无法工作。

到目前为止这是我的代码:

struct pollfd fds[1];
int pol_ret;

fds[0].fd = open(pipe_name, O_RDONLY /* | O_NONBLOCK */);

if (fds[0].fd < 0)
{
    // send_signal_to_parent();
    std::cout << "error while opening the pipe for read, exiting!" << '\n';
    return -1;
}

fds[0].events = POLLIN;

int timeout_msecs = 30000;    //  (30 seconds)
pol_ret = poll(fds, 1, timeout_msecs);

std::cout << "poll returned: "<< pol_ret << '\n';
 if (pol_ret == 0)
 {
     std::cout << "im leaving" << '\n';
     return -1;    
 }

如何打开管道进行读取,我怎能等待30秒?

我正在运行Linux,尤其是debian。

c++ linux named-pipes polling
1个回答
0
投票

设置一个带有信号处理程序的计时器,并在fifo上打开等待调用。如果open与errno=EINTR失败并且您的处理程序运行,则open调用被您的计时器中断,即它超时。

示例代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>

volatile sig_atomic_t abort_eh;
void handler(int Sig)
{
    abort_eh = 1;
}

int main()
{
    struct sigaction sa;
    sa.sa_flags = 0;
    sa.sa_handler = handler;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGALRM,&sa,0);

    //try to ensure the fifo exists
    (void)mkfifo("fifo",0600);

    //open with a timeout of 1s
    alarm(1);

    int fd;
    do{
        if (0>(fd=open("fifo",O_RDONLY)))
            if(errno==EINTR){
                if(abort_eh) return puts("timed out"),1;
                else continue; //another signal interrupted it, so retry
            }else return perror("open"),1;
    }while(0);

    alarm(0); //cancel timer
    printf("sucessfully opened at fd=%d\n", fd);

}

setitimertimer_create / timer_settime提供比alarm更好的更细粒度的计时器。他们还可以设置定时器重复,这允许你在第一个信号“错过”的情况下重新信号(即,在输入open之前运行,因此无法打破可能无限期阻塞的系统调用)。

© www.soinside.com 2019 - 2024. All rights reserved.