繁体   English   中英

poll() function 试图检测来自 jq 的标准输出

[英]poll() function trying to detect stdout from jq

我正在尝试在 C 中编写一个 function,它使用poll()检查标准输入的存在

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

\\other code

void check_stdin(){
    struct pollfd fds;
    int ret; fds.fd = 0; fds.events = POLLIN;
    ret = poll(&fds, 1, 10);
    printf("Return value: %d\n", ret);
    if(ret != 1){
        printf("stdin could not be read\n");
    }
}

这里fds.fd=0指的是 STDIN 的文件描述符。 fds.events = POLLIN是指有数据可读的事件。 我使用 10 毫秒的超时。 当我跑步时

echo "{\"key\": 1}" | jq .key | ./test_stdin

其中test_stdin是 C 程序的 object 文件,我得到 output

Return value: 0
stdin could not be read

如果在 STDIN 中发现要读取的数据,则ret的值应为 1。 来自jq的 STDOUT 在这里不被视为./test_stdin的 STDIN 吗?

您的 shell 管道中存在竞争条件。

ret = poll(&fds, 1, 10);

您告诉poll()在超时之前等待 10 毫秒。 jq在你测试它的那段短时间内没有产生任何 output (对我来说也没有)。 如果您使用更长的超时时间,比如 500 毫秒,您可能会看到

Return value: 1

作为 output 而不是。

管道中的命令都是同时运行的,它们执行的顺序取决于操作系统的调度程序。 所以最后的 C 程序实际上可能在jq开始执行之前就结束了。 如果打算在管道中使用的程序使用阻塞读取,他们将永远不会注意到,但在非常短的超时时间内,您会看到效果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM