0

I'm trying to write a C++ program which will start new process (some script, programm, command) like daemon and gets some info from it (stdout). I'm trying to use popen(). But subprocess finishing when main program complete. I dont know, does C++ have something easy in use like Python (subprocessing). There is my code:

#include <stdio.h>
#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
  FILE *in;
  char buff[512];
  in = popen(argv[1], "r");
  fgets(buff, sizeof(buff), in);
  cout << buff;
}

P.S: & in the end of executive command doesn't helps.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Michael Smile
  • 11
  • 1
  • 5
  • 1
    Add what the input (`argv[1]`) was, what the output (`buff`) was and what you wanted the output to be. That will help reproduce the issue. – Matt Feb 14 '17 at 15:20
  • I would say this is not a communication issue: When the parent process stops, its child processes are stopped too, unless they took preventive measures. That's standard behaviour, nothing C/C++ specific. If you have your parent process read from 'in' until the child process is finished, that would solve this first problem. – Rene Feb 14 '17 at 15:37
  • You may also want to narrow the tags for you question to POSIX operating systems or Linux or whatever OS you are targeting (i.e. Microsoft Windows has different API to run a child process) – roalz Feb 14 '17 at 15:44

3 Answers3

1

fgets doesn't wait for the subprocess to complete, and neither does popen.

You need to read until the end of in:

while (fgets(buff, sizeof(buff), in))
{
    cout << buff;
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

Reference for popen function: http://man7.org/linux/man-pages/man3/popen.3.html

Excerpt:
"The popen() function opens a process by creating a pipe, forking, and invoking the shell."

I think that because of the fork mechanism, when your (calling) process ends, its child process (the called one) is stopped too, at least as default behaviour.
One option is to keep reading from the pipe (and keep the caller process running) until the child process ends.

Your code is also missing a pclose(in) before exiting.

See also this other post on StackOverflow.

Community
  • 1
  • 1
roalz
  • 2,699
  • 3
  • 25
  • 42
0

Have a look here https://github.com/arun11299/cpp-subprocess

This library can be exactly what you're looking for.

ilya
  • 301
  • 1
  • 3
  • 7