Linux 使用 system() 执行后台进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5691039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:41:20  来源:igfitidea点击:

Executing a background process with system()

c++linuxprocessbackground

提问by node ninja

I tried to execute a process using something like the following:

我尝试使用以下内容执行流程:

system("zsh &");

system("zsh &");

I don't think it works though, because the process doesn't show up. Why doesn't it work? How should it be changed?

我不认为它有效,因为该过程没有出现。为什么不起作用?应该怎么改?

回答by Konstantin Weitz

Following code works perfectly, using htop I can see that sleep is still running after my app terminates. I don't see how it should be different in your code.

以下代码完美运行,使用 htop 我可以看到在我的应用程序终止后 sleep 仍在运行。我不明白你的代码应该有什么不同。

#include <stdio.h>

int main()
{ 
   return system("sleep 100 &");
} 

回答by Dani

It's because zsh and all shells bind stdin and it couldn't on background so it crashed. That's also why sleep in background worked.

这是因为 zsh 和所有 shell 都绑定了 stdin 并且它不能在后台运行,所以它崩溃了。这也是后台睡眠有效的原因。

回答by dj_segfault

Regardless of any ampersand to run it in the background, or what system() will do, you're launching an interactive shell. When you launch an interactive shell, it looks for a console to connect to, Failing that, it looks for stdin lines to process. Failing that, it exits. That's what's happening.

不管在后台运行它的任何符号,或者 system() 会做什么,你都在启动一个交互式 shell。当您启动交互式 shell 时,它会查找要连接的控制台,否则,它会查找要处理的 stdin 行。如果失败,它退出。这就是正在发生的事情。