如何获取通过 C++ 中的 system() 启动的脚本的退出代码?
How to get exit code of a script launched via system() in C++?
我想 运行 C++ 应用程序中的脚本并从中捕获退出代码。所以我在应用程序中这样做了:
std::string script_path = "/home/john/script.sh";
int i = system(script_path.c_str());
std::cout << "ERROR: " << i << std::endl;
我写了一个简单的脚本,看它是否能捕捉到错误号:
#!/bin/sh
exit 5
但是程序显示:
ERROR: 1280
我不知道为什么,因为我在脚本中返回了 5。我该如何解决?我用 Linux
How could I fix it? I use Linux
来自man 3 system
:
RETURN VALUE
- If command is NULL, then a nonzero value if a shell is available, or 0 if no shell is available.
- If a child process could not be created, or its status could not be retrieved, the return value is -1 and errno is set to indicate the error.
- If a shell could not be executed in the child process, then the return value is as though the child shell terminated by calling _exit(2) with
the status 127.
- if all system calls succeed, then the return value is the termination status of the child shell used to execute command. (The termination sta‐
tus of a shell is the termination status of the last command it executes.)
In the last two cases, the return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED(),
WEXITSTATUS(), and so on).
您可以使用:
std::cout << "ERROR: " << ( (i != -1 && i != 127 && WIFEXITED(i)) ? WEXITSTATUS(i) : -1) << std::endl;
我想 运行 C++ 应用程序中的脚本并从中捕获退出代码。所以我在应用程序中这样做了:
std::string script_path = "/home/john/script.sh";
int i = system(script_path.c_str());
std::cout << "ERROR: " << i << std::endl;
我写了一个简单的脚本,看它是否能捕捉到错误号:
#!/bin/sh
exit 5
但是程序显示:
ERROR: 1280
我不知道为什么,因为我在脚本中返回了 5。我该如何解决?我用 Linux
How could I fix it? I use Linux
来自man 3 system
:
RETURN VALUE
- If command is NULL, then a nonzero value if a shell is available, or 0 if no shell is available.
- If a child process could not be created, or its status could not be retrieved, the return value is -1 and errno is set to indicate the error.
- If a shell could not be executed in the child process, then the return value is as though the child shell terminated by calling _exit(2) with the status 127.
- if all system calls succeed, then the return value is the termination status of the child shell used to execute command. (The termination sta‐ tus of a shell is the termination status of the last command it executes.)
In the last two cases, the return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED(), WEXITSTATUS(), and so on).
您可以使用:
std::cout << "ERROR: " << ( (i != -1 && i != 127 && WIFEXITED(i)) ? WEXITSTATUS(i) : -1) << std::endl;