Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Why does std::system("exit 1") return 256?

Tags:

c++

stl

I want to run a little UNIX shell script inside my C++ program and I want to capture the exit code of the shell script. But the value returned by std::system is not what I expect it to be:

#include <iostream>
#include <cstdlib>

int main()
{
  std::cout << std::system("echo Hello >/dev/null") << std::endl;
  std::cout << std::system("which does_not_exisit 2>/dev/null") << std::endl;

  std::cout << std::system("exit 0") << std::endl;
  std::cout << std::system("exit 1") << std::endl;
  std::cout << std::system("exit 2") << std::endl;
  std::cout << std::system("exit 3") << std::endl;
  std::cout << std::system("echo exit 4 | bash") << std::endl;

  return 0;
}

On my Linux box this produces:

0
256
0
256
512
768
1024

It seems like all exit codes greater than 0 are multiplied by 256. What's the reason for this behavior? Is this portable across UNIX like operating systems?

like image 289
Linoliumz Avatar asked Oct 23 '15 19:10

Linoliumz


1 Answers

And the answer is:

  int status = std::system("exit 3");
  std::cout << WEXITSTATUS(status) << std::endl;

Which returns:

3

For more information visit:

Return value of system() function call in C++, used to run a Python program

like image 90
Linoliumz Avatar answered Nov 11 '22 03:11

Linoliumz