在c++中,不等待并不意味着在后台运行?

发布于 2024-11-05 06:02:31 字数 252 浏览 2 评论 0 原文

在我的 C++ 程序中,我尝试通过不等待程序来在后台运行程序。

但是在Linux中,如果我像这样在后台启动vi:vi &,那么vi不会显示。在我的程序中,即使我不等待它终止,vi仍然会弹出。

那么这是否意味着我并没有真正在后台运行它?如何解决这个问题?

另外,我注意到在 Linux 中如果我输入 fg 将 vi 带到前台,那么 vi 就会出现。我怎样才能在 C++ 中做到这一点?

In my c++ program, I try to run programs in the background by simply not waiting for them.

However in Linux, if I start vi in the background like this: vi &, then vi doesn't show up. In my program, vi will still pop up even if I don't wait for it to terminate.

So does that mean that I'm not really running it in the background? How can this be fixed?

Also, I noticed that in Linux if I type fg to bring vi into the foreground, then vi will appear. How can I do this in c++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白色秋天 2024-11-12 06:02:35

这里发生的事情相当复杂(有关比您可能需要的更多信息,请参阅 glibc 的手册部分 作业控制),但简短的版本是:只有前台进程组可以访问终端。如果任何其他进程尝试访问终端,内核都会自动^Zed。

当您从 C 派生进程时,如果父进程位于前台进程组中,则子进程也被视为位于前台进程组中,除非父进程或子进程更改了这一点。当您执行 vi & 时,shell(记住,这只是另一个 C 程序)将 vi 从前台进程组中取出。但您没有这样做,因此 vi 立即运行。

现在,您想要从 C 程序中派生一个进程,并对其进行与从 shell 中使用 & 运行一样的处理。你只能做其中的一部分。您可以将其放入非前台进程组中——请参阅 glibc 手册以获取说明;正如我所说,它很复杂 - 但您不能将其添加到 shell 作业控制命令了解的进程组列表中。该列表是 shell 内部的状态,无法从其他进程获取它。

What's going on here is rather complicated (for more information than you probably require, see glibc's manual section on job control) but the short version is: Only the foreground process group can access the terminal. Any other process gets automatically ^Zed by the kernel if it tries to access the terminal.

When you fork a process from C, if the parent is in the foreground process group, the child is also considered to be in the foreground process group unless either the parent or the child changes that. When you do vi &, the shell (which is just another C program, remember) takes vi out of the foreground process group. But you're not doing that, so vi runs immediately.

Now, you want to fork a process from your C program and have it be treated the same as if it had been run with & from the shell. You can only do part of that. You can put it into a non-foreground process group -- see the glibc manual for instructions; as I said, it's complicated -- but you can't add it to the list of process groups that the shell's job control commands know about. That list is state internal to the shell, there's no way to get at it from another process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文