本文介绍了将进程发送到后台并将控件返回到我的shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为CS类编写外壳程序,并且如果'&',则项目的一部分涉及在后台运行进程.字符由用户传递.

I am programming a shell for my CS class and part of the project involves running a process in the background if the '&' character is passed in by the user.

如果某个进程在前台运行,那么我只需execvp该进程,由于它在前台,因此它仍受终端的控制.但是,如果它是一个后台进程,则必须在开始执行该进程后将控制权返回给我的主shell.我知道系统调用tcsetpgrp(pid_t)将作为参数传入的进程放在前台,但是我不太了解如何使用它.

If a process is run in the foreground, I simply execvp the process and it remains in control of the terminal since it is in the foreground. However, if it is a background process, I must return control to my main shell after starting the execution of the process. I understand that the system call tcsetpgrp(pid_t) places the process passed in as argument in the foreground, but I don't quite understand how to use it.

如果它是后台进程,我应该在execvp之后调用tcsetpgrp吗?如果是这样,我可以仅通过调用getpid来获取我的shell的pid吗?

Should I call tcsetpgrp after execvp if it is a background process? If so, can I obtain the pid of my shell just by calling getpid?

推荐答案

tcsetpgrp()适用于进程组,而不是单个进程.您想做的是这样:

tcsetpgrp() works on process groups, not individual processes. What you want to do is this:

  1. 创建新管道时,请调用setpgid()将管道的所有成员放入新的进程组中(将管道中第一个进程的PID作为PGID). (管道是当您看到诸如ls | grep foo | wc -l之类的请求时,由外壳程序启动的一系列过程-最简单的管道中只有一个过程).通常,您将在调用exec()之前从管道中的第一个进程调用setpgid(0, 0).

  1. When you create a new pipeline, call setpgid() to put all the members of the pipeline in a new process group (with the PID of the first process in the pipeline as the PGID). (A pipeline is a sequence of processes started by your shell when it sees a request like ls | grep foo | wc -l - the simplest pipeline has just one process in it). Normally you would call setpgid(0, 0) from the first process in the pipeline, before calling exec().

使用tcsetpgrp()管理哪个进程组位于前台.如果将进程组从前台移到后台,则需要将外壳程序自身的进程组设置为前台进程组-您可以在外壳程序中使用getpgid(0)来获得它.

Use tcsetpgrp() to manage which process group is in the foreground. If you move a process group from the foreground to the background, you would set the shell's own process group as the foreground process group - you can get this with getpgid(0) in the shell.

当外壳在后台时,它应使用阻塞式waitpid()调用来等待子进程退出而不是显示提示.一旦退出前台管道中的每个进程,它都应再次将自己放回前台(并显示提示).

When the shell is in the background, it should use a blocking waitpid() call to wait for a child process to exit rather than show a prompt. Once every process in the foreground pipeline has exited, it should put itself back into the foreground again (and show a prompt).

当外壳在前台时,它应该在显示提示之前使用WNOHANGWUNTRACED标志调用waitpid()以检查子进程的状态-这将通知您何时他们已停止或退出,并让您通知用户.

When the shell is in the foreground, it should call waitpid() with the WNOHANG and WUNTRACED flags to check on the status of child processes just before you show the prompt - this will inform you when they have stopped or exited, and let you inform the user.

这篇关于将进程发送到后台并将控件返回到我的shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:57