CuriousKimchi CuriousKimchi - 14 days ago 5x
Linux Question

How do I make my c++ code know whether a command run from "system(cmd)" failed or not?

Let's assume I am running a unix command using

system("foocmd param1")
on c++.
returns "Invalid argument" back to the terminal via stderr, then how do I get my c++ code to know whether

Here is my attempted solution:

My assumption is that I should check whether anything got returned to stderr by calling the command.
To do that, I tried switching over to popen. Currently, this is the way I check. I first output my stderr into a file.

sprintf(cmd, "foocmd param1 2>temp.txt");

Then I check if temp.txt is empty or not.

But there has to be a better way. Can anyone lend me a hand?


The usual way is to examine the return value of system():

  • If it's zero, the command executed successfully and exited with a status of 0.
  • If it's negative, there was a problem with system() itself, and you can't assume anything.
  • If it's positive, then you can use WEXITSTATUS() and related macros to find out how the process exited.

See the system(3) man page for the full details.

Most of the time, you are only interested in whether the command says it succeeded:

if (!system(cmd)) {
    syslog(LOG_WARNING, "Command \"%s\" failed", cmd);
    /* maybe some more error handling here */
    goto err_return;