0

I want to fetch the output of a shell execution in an ifstreambut the problem is that the program is never terminated, so I can't use popen(). I have to fetch the output of various tools, but one example is ping. So I either have to stop the program running in the pipe somehow so that popen() returns the string or have some method (I don't know yet) to stream the output. I know I could use system(), direct the output to a file and stream it in. But I would definitely prefer some direct method if there's any.

Does somebody know of a method to stream a Linux shell output of a self-invoked running program into an ifstream or something similar?

Marste
  • 627
  • 7
  • 22
  • 1
    You still could use `popen`, even for a non-terminating command. – Basile Starynkevitch Jun 17 '15 at 12:34
  • 1
    Are you aware of the fact that `ping` has command-line options that you can give it that tell it to not continue indefinitely? – twalberg Jun 17 '15 at 15:58
  • Yes, of course. The issue isn't about ping but about non-terminating programs in general- maybe this was a bad example, my apologies. One tool i actually use is cdpsnarf, which doesn't have such an option. – Marste Jun 18 '15 at 07:49

2 Answers2

2

popen and C++ streams use basic Linux system calls, and these are listed in syscalls(2) and most of them are explained in Advanced Linux Programming.

If you have only one single child command process running indefinitely, I believe you could use popen(3).

Things become more complex if you want to read from several pipes at once (e.g. running several child processes at one time), or if you need both the child process and your own one to be simultaneously active.

Then you'll set up pipes (see pipe(7) & pipe(2)), then fork(2) the child processes, etc (you'll also need dup2, waitpid, execve or execvp etc ...) Then you need a multiplexing syscall, like poll(2) -which I recommend- or the older select(2), etc... (for completeness, see also epoll(7) and read about the C10K problem).

You'll then need some event loop (doing the poll), and you might use some existing library for that (libev, libevent, etc...). If you are coding a GUI application (e.g. using Qt or Gtk), you should use its event loop machinery and its child process support (both provided by most GUI toolkits).

Explaining all the details would take me too much time; Advanced Linux Programming is explaining them very well.

You might want to strace(1) some commands or processes to understand what syscalls are involved.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

I've found the answer best suiting my needs in this post:

How to execute a command and get output of command within C++ using POSIX?

The pstreams libary does everything needed to solve this problem:

http://pstreams.sourceforge.net/

Community
  • 1
  • 1
Marste
  • 627
  • 7
  • 22