Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 轮询返回0,但读取不阻塞_C++_C_Polling - Fatal编程技术网

C++ 轮询返回0,但读取不阻塞

C++ 轮询返回0,但读取不阻塞,c++,c,polling,C++,C,Polling,我研究这段代码已经有一段时间了,出于某种原因,poll返回零,即使有数据要从outpds管道读入。出于某种原因,如果我读入一些数据,然后运行poll,它将返回正确的值,但这不是一个解决方案。以前有没有人见过这个,知道我该怎么做 #include <stdio.h> #include <stdlib.h> #include <sys/poll.h> int main(void) { int outFds[2]; pipe(outFds);

我研究这段代码已经有一段时间了,出于某种原因,poll返回零,即使有数据要从outpds管道读入。出于某种原因,如果我读入一些数据,然后运行poll,它将返回正确的值,但这不是一个解决方案。以前有没有人见过这个,知道我该怎么做

#include <stdio.h>
#include <stdlib.h>
#include <sys/poll.h>

int main(void)
{
    int outFds[2];

    pipe(outFds);

    if(!fork()) {
        dup2(outFds[1], 1);

        close(outFds[0]);
        close(outFds[1]);

        // disable printf buffering
        setvbuf(stdout, NULL, _IONBF, 0);

        sleep(1);
        char buf[32];
        printf("blah");

        exit(0);
    }

    close(outFds[1]);

    char c;
    // Read 'b' into c. If this next line is not commented poll returns 1
    //read(outFds[0], &c, 1); 

    struct pollfd outFd;
    outFd.fd = outFds[0];
    outFd.events = POLLIN;
    printf("%d\n", poll(&outFd, 1, 0)); // poll returns 0 for some reason
}
#包括
#包括
#包括
内部主(空)
{
int OUTPDS[2];
管道(出口);
如果(!fork()){
dup2(OUTPDS[1],1);
关闭(输出[0]);
关闭(出口[1]);
//禁用printf缓冲
setvbuf(标准输出,空,0);
睡眠(1);
char-buf[32];
printf(“废话”);
出口(0);
}
关闭(出口[1]);
字符c;
//将“b”读入c。如果下一行没有注释,则轮询返回1
//读取(OUTPDS[0],&c,1);
结构pollfd outd;
outFd.fd=outFds[0];
outpd.events=POLLIN;
printf(“%d\n”,poll(&outpd,1,0));//由于某种原因,poll返回0
}
从手册页:

指定超时为零会导致poll()立即返回,甚至 如果没有准备好文件描述符


我将其理解为一个timespec结构,其中
tv\u sec
tv\u nsec
设置为
0
,但似乎将
nullptr
放入具有相同效果。

似乎是在孩子写入管道之前进行的
poll
。您是否尝试在
轮询
之前放置另一个
睡眠
?“轮询返回零,即使有数据要从OutPDS管道读入”。您如何知道有数据要读取?代码中的任何内容都不能保证子
printf
在父
poll
之前执行。尤其是因为在调用
printf
之前,您在孩子身上有一个
睡眠
。所以我的钱在
民意测验上了
表现正确,而你的假设不正确。谢谢艾伦!我知道现在我睡错了地方,这就解释了为什么读取一个字节就可以解决这个问题。不知怎么的,我忘了读块哈哈。