我知道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) {