1

I have a program that executes various shell commands via system() and occasionally prints to cout. I want to redirect all output coming from system() calls to a log file so they don't clutter up the normal output. Can I do this without having to append > log to all my system commands?

suszterpatt
  • 7,929
  • 33
  • 58

4 Answers4

4

Looks like you can use popen

Community
  • 1
  • 1
SwDevMan81
  • 45,922
  • 20
  • 140
  • 177
  • 1
    Yeah using popen for reading will hand you a pipe from which you can read the commands stdout and do with it what you want. – Joe Doliner Jan 26 '11 at 17:59
  • This is only valid for platforms that support `popen`. FYI, the standard C and C++ specifications do not require platforms to support `popen`. – Thomas Matthews Jan 26 '11 at 20:34
2

Close the stdio file descriptors (0, 1, and 2) and re-open them on whatever output device you like.

Conrad Meyer
  • 2,763
  • 18
  • 23
2

Using system is just a bad idea, period. If you use fork and execve or posix_spawn, you can easily make the necessary redirections and avoid all sorts of vulnerabilities from shell quoting issues.

R.. GitHub STOP HELPING ICE
  • 195,354
  • 31
  • 331
  • 669
0

If you can use a library that wrap process call. It is hard to code from posix. I use boost.process, it works fine. you can simply tell the lib how you want the output to be redirected...

my2c

neuro
  • 13,707
  • 3
  • 31
  • 57