使用 popen 使用两个可执行文件在 C 中读取和写入



我知道popen不允许同时读写。

为了解决这个问题,我创建了两个文件,1.c用于写作,2.c用于阅读。这些文件包含在下面。

当我运行1.out时,我得到了stdout的预期输出:

bodhi@bodhipc:~/Downloads$ ./1.out
Stockfish 11 64 BMI2 by T. Romstad, M. Costalba, J. Kiiski, G. Linscott
bodhi@bodhipc:~/Downloads$

但是,2.out不会在stdout上给出任何输出:

bodhi@bodhipc:~/Downloads$ ./2.out
bodhi@bodhipc:~/Downloads$

我哪里出错了?

1.c:

#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{    
FILE *fp;
char path[1035];
/* Open the command for writing. */
fp = popen("./stockfish", "w");
if (fp == NULL) {
printf("Failed to run commandn" );
exit(1);
}
fprintf(fp,"ucin");
/* close */
pclose(fp);
return 0;
}

2.c:

#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("./1.out", "r");
if (fp == NULL) {
printf("Failed to run commandn" );
exit(1);
}
/* Read the output a line at a time - output it.*/
while (fgets(path, sizeof(path), stdout) != NULL) {
printf("%s", path);
printf("Done!n");
}
/* close */
pclose(fp);
return 0;
}
while (fgets(path, sizeof(path), stdout) != NULL) {

您不想从stdout中读取,而是:

while (fgets(path, sizeof(path), fp) != NULL) {

最新更新