首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用popen使用两个可执行文件在C中读写

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

Stack Overflow用户
提问于 2020-06-27 20:50:08
回答 1查看 106关注 0票数 2

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

为了解决这个问题,我创建了两个文件,一个用于写入的1.c文件,一个用于读取的2.c文件。这些文件包括在下面。

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

代码语言:javascript
复制
bodhi@bodhipc:~/Downloads$ ./1.out
Stockfish 11 64 BMI2 by T. Romstad, M. Costalba, J. Kiiski, G. Linscott
bodhi@bodhipc:~/Downloads$

但是,2.out没有在stdout上提供任何输出

代码语言:javascript
复制
bodhi@bodhipc:~/Downloads$ ./2.out
bodhi@bodhipc:~/Downloads$

我哪里出问题了?

1.c:

代码语言:javascript
复制
#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:

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-27 20:53:30

代码语言:javascript
复制
  while (fgets(path, sizeof(path), stdout) != NULL) {

您不想从stdout上读到,相反:

代码语言:javascript
复制
  while (fgets(path, sizeof(path), fp) != NULL) {
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62615429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档