C dup2 pipe delay with stdout, how to fix?

80 views Asked by At

I can't figure out how to get rid of a delay, it seems like a buffering delay but I havent had any luck with setvbuf or fflush...

I have a c/c++ program that executes a python script which immediately starts printing to stdout (quite a bit), however there seems to be a huge delay when I try to read that input in my program. I have tried to include a basic version of what I am doing below. In the output I see TEST0 immediately and then after quite some time I get a huge dump of prints.... I tried setvbuff but that didnt seem to make a difference. I think either I am doing something wrong or just not understanding what's happening.

Update: I am running in Linux. Update2: fixed code typo with multiple forks Update3: Adding stdout flushes in the python script fixed the problem, no more delays! Thanks @DavidGrayson

int pipeFd[2];
pid_t pid;
char buff[PATH_MAX];
std::string path = "/user/bin/python3";
std::string script = "";//use path to python script here
std::string args = ""; //use args for python script here
  pid = fork();
  if( pid == -1)
  {
    printf( "[ERROR] cant fork\n" );
  }
  else if( pid == 0 )
  {
    close( pipeFd[0] );
    dup2( pipeFd[1], STDOUT_FILENO);
    close( pipeFd[1] );
    execl(path.c_str(), "python3", script.c_str(), args.c_str(), (char*)NULL );
    printf( "[ERROR] script execl failed\n" );
    exit(1);
  }
  else
  {
    //setvbuf(stdout, NULL, _IONBF, 0);
    //setvbuf(stdin, NULL, _IONBF, 0);
    printf( "TEST0\n" );
    fflush(stdout);
    //it takes a really long time to see this next print
    read( pipeFd[0], buff, 1 );
    printf( "TEST1:%c\n", buff[0] );
    fflush(stdout);
    
  }
0

There are 0 answers