I want to launch a script and get the exit status in C++. But I noticed that the exit status of a system command always has a left shift of 8 bits. Why does the system function do that?
Sample code:
#include <iostream>
using namespace std;
int main()
{
int exit_code_0 = system("exit 0") >> 8;
int exit_code_1 = system("exit 1") >> 8;
int exit_code_2 = system("exit 2") >> 8;
int exit_code_3 = system("exit 3") >> 8;
int exit_code_4 = system("exit 4") >> 8;
int exit_code_255 = system("exit 255")>> 8;
cout<<"Exit code was: " << exit_code_0 <<", Expected: 0"<< endl;
cout<<"Exit code was: " << exit_code_1 <<", Expected: 1"<< endl;
cout<<"Exit code was: " << exit_code_2 <<", Expected: 2"<< endl;
cout<<"Exit code was: " << exit_code_3 <<", Expected: 3"<< endl;
cout<<"Exit code was: " << exit_code_4 <<", Expected: 4"<< endl;
cout<<"Exit code was: " << exit_code_255 <<", Expected: 255"<< endl;
return 0;
}
Test results:
Exit code was: 0, Expected: 0
Exit code was: 1, Expected: 1
Exit code was: 2, Expected: 2
Exit code was: 3, Expected: 3
Exit code was: 4, Expected: 4
Exit code was: 255, Expected: 255
System() Function in C/C++ It is used to pass the commands that can be executed in the command processor or the terminal of the operating system, and finally returns the command after it has been completed. <stdlib. h> or <cstdlib> should be included to call this function.
Do not use system() from a program with set-user-ID or set-group-ID privileges, because strange values for some environment variables might be used to subvert system integrity.
The C programming language allows programs exiting or returning from the main function to signal success or failure by returning an integer, or returning the macros EXIT_SUCCESS and EXIT_FAILURE . On Unix-like systems these are equal to 0 and 1 respectively.
Under any version of the language, exit requires a single argument of type int . Passing 0 or EXIT_SUCCESS (a macro defined in <stdlib. h> causes the program to terminate and pass a status to the environment indicating success. Passing EXIT_FAILURE causes the program to terminate with a status indicating failure.
In the C and C++ standards, system
returns an implementation-defined value.
In POSIX systems, the return value contains a combination of different values, which can be extracted with macros. To get the program's exit status, you use WEXITSTATUS(return_value)
, which on your system is defined to be a right shift by 8. The lower 8 bits contain other values (letting you determine, for example, if the program exited normally or due to a signal, etc.)
You are supposed to read the return value using
WEXITSTATUS(code)
https://man7.org/linux/man-pages/man3/system.3.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With