-1

My C++ program creates a subprocess to call a python script that does not terminate, but I also want to know what's happening in that subprocess by retrieving its (the python subprocess) stdout in my main program C++. I have the following code. In this case, I am only interested in the first line of stdout of the python program.

FILE *fp;
char *line = (char*)malloc(1024 * sizeof(char));
int index = 0;
char c;

fp = popen("python testing.py run_for_long_time", "r");
while (true)
{
    c = fgetc(fp);
    if (c == '\n') {
        break;
    }
    line[index++] = c;
}
line[index] = '\0';
printf("Finished\n");

I noticed that the code does not print out finished until the subprocess has terminated (but I am only interested in the first line of the subprocess stdout so I don't want to wait for subprocess termination). How can I do this with popen and file descriptor?

vda8888
  • 689
  • 1
  • 8
  • 19
  • Do you still want to *run* the whole subprocess (until the end), or would you be fine with just killing the subprocess after it has written the first line? In the latter case, you could pipe the output of your python program through "head". – Oguk Nov 12 '14 at 19:34
  • I still want to run the whole subprocess till the end but don't want to waste time waiting for it to terminate. – vda8888 Nov 12 '14 at 19:35
  • Not reproducible [live demo](http://coliru.stacked-crooked.com/a/6c71d48edc548e2a). Post a minimal self-contained example. (You cannot run the subprocess to the end like that, but that's another issue) – n. m. could be an AI Nov 12 '14 at 19:39
  • Might be because the subprocess does not use a line buffering (or maybe outputs newlines in an unusual way). Try running it with "python -u", cf. http://stackoverflow.com/questions/107705/python-output-buffering – ArtemGr Nov 12 '14 at 22:19
  • Please don't put answers in questions ;0 – BartoszKP Nov 12 '14 at 22:59

1 Answers1

0

Thanks to @ArtemGr, it turns out that I just need to enable python buffering. See Disable output buffering

Community
  • 1
  • 1
vda8888
  • 689
  • 1
  • 8
  • 19