我正在使用的程序需要辅助可执行文件才能运行(用于资产压缩)。出于错误处理的原因,我需要子进程的返回值。根据
system
手册页,
如果所有系统调用都成功,则返回值是用于执行[the]命令的子shell的终止状态。 (shell 的终止状态是它执行的最后一个命令的终止状态。)
据此,我的
system
调用的返回状态应该是被调用进程的返回值。但似乎并非如此。 相反,当生成器返回 EXIT_FAILURE
时,程序会收到 EXIT_SUCCESS
或 0
。 我是不是误会了什么?
我的代码如下。
// Checks to see if the generator still exists using access().
bool asset_generator_availability = CheckAssetGenerator();
if (!asset_generator_availability) LogMessage("Assets already generated.");
else
{
LogWarning(
"Assets still uncompressed and unformatted. Running the Generator.");
u8 generator_state = system("./AssetGenerator && rm AssetGenerator");
// Here is the problem line.
if (generator_state == EXIT_FAILURE) exit(EXIT_FAILURE);
}
出现此问题是因为当系统成功运行被调用的进程时,它不会返回进程运行的直接返回值。相反,它返回一个“等待状态”,可以使用 waitpid(2) 中描述的宏进行检查。 (即 WIFEXITED()、WEXITSTATUS() 等)。 手册页对此问题有更多详细信息,但对于您的代码,您可以使用 WIFEXITED 和 WEXITSTATUS,如下所示:
if (WIFEXITED(generator_state) && WEXITSTATUS(generator_state) == EXIT_FAILURE)
{
exit(EXIT_FAILURE);
}
在此代码中,WIFEXITED 检查子进程是否正常退出,WEXITSTATUS 检查子进程的退出状态。希望有帮助!