使用popen在C中使用两个可执行文件进行读写

Using popen to read and write in C using two executables

我了解 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 command\n" );
    exit(1);
  }

  fprintf(fp,"uci\n");

  /* 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 command\n" );
    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) {