gpt4 book ai didi

c++ - Linux C++ 程序通过系统调用启动 bash 脚本总是返回 -1

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

我有一个程序链如下:

C++ 程序“A”启动另一个 C++ 程序“B”,后者启动 bash 脚本。

要启动 bash 脚本,我使用:

int returnVal = system("pathToScript/myScript.sh");

我可以在我的日志文件中看到脚本的输出,所以它肯定正在执行。

问题是,无论脚本返回什么,returnVal 始终为 -1。我什至在脚本中硬编码了一个“exit 3”,当我通过系统调用启动它时,我仍然得到 -1 的 returnVal。

在终端中独立运行脚本并回显“$?”按预期显示返回值 3。

那么,当我通过一系列 C++ 程序运行它时,为什么退出代码会中断?有什么办法可以解决这个问题吗?

编辑 - 使用 perror 显示“无子进程”错误消息。

编辑 - 作为替代方案,我尝试使用 fork/exec/wait 来执行我的脚本,但我得到随机退出代码,例如 182、56、163、62, 51 等...代码如下:

pid_t pid = vfork();

switch (pid)
{
case -1:
cout << "Failed to fork." << endl;

case 0: // Child process
cout << "Child process launched!" << endl;
execl("/pathToScript/myScript.sh", "/pathToScript/myScript.sh", "someArgument", NULL);
cout << "execl call failed." << endl;
exit(0);

default:
int status;

cout << "Waiting for process to complete..." << endl;

waitpid(pid, &status, 0); // Wait for the process to complete.

cout << "Process exited with status: " << WEXITSTATUS(status) << endl;
}

为什么我在这里得到随机退出状态?

感谢任何建议。谢谢!

最佳答案

如评论中所述,您的问题是忽略 SIGCHLD。忽略 SIGCHLD 可用于防止创建僵尸。因此,通过将其配置设置为默认您可以破坏某些东西。

这里的例子:

signal (SIGCHLD, SIG_DFL);
system ("some_program");
signal (SIGCHLD, SIG_IGN);

如果某个子进程(不是 system 中的子进程)在执行第一行和第三行之间终止,它将变成僵尸。

如果你想正确解决这个资源泄漏,你应该使用另一种方法(双重forkwait)来解决僵尸问题。


Why am I getting random exit status here?

因为 waitpid 调用失败。 如果打印出 waitpid 的返回值,它将是 -1errno 的值很可能是 ECHILD。将 SIGCHLD 的处置设置为 SIG_IGN 会导致中断 waitwaitpid。在您的示例中,waitpid 没有向 status 变量写入任何内容(或写入垃圾)。

182, 56, 163, 62, 51, etc..

这些数字是未初始化的整数变量(或垃圾)的值。

As an alternative, I'm trying to use fork/exec/wait to execute my script

这不是好的选择。替代解决方案是为程序的所有部分将 SIGCHLD 的配置设置为 SIG_DFL。并改变其他部分处理僵尸的策略。

关于c++ - Linux C++ 程序通过系统调用启动 bash 脚本总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18067455/

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