Ritesh Singh
Ritesh Singh

Reputation: 279

Using popen to read and write in C using two executables

I understand that popen doesn't allow simultaneous read and write.

To get around this, I created two files, 1.c for writing, and 2.c for reading. The files are included below.

When I run 1.out, I get the expected output on stdout:

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

However, 2.out doesn't give any output on stdout:

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

Where am I going wrong?

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;
}

Upvotes: 2

Views: 894

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

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

you don't want to read from stdout, instead:

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

Upvotes: 4

Related Questions