Python Popen输出到c程序,fget在循环中读取相同的stdin

时间:2015-01-20 15:47:18

标签: python c subprocess popen fgets

我希望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);
    }

}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

由于您没有停止条件,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);
}