【问题标题】:Python Popen output to a c program, fget read the same stdin in a loopPython Popen输出到c程序,fget在循环中读取相同的stdin
【发布时间】:2015-03-18 22:16:05
【问题描述】:

我希望 c 程序打印收到的 3 行。但结果是c程序不停地打印from c program:33333333。我不知道为什么fgets()在执行后没有消耗stdin

# pin.py
from subprocess import Popen, PIPE
p = Popen("/home/jchn/pstdin",stdin=PIPE,stdout=None)
p.stdin.write("11111111")
p.stdin.write("22222222")
p.stdin.write("33333333")

pstdin.c的内容

# pstdin.c
#include <stdio.h>

int main(){
    char a[10];
    FILE* fd = fopen("output","w");
    while (1){  
        fgets(a,10,stdin);
        printf("--from c program--:%s",a);
    }

}

【问题讨论】:

    标签: python c subprocess popen fgets


    【解决方案1】:

    while(1) 是一个无限循环,你没有停止条件

    while(fgets(a,10,stdin) != NULL)
    {
      printf("--from c program--:%s",a);
    }
    

    【讨论】:

    • 我认为 fgets() 会阻塞等待,直到给出新的标准输入。
    • @jvchn 你正在做 fgets() 这是正确的,但在 while(1) 中这样做是不对的,因为你没有退出条件
    • @jvchn:如果fgets() 失败,您不会像在 Python 中那样遇到异常。您必须检查其返回值以检测 EOF 或错误(您可以使用feof()ferror() 来区分两者)。
    【解决方案2】:

    由于您没有停止条件,fgets() 无法读取,但a 数组仍然包含最后一个字符串,即"33333333",因此它会继续打印。

    当没有更多要阅读的内容时,fgets() 返回 NULL,因此您可以按照 Gopi 已经提到的方式进行检查。

    如果你这样做,你的 c 程序会运行良好

    # pstdin.c
    #include <stdio.h>
    
    int main(){
        char a[10];
        FILE* fd = fopen("output","w");
        if (fd == NULL)
            return -1; /* check this before accessing the file please */
        while (fgets(a, 10, stdin))
            printf("--from c program--:%s",a);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 2013-11-30
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 2017-11-21
      • 2012-03-27
      相关资源
      最近更新 更多