gpt4 book ai didi

linux - 如何让system()函数畅通无阻?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:21:58 25 4
gpt4 key购买 nike

我正在从 Android Linux 中的另一个可执行文件调用一个可执行文件。以下是相关代码:

...
int status = system("/system/bin/executable");
...

我的要求是不要等待 executable 完成执行。意味着我想独立于调用它的可执行文件运行 executable

我在互联网上搜索过,但没有找到如何使这个系统调用成为非阻塞的。请帮我解决一下。

最佳答案

没有错误处理的 system() 函数如下所示:

int system(char const *cmdline)
{
pid_t pid = fork();
if(pid == 0)
{
char const *argv[] = { "sh", "-c", cmdline, NULL };
execve("/bin/sh", argv, NULL);
_exit(1);
}
else
{
int status;
waitpid(pid, &status, 0);
return status;
}
}

命令本身由 shell 解析,因此您可以使用普通的 & 后缀将命令发送到后台。然后 shell 立即终止,后台程序重新设置为 PID 1(因此您的程序不负责收集僵尸),system() 返回。

关于linux - 如何让system()函数畅通无阻?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56772427/

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