简体   繁体   English

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

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

I am trying to write a function in C that checks the presence of stdin using poll()我正在尝试在 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");
    }
}

Here fds.fd=0 refers to file descriptor for STDIN.这里fds.fd=0指的是 STDIN 的文件描述符。 fds.events = POLLIN refers to the event that there is data to read. fds.events = POLLIN是指有数据可读的事件。 I am using a timeout of 10 milliseconds.我使用 10 毫秒的超时。 When I run当我跑步时

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

where test_stdin is the object file for the C program, I get the output其中test_stdin是 C 程序的 object 文件,我得到 output

Return value: 0
stdin could not be read

The value of ret should be 1 if there was data found to be read in the STDIN.如果在 STDIN 中发现要读取的数据,则ret的值应为 1。 Is the STDOUT from jq not considered as STDIN for ./test_stdin here?来自jq的 STDOUT 在这里不被视为./test_stdin的 STDIN 吗?

You have a race condition in your shell pipeline.您的 shell 管道中存在竞争条件。

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

You're telling poll() to wait for 10 milliseconds before timing out.您告诉poll()在超时之前等待 10 毫秒。 jq wasn't producing any output in that short time when you tested it (Didn't for me either). jq在你测试它的那段短时间内没有产生任何 output (对我来说也没有)。 If you use a longer timeout, say 500 milliseconds, you'll likely see如果您使用更长的超时时间,比如 500 毫秒,您可能会看到

Return value: 1

as the output instead.作为 output 而不是。

Commands in a pipeline are all run concurrently, and what order they execute in is dependent on your OS's scheduler.管道中的命令都是同时运行的,它们执行的顺序取决于操作系统的调度程序。 So the C program at the end might actually be ending before jq even starts to execute.所以最后的 C 程序实际上可能在jq开始执行之前就结束了。 If programs intended for use in a pipeline use blocking reads, they'll never notice, but with that very short timeout, you're seeing the effects.如果打算在管道中使用的程序使用阻塞读取,他们将永远不会注意到,但在非常短的超时时间内,您会看到效果。

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

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