gpt4 book ai didi

c++ - C++ 如何解释 system() 的返回值

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:08 24 4
gpt4 key购买 nike

我需要让我的 C++ 程序执行一个 bash 脚本。所以我想我需要使用 system(),这里是一个例子:

bash 脚本 test.sh:

#!/bin/sh
exit 1

C++:

int main()
{
std::cout << system("./test.sh") << std::endl;
return 0;
}

令我惊讶的是,我得到了 256 等。这是我发现的:

 test.sh | C++
---------|-----
exit 0 | 0
exit 1 | 256
exit 2 | 512
...

我不知道为什么。是否有可能获得 0、1、2 等?该值是否取决于机器?

最佳答案

Does the value depend on the machine?

是的(至少就 C++ 标准而言)。

it possible to get the 0, 1, 2 etc?

C++标准没有提供获取子进程返回值的方法,但是POSIX确实如此,这适用于您,因为您使用的是 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()指定可用于提取从 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().

关于c++ - C++ 如何解释 system() 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46075721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com