如何将后台运行的子进程调到前台

发布于 2024-11-03 11:22:22 字数 103 浏览 1 评论 0原文

如果我使用 fork() 和 execv() 生成多个在后台运行的子进程,并且我想将其中一个子进程带到前台,我该怎么做?

我正在尝试编写一个可以在前台或后台启动进程的外壳程序。

If I used fork() and execv() to spawn several child processes running in the background and I wanted to bring one of them to the foreground, how could I do that?

I am trying to write a shell that can start processes either in the foreground or background.

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

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

发布评论

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

评论(3

因为看清所以看轻 2024-11-10 11:22:22

“后台”和“前台”不是一般用于进程的术语,而仅适用于可以按需等待作业的 shell。

"Background" and "foreground" are not terms used generically for processes, but rather only apply to shells which can wait for jobs on demand.

晨敛清荷 2024-11-10 11:22:22

免费 Ignacio Vazquez-Abram 的回答,我建议您模拟 shell 前台/后台模型。

据我所知,后台进程意味着暂停它。最简单的方法是通过 SIGSTOP。当您将进程置于前台时,请向其发送SIGCONT。只要当前只有一项“作业”位于前台,它就将是唯一读取和写入会话 tty 的作业。

kill(child_pid, SIGSTOP);
kill(child_pid, SIGCONT);

您可能希望在 fork 之后和 execv 之前挂起每个进程,并为 shell 的用户提供稍后将它们置于前台的选项,以保持不变量。

if (!fork()) { // we are the child
    raise(SIGSTOP); // suspend self
    execv(...); // run the command (after we've been resumed)

以下是我找到的一些相关链接:

Complimentarily to Ignacio Vazquez-Abram's answer, I suggest that you emulate the shell foreground/background model.

As far as I can tell, backgrounding a process means suspending it. The easiest way to do this is through SIGSTOP. When you foreground a process, send it SIGCONT. As long as only one of your "jobs" are currently in the foreground, it will be the only one read and writing to the session's tty.

kill(child_pid, SIGSTOP);
kill(child_pid, SIGCONT);

You may want to suspend each process after you fork, and before you execv, and give the user of your shell the option to foreground them later to maintain the invariant.

if (!fork()) { // we are the child
    raise(SIGSTOP); // suspend self
    execv(...); // run the command (after we've been resumed)

Here are some related links I found:

岁吢 2024-11-10 11:22:22

您可以使用 fg 将进程置于前台,使用 bg 将进程置于后台。您应该知道进程的 pid 才能将其带到前台。请参阅 fg 和 bg 的 linux 手册以获取更多信息

you can do use fg to bring process to foreground and bg to put process to background. you should know the pid of the process to bring it to foreground. refer linux manual of fg and bg for more info

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