【发布时间】:2018-02-14 23:23:05
【问题描述】:
我需要让我的 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 等?值是否取决于机器?
【问题讨论】:
-
根据手册,返回值(大部分)是实现定义的en.cppreference.com/w/cpp/utility/program/system
-
@Galik:我假设他正在使用 Linux,其中:
The value returned is -1 on error (e.g., fork(2) failed), and the return status of the command otherwise.成立。见Linux manpage of system。 -
@AndreKampling 然而,重要的是要提到命令的返回状态不是从
main返回的值。 -
你检查过你的shell脚本在c++之外产生了什么状态吗?