📄 job.texi
字号:
@node Job Control@chapter Job Control@cindex process groups@cindex job control@cindex job@cindex session@dfn{Job control} refers to the protocol for allowing a user to movebetween multiple @dfn{process groups} (or @dfn{jobs}) within a single@dfn{login session}. The job control facilities are set up so thatappropriate behavior for most programs happens automatically and theyneed not do anything special about job control. So you can probablyignore the material in this chapter unless you are writing a shell orlogin program.You need to be familiar with concepts relating to process creation(@pxref{Process Creation Concepts}) and signal handling (@pxref{SignalHandling}) in order to understand this material presented in thischapter.@menu* Concepts of Job Control:: Jobs can be controlled by a shell.* Job Control is Optional:: Not all POSIX systems support job control.* Controlling Terminal:: How a process gets its controlling terminal.* Access to the Terminal:: How processes share the controlling terminal.* Orphaned Process Groups:: Jobs left after the user logs out.* Implementing a Shell:: What a shell must do to implement job control.* Functions for Job Control:: Functions to control process groups.@end menu@node Concepts of Job Control, Job Control is Optional, , Job Control@section Concepts of Job Control@cindex shellThe fundamental purpose of an interactive shell is to readcommands from the user's terminal and create processes to execute theprograms specified by those commands. It can do this using the@code{fork} (@pxref{Creating a Process}) and @code{exec}(@pxref{Executing a File}) functions.A single command may run just one process---but often one command usesseveral processes. If you use the @samp{|} operator in a shell command,you explicitly request several programs in their own processes. Buteven if you run just one program, it can use multiple processesinternally. For example, a single compilation command such as @samp{cc-c foo.c} typically uses four processes (though normally only two at anygiven time). If you run @code{make}, its job is to run other programsin separate processes.The processes belonging to a single command are called a @dfn{processgroup} or @dfn{job}. This is so that you can operate on all of them atonce. For example, typing @kbd{C-c} sends the signal @code{SIGINT} toterminate all the processes in the foreground process group.@cindex sessionA @dfn{session} is a larger group of processes. Normally all theproccesses that stem from a single login belong to the same session.Every process belongs to a process group. When a process is created, itbecomes a member of the same process group and session as its parentprocess. You can put it in another process group using the@code{setpgid} function, provided the process group belongs to the samesession.@cindex session leaderThe only way to put a process in a different session is to make it theinitial process of a new session, or a @dfn{session leader}, using the@code{setsid} function. This also puts the session leader into a newprocess group, and you can't move it out of that process group again.Usually, new sessions are created by the system login program, and thesession leader is the process running the user's login shell.@cindex controlling terminalA shell that supports job control must arrange to control which job canuse the terminal at any time. Otherwise there might be multiple jobstrying to read from the terminal at once, and confusion about whichprocess should receive the input typed by the user. To prevent this,the shell must cooperate with the terminal driver using the protocoldescribed in this chapter.@cindex foreground job@cindex background jobThe shell can give unlimited access to the controlling terminal to onlyone process group at a time. This is called the @dfn{foreground job} onthat controlling terminal. Other process groups managed by the shellthat are executing without such access to the terminal are called@dfn{background jobs}.@cindex stopped jobIf a background job needs to read from its controllingterminal, it is @dfn{stopped} by the terminal driver; if the@code{TOSTOP} mode is set, likewise for writing. The user can stopa foreground job by typing the SUSP character (@pxref{SpecialCharacters}) and a program can stop any job by sending it a@code{SIGSTOP} signal. It's the responsibility of the shell to noticewhen jobs stop, to notify the user about them, and to provide mechanismsfor allowing the user to interactively continue stopped jobs and switchjobs between foreground and background.@xref{Access to the Terminal}, for more information about I/O to thecontrolling terminal,@node Job Control is Optional, Controlling Terminal, Concepts of Job Control , Job Control@section Job Control is Optional@cindex job control is optionalNot all operating systems support job control. The GNU system doessupport job control, but if you are using the GNU library on some othersystem, that system may not support job control itself.You can use the @code{_POSIX_JOB_CONTROL} macro to test at compile-timewhether the system supports job control. @xref{System Options}.If job control is not supported, then there can be only one processgroup per session, which behaves as if it were always in the foreground.The functions for creating additional process groups simply fail withthe error code @code{ENOSYS}.The macros naming the various job control signals (@pxref{Job ControlSignals}) are defined even if job control is not supported. However,the system never generates these signals, and attempts to send a jobcontrol signal or examine or specify their actions report errors or donothing.@node Controlling Terminal, Access to the Terminal, Job Control is Optional, Job Control@section Controlling Terminal of a ProcessOne of the attributes of a process is its controlling terminal. Childprocesses created with @code{fork} inherit the controlling terminal fromtheir parent process. In this way, all the processes in a sessioninherit the controlling terminal from the session leader. A sessionleader that has control of a terminal is called the @dfn{controllingprocess} of that terminal.@cindex controlling processYou generally do not need to worry about the exact mechanism used toallocate a controlling terminal to a session, since it is done for youby the system when you log in.@c ??? How does GNU system let a process get a ctl terminal.An individual process disconnects from its controlling terminal when itcalls @code{setsid} to become the leader of a new session.@xref{Process Group Functions}.@c !!! explain how it gets a new one (by opening any terminal)@c ??? How you get a controlling terminal is system-dependent.@c We should document how this will work in the GNU system when it is decided.@c What Unix does is not clean and I don't think GNU should use that.@node Access to the Terminal, Orphaned Process Groups, Controlling Terminal, Job Control@section Access to the Controlling Terminal@cindex controlling terminal, access toProcesses in the foreground job of a controlling terminal haveunrestricted access to that terminal; background proesses do not. Thissection describes in more detail what happens when a process in abackground job tries to access its controlling terminal.@cindex @code{SIGTTIN}, from background jobWhen a process in a background job tries to read from its controllingterminal, the process group is usually sent a @code{SIGTTIN} signal.This normally causes all of the processes in that group to stop (unlessthey handle the signal and don't stop themselves). However, if thereading process is ignoring or blocking this signal, then @code{read}fails with an @code{EIO} error instead.@cindex @code{SIGTTOU}, from background jobSimilarly, when a process in a background job tries to write to itscontrolling terminal, the default behavior is to send a @code{SIGTTOU}signal to the process group. However, the behavior is modified by the@code{TOSTOP} bit of the local modes flags (@pxref{Local Modes}). Ifthis bit is not set (which is the default), then writing to thecontrolling terminal is always permitted without sending a signal.Writing is also permitted if the @code{SIGTTOU} signal is being ignoredor blocked by the writing process.Most other terminal operations that a program can do are treated asreading or as writing. (The description of each operation should saywhich.)For more information about the primitive @code{read} and @code{write}functions, see @ref{I/O Primitives}.@node Orphaned Process Groups, Implementing a Shell, Access to the Terminal, Job Control@section Orphaned Process Groups@cindex orphaned process groupWhen a controlling process terminates, its terminal becomes free and anew session can be established on it. (In fact, another user could login on the terminal.) This could cause a problem if any processes fromthe old session are still trying to use that terminal.To prevent problems, process groups that continue running even after thesession leader has terminated are marked as @dfn{orphaned processgroups}.When a process group becomes an orphan, its processes are sent a@code{SIGHUP} signal. Ordinarily, this causes the processes toterminate. However, if a program ignores this signal or establishes ahandler for it (@pxref{Signal Handling}), it can continue running as inthe orphan process group even after its controlling process terminates;but it still cannot access the terminal any more.@node Implementing a Shell, Functions for Job Control, Orphaned Process Groups, Job Control@section Implementing a Job Control ShellThis section describes what a shell must do to implement job control, bypresenting an extensive sample program to illustrate the conceptsinvolved.@iftex@itemize @bullet@item @ref{Data Structures}, introduces the example and presentsits primary data structures.@item@ref{Initializing the Shell}, discusses actions which the shell mustperform to prepare for job control.@item@ref{Launching Jobs}, includes information about how to create jobsto execute commands.@item@ref{Foreground and Background}, discusses what the shell shoulddo differently when launching a job in the foreground as opposed toa background job.@item@ref{Stopped and Terminated Jobs}, discusses reporting of job statusback to the shell.@item@ref{Continuing Stopped Jobs}, tells you how to continue jobs thathave been stopped.@item@ref{Missing Pieces}, discusses other parts of the shell.@end itemize@end iftex@menu* Data Structures:: Introduction to the sample shell.* Initializing the Shell:: What the shell must do to take responsibility for job control.* Launching Jobs:: Creating jobs to execute commands.* Foreground and Background:: Putting a job in foreground of background.* Stopped and Terminated Jobs:: Reporting job status.* Continuing Stopped Jobs:: How to continue a stopped job in the foreground or background.* Missing Pieces:: Other parts of the shell.@end menu@node Data Structures, Initializing the Shell, , Implementing a Shell@subsection Data Structures for the ShellAll of the program examples included in this chapter are part ofa simple shell program. This section presents data structuresand utility functions which are used throughout the example.The sample shell deals mainly with two data structures. The@code{job} type contains information about a job, which is aset of subprocesses linked together with pipes. The @code{process} typeholds information about a single subprocess. Here are the relevantdata structure declarations:@smallexample@group/* @r{A process is a single process.} */typedef struct process@{ struct process *next; /* @r{next process in pipeline} */ char **argv; /* @r{for exec} */ pid_t pid; /* @r{process ID} */ char completed; /* @r{true if process has completed} */ char stopped; /* @r{true if process has stopped} */ int status; /* @r{reported status value} */@} process;@end group@group/* @r{A job is a pipeline of processes.} */typedef struct job@{ struct job *next; /* @r{next active job} */ char *command; /* @r{command line, used for messages} */ process *first_process; /* @r{list of processes in this job} */ pid_t pgid; /* @r{process group ID} */ char notified; /* @r{true if user told about stopped job} */ struct termios tmodes; /* @r{saved terminal modes} */ int stdin, stdout, stderr; /* @r{standard i/o channels} */@} job;/* @r{The active jobs are linked into a list. This is its head.} */job *first_job = NULL;@end group@end smallexampleHere are some utility functions that are used for operating on @code{job}objects.@smallexample@group/* @r{Find the active job with the indicated @var{pgid}.} */job *find_job (pid_t pgid)@{ job *j; for (j = first_job; j; j = j->next) if (j->pgid == pgid) return j; return NULL;@}@end group@group/* @r{Return true if all processes in the job have stopped or completed.} */intjob_is_stopped (job *j)@{ process *p; for (p = j->first_process; p; p = p->next) if (!p->completed && !p->stopped) return 0; return 1;@}@end group@group/* @r{Return true if all processes in the job have completed.} */intjob_is_completed (job *j)@{ process *p; for (p = j->first_process; p; p = p->next) if (!p->completed) return 0; return 1;@}@end group@end smallexample@node Initializing the Shell, Launching Jobs, Data Structures, Implementing a Shell@subsection Initializing the Shell@cindex job control, enabling@cindex subshellWhen a shell program that normally performs job control is started, ithas to be careful in case it has been invoked from another shell that isalready doing its own job control. A subshell that runs interactively has to ensure that it has been placedin the foreground by its parent shell before it can enable job controlitself. It does this by getting its initial process group ID with the@code{getpgrp} function, and comparing it to the process group ID of thecurrent foreground job associated with its controlling terminal (whichcan be retrieved using the @code{tcgetpgrp} function).If the subshell is not running as a foreground job, it must stop itselfby sending a @code{SIGTTIN} signal to its own process group. It may notarbitrarily put itself into the foreground; it must wait for the user totell the parent shell to do this. If the subshell is continued again,it should repeat the check and stop itself again if it is still not inthe foreground.@cindex job control, enablingOnce the subshell has been placed into the foreground by its parentshell, it can enable its own job control. It does this by calling@code{setpgid} to put itself into its own process group, and thencalling @code{tcsetpgrp} to place this process group into theforeground.When a shell enables job control, it should set itself to ignore all thejob control stop signals so that it doesn't accidentally stop itself.You can do this by setting the action for all the stop signals to@code{SIG_IGN}.A subshell that runs non-interactively cannot and should not support jobcontrol. It must leave all processes it creates in the same processgroup as the shell itself; this allows the non-interactive shell and itschild processes to be treated as a single job by the parent shell. Thisis easy to do---just don't use any of the job control primitives---butyou must remember to make the shell do it.Here is the initialization code for the sample shell that shows how todo all of this.@smallexample/* @r{Keep track of attributes of the shell.} */#include <sys/types.h>#include <termios.h>#include <unistd.h>pid_t shell_pgid;struct termios shell_tmodes;int shell_terminal;int shell_is_interactive;/* @r{Make sure the shell is running interactively as the foreground job} @r{before proceeding.} */voidinit_shell ()@{ /* @r{See if we are running interactively.} */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -