11

With C++ how do i launch an exe/process with stdin stdout and stderr? I know how to do this in .NET and i remember using popen in the past but popen seems to allow stdin OR stdout not both and not all 3.

I need this for windows but a linux solution is welcome as i'll need it for the same project in the future.

3 Answers3

3

You shoud use CreateProcess from WinApi. It takes as argument an object of struct STARTUP_INFO type. You can set hStdin, hStdout, and hStderr fields of the object to redirect those streams of child process to file handles you want (file, pipe, socket...)

Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111
3

A portable solution would be boost.process

(Note: this has been proposed as a Boost library, and released under the same license terms, but not officially accepted. See also Where is Boost.Process?)

Community
  • 1
  • 1
MSalters
  • 173,980
  • 10
  • 155
  • 350
  • boost process does not implement the Unicode API, only the ANSI API (CreateProcessA), which is a major limitation, making it unsuitable in many cases. – Ad N Jul 02 '19 at 15:34
2

I had troubles with spawning processes and reading or writing to their stream, but then I discovered a great C++ library which is very very convenient.

This open-source project is called tiny-process-library and was created by eidheim (a big thanks to him).

A small platform independent library making it simple to create and stop new processes in C++, as well as writing to stdin and reading from stdout and stderr of a new process.

Features

  • No external dependencies
  • Simple to use
  • Platform independent
  • Read separately from stout and stderr using anonymous functions
  • Write to stdin
  • Kill a running process (SIGTERM is supported on Unix-like systems)
  • Correctly closes file descriptors/handles

I am sharing this here because I first come to this thread before finding the library several hours later, so I hope it can save some time for further readers.

John McFarlane
  • 5,528
  • 4
  • 34
  • 38
Delgan
  • 18,571
  • 11
  • 90
  • 141