fgets 在使用 popen 执行的程序完成后读取行**
fgets reads lines **after** program executed with popen finishes
程序sdh:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void main(void) {
FILE *fp = popen("/path/to/asd", "r");
char str[256];
while (fgets(str, sizeof(str), fp) != NULL) {
printf("%s", str);
}
}
程序asd:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
void main(void) {
printf("A\n\r");
sleep(1);
printf("B\n\r");
}
当运行程序sdh时,等待1秒然后打印
A
B
我希望它做的是打印
A
,等待1秒,然后打印
B
换句话说,程序 asd 在 fgets
设法读取第一行之前完成。我应该如何修改它才能在打印后立即阅读这些行?
标准输出流 (stdout) 默认情况下被缓冲,只要缓冲区已满就会被刷新。在 printf 中换行会立即刷新
仅当输出为 console/terminal 时。但在你的情况下,它会进入管道,因此不会被冲洗掉。
在每个 printf 语句(在 "asd" 程序中)之后添加 fflush(stdout);
将提供所需的行为,即立即从 stdio 缓冲区刷新输出。
但是如果您不想使用 stdio 缓冲,则可以使用 setbuf(3)
完全禁用它。例如,在"asd"程序的开头添加setbuf(stdout, NULL);
。
或者,如果您使用的是 unixy 系统,您也可以使用 write(2)
系统调用,它根本不会缓冲。
程序sdh:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void main(void) {
FILE *fp = popen("/path/to/asd", "r");
char str[256];
while (fgets(str, sizeof(str), fp) != NULL) {
printf("%s", str);
}
}
程序asd:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
void main(void) {
printf("A\n\r");
sleep(1);
printf("B\n\r");
}
当运行程序sdh时,等待1秒然后打印
A
B
我希望它做的是打印
A
,等待1秒,然后打印
B
换句话说,程序 asd 在 fgets
设法读取第一行之前完成。我应该如何修改它才能在打印后立即阅读这些行?
标准输出流 (stdout) 默认情况下被缓冲,只要缓冲区已满就会被刷新。在 printf 中换行会立即刷新 仅当输出为 console/terminal 时。但在你的情况下,它会进入管道,因此不会被冲洗掉。
在每个 printf 语句(在 "asd" 程序中)之后添加 fflush(stdout);
将提供所需的行为,即立即从 stdio 缓冲区刷新输出。
但是如果您不想使用 stdio 缓冲,则可以使用 setbuf(3)
完全禁用它。例如,在"asd"程序的开头添加setbuf(stdout, NULL);
。
或者,如果您使用的是 unixy 系统,您也可以使用 write(2)
系统调用,它根本不会缓冲。