I need to make my C++ program execute a bash script. So I think I need to use system()
, here is an example:
bash script test.sh
:
#!/bin/sh
exit 1
C++:
int main()
{
std::cout << system("./test.sh") << std::endl;
return 0;
}
To my surprise, I get an 256
etc. Here is what I've found:
test.sh | C++
---------|-----
exit 0 | 0
exit 1 | 256
exit 2 | 512
...
I don't know why. Is it possible to get the 0, 1, 2 etc.? Does the value depend on the machine?
Does the value depend on the machine?
Yes (at least as far as C++ standard is concerned).
it possible to get the 0, 1, 2 etc?
C++ standard does not provide a way to get the return value of the sub-process, but POSIX does, which applies to you since you use Linux.
Return Value
If command is a null pointer, system() shall return non-zero to indicate that a command processor is available, or zero if none is available. [CX] [Option Start] The system() function shall always return non-zero when command is NULL. [Option End]
[CX] [Option Start] If command is not a null pointer, system() shall return the termination status of the command language interpreter in the format specified by waitpid(). The termination status shall be as defined for the sh utility; otherwise, the termination status is unspecified. If some error prevents the command language interpreter from executing after the child process is created, the return value from system() shall be as if the command language interpreter had terminated using exit(127) or _exit(127). If a child process cannot be created, or if the termination status for the command language interpreter cannot be obtained, system() shall return -1 and set errno to indicate the error. [Option End]
waitpid() specifies a macro that can be used to extract the value returned from main()
.
WEXITSTATUS(stat_val)
If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().