Issuing system commands in Linux from C, C++

system is a bad idea for several reasons:

  • Your program is suspended until the command finishes.
  • It runs the command through a shell, which means you have to worry about making sure the string you pass is safe for the shell to evaluate.
  • If you try to run a backgrounded command with &, it ends up being a grandchild process and gets orphaned and taken in by the init process (pid 1), and you have no way of checking its status after that.
  • There’s no way to read the command’s output back into your program.

For the first and final issues, popen is one solution, but it doesn’t address the other issues. You should really use fork and exec (or posix_spawn) yourself for running any external command/program.

Leave a Comment