Sun Dec 17 15:56:35 1995 Miles Bader <miles@gnu.ai.mit.edu>
[glibc.git] / manual / job.texi
blob1ac15fffc4e4735104c0053cc325db45b156f6d7
1 @node Job Control
2 @chapter Job Control
4 @cindex process groups
5 @cindex job control
6 @cindex job
7 @cindex session
8 @dfn{Job control} refers to the protocol for allowing a user to move
9 between multiple @dfn{process groups} (or @dfn{jobs}) within a single
10 @dfn{login session}.  The job control facilities are set up so that
11 appropriate behavior for most programs happens automatically and they
12 need not do anything special about job control.  So you can probably
13 ignore the material in this chapter unless you are writing a shell or
14 login program.
16 You need to be familiar with concepts relating to process creation
17 (@pxref{Process Creation Concepts}) and signal handling (@pxref{Signal
18 Handling}) in order to understand this material presented in this
19 chapter.
21 @menu
22 * Concepts of Job Control::     Jobs can be controlled by a shell.
23 * Job Control is Optional::     Not all POSIX systems support job control.
24 * Controlling Terminal::        How a process gets its controlling terminal.
25 * Access to the Terminal::      How processes share the controlling terminal.
26 * Orphaned Process Groups::     Jobs left after the user logs out.
27 * Implementing a Shell::        What a shell must do to implement job control.
28 * Functions for Job Control::   Functions to control process groups.
29 @end menu
31 @node Concepts of Job Control, Job Control is Optional,  , Job Control
32 @section Concepts of Job Control
34 @cindex shell
35 The fundamental purpose of an interactive shell is to read
36 commands from the user's terminal and create processes to execute the
37 programs specified by those commands.  It can do this using the
38 @code{fork} (@pxref{Creating a Process}) and @code{exec}
39 (@pxref{Executing a File}) functions.
41 A single command may run just one process---but often one command uses
42 several processes.  If you use the @samp{|} operator in a shell command,
43 you explicitly request several programs in their own processes.  But
44 even if you run just one program, it can use multiple processes
45 internally.  For example, a single compilation command such as @samp{cc
46 -c foo.c} typically uses four processes (though normally only two at any
47 given time).  If you run @code{make}, its job is to run other programs
48 in separate processes.
50 The processes belonging to a single command are called a @dfn{process
51 group} or @dfn{job}.  This is so that you can operate on all of them at
52 once.  For example, typing @kbd{C-c} sends the signal @code{SIGINT} to
53 terminate all the processes in the foreground process group.
55 @cindex session
56 A @dfn{session} is a larger group of processes.  Normally all the
57 proccesses that stem from a single login belong to the same session.
59 Every process belongs to a process group.  When a process is created, it
60 becomes a member of the same process group and session as its parent
61 process.  You can put it in another process group using the
62 @code{setpgid} function, provided the process group belongs to the same
63 session.
65 @cindex session leader
66 The only way to put a process in a different session is to make it the
67 initial process of a new session, or a @dfn{session leader}, using the
68 @code{setsid} function.  This also puts the session leader into a new
69 process group, and you can't move it out of that process group again.
71 Usually, new sessions are created by the system login program, and the
72 session leader is the process running the user's login shell.
74 @cindex controlling terminal
75 A shell that supports job control must arrange to control which job can
76 use the terminal at any time.  Otherwise there might be multiple jobs
77 trying to read from the terminal at once, and confusion about which
78 process should receive the input typed by the user.  To prevent this,
79 the shell must cooperate with the terminal driver using the protocol
80 described in this chapter.
82 @cindex foreground job
83 @cindex background job
84 The shell can give unlimited access to the controlling terminal to only
85 one process group at a time.  This is called the @dfn{foreground job} on
86 that controlling terminal.  Other process groups managed by the shell
87 that are executing without such access to the terminal are called
88 @dfn{background jobs}.
90 @cindex stopped job
91 If a background job needs to read from its controlling
92 terminal, it is @dfn{stopped} by the terminal driver; if the
93 @code{TOSTOP} mode is set, likewise for writing.  The user can stop
94 a foreground job by typing the SUSP character (@pxref{Special
95 Characters}) and a program can stop any job by sending it a
96 @code{SIGSTOP} signal.  It's the responsibility of the shell to notice
97 when jobs stop, to notify the user about them, and to provide mechanisms
98 for allowing the user to interactively continue stopped jobs and switch
99 jobs between foreground and background.
101 @xref{Access to the Terminal}, for more information about I/O to the
102 controlling terminal,
104 @node Job Control is Optional, Controlling Terminal, Concepts of Job Control , Job Control
105 @section Job Control is Optional
106 @cindex job control is optional
108 Not all operating systems support job control.  The GNU system does
109 support job control, but if you are using the GNU library on some other
110 system, that system may not support job control itself.
112 You can use the @code{_POSIX_JOB_CONTROL} macro to test at compile-time
113 whether the system supports job control.  @xref{System Options}.
115 If job control is not supported, then there can be only one process
116 group per session, which behaves as if it were always in the foreground.
117 The functions for creating additional process groups simply fail with
118 the error code @code{ENOSYS}.
120 The macros naming the various job control signals (@pxref{Job Control
121 Signals}) are defined even if job control is not supported.  However,
122 the system never generates these signals, and attempts to send a job
123 control signal or examine or specify their actions report errors or do
124 nothing.
127 @node Controlling Terminal, Access to the Terminal, Job Control is Optional, Job Control
128 @section Controlling Terminal of a Process
130 One of the attributes of a process is its controlling terminal.  Child
131 processes created with @code{fork} inherit the controlling terminal from
132 their parent process.  In this way, all the processes in a session
133 inherit the controlling terminal from the session leader.  A session
134 leader that has control of a terminal is called the @dfn{controlling
135 process} of that terminal.
137 @cindex controlling process
138 You generally do not need to worry about the exact mechanism used to
139 allocate a controlling terminal to a session, since it is done for you
140 by the system when you log in.
141 @c ??? How does GNU system let a process get a ctl terminal.
143 An individual process disconnects from its controlling terminal when it
144 calls @code{setsid} to become the leader of a new session.
145 @xref{Process Group Functions}.
147 @c !!! explain how it gets a new one (by opening any terminal)
148 @c ??? How you get a controlling terminal is system-dependent.
149 @c We should document how this will work in the GNU system when it is decided.
150 @c What Unix does is not clean and I don't think GNU should use that.
152 @node Access to the Terminal, Orphaned Process Groups, Controlling Terminal, Job Control
153 @section Access to the Controlling Terminal
154 @cindex controlling terminal, access to
156 Processes in the foreground job of a controlling terminal have
157 unrestricted access to that terminal; background proesses do not.  This
158 section describes in more detail what happens when a process in a
159 background job tries to access its controlling terminal.
161 @cindex @code{SIGTTIN}, from background job
162 When a process in a background job tries to read from its controlling
163 terminal, the process group is usually sent a @code{SIGTTIN} signal.
164 This normally causes all of the processes in that group to stop (unless
165 they handle the signal and don't stop themselves).  However, if the
166 reading process is ignoring or blocking this signal, then @code{read}
167 fails with an @code{EIO} error instead.
169 @cindex @code{SIGTTOU}, from background job
170 Similarly, when a process in a background job tries to write to its
171 controlling terminal, the default behavior is to send a @code{SIGTTOU}
172 signal to the process group.  However, the behavior is modified by the
173 @code{TOSTOP} bit of the local modes flags (@pxref{Local Modes}).  If
174 this bit is not set (which is the default), then writing to the
175 controlling terminal is always permitted without sending a signal.
176 Writing is also permitted if the @code{SIGTTOU} signal is being ignored
177 or blocked by the writing process.
179 Most other terminal operations that a program can do are treated as
180 reading or as writing.  (The description of each operation should say
181 which.)
183 For more information about the primitive @code{read} and @code{write}
184 functions, see @ref{I/O Primitives}.
187 @node Orphaned Process Groups, Implementing a Shell, Access to the Terminal, Job Control
188 @section Orphaned Process Groups
189 @cindex orphaned process group
191 When a controlling process terminates, its terminal becomes free and a
192 new session can be established on it.  (In fact, another user could log
193 in on the terminal.)  This could cause a problem if any processes from
194 the old session are still trying to use that terminal.
196 To prevent problems, process groups that continue running even after the
197 session leader has terminated are marked as @dfn{orphaned process
198 groups}.
200 When a process group becomes an orphan, its processes are sent a
201 @code{SIGHUP} signal.  Ordinarily, this causes the processes to
202 terminate.  However, if a program ignores this signal or establishes a
203 handler for it (@pxref{Signal Handling}), it can continue running as in
204 the orphan process group even after its controlling process terminates;
205 but it still cannot access the terminal any more.
207 @node Implementing a Shell, Functions for Job Control, Orphaned Process Groups, Job Control
208 @section Implementing a Job Control Shell
210 This section describes what a shell must do to implement job control, by
211 presenting an extensive sample program to illustrate the concepts
212 involved.
214 @iftex
215 @itemize @bullet
216 @item 
217 @ref{Data Structures}, introduces the example and presents
218 its primary data structures.
220 @item
221 @ref{Initializing the Shell}, discusses actions which the shell must
222 perform to prepare for job control.
224 @item
225 @ref{Launching Jobs}, includes information about how to create jobs
226 to execute commands.
228 @item
229 @ref{Foreground and Background}, discusses what the shell should
230 do differently when launching a job in the foreground as opposed to
231 a background job.
233 @item
234 @ref{Stopped and Terminated Jobs}, discusses reporting of job status
235 back to the shell.
237 @item
238 @ref{Continuing Stopped Jobs}, tells you how to continue jobs that
239 have been stopped.
241 @item
242 @ref{Missing Pieces}, discusses other parts of the shell.
243 @end itemize
244 @end iftex
246 @menu
247 * Data Structures::             Introduction to the sample shell.
248 * Initializing the Shell::      What the shell must do to take
249                                  responsibility for job control.
250 * Launching Jobs::              Creating jobs to execute commands.
251 * Foreground and Background::   Putting a job in foreground of background.
252 * Stopped and Terminated Jobs::  Reporting job status.
253 * Continuing Stopped Jobs::     How to continue a stopped job in
254                                  the foreground or background.
255 * Missing Pieces::              Other parts of the shell.
256 @end menu
258 @node Data Structures, Initializing the Shell,  , Implementing a Shell
259 @subsection Data Structures for the Shell
261 All of the program examples included in this chapter are part of
262 a simple shell program.  This section presents data structures
263 and utility functions which are used throughout the example.
265 The sample shell deals mainly with two data structures.  The
266 @code{job} type contains information about a job, which is a
267 set of subprocesses linked together with pipes.  The @code{process} type
268 holds information about a single subprocess.  Here are the relevant
269 data structure declarations:
271 @smallexample
272 @group
273 /* @r{A process is a single process.}  */
274 typedef struct process
276   struct process *next;       /* @r{next process in pipeline} */
277   char **argv;                /* @r{for exec} */
278   pid_t pid;                  /* @r{process ID} */
279   char completed;             /* @r{true if process has completed} */
280   char stopped;               /* @r{true if process has stopped} */
281   int status;                 /* @r{reported status value} */
282 @} process;
283 @end group
285 @group
286 /* @r{A job is a pipeline of processes.}  */
287 typedef struct job
289   struct job *next;           /* @r{next active job} */
290   char *command;              /* @r{command line, used for messages} */
291   process *first_process;     /* @r{list of processes in this job} */
292   pid_t pgid;                 /* @r{process group ID} */
293   char notified;              /* @r{true if user told about stopped job} */
294   struct termios tmodes;      /* @r{saved terminal modes} */
295   int stdin, stdout, stderr;  /* @r{standard i/o channels} */
296 @} job;
298 /* @r{The active jobs are linked into a list.  This is its head.}   */
299 job *first_job = NULL;
300 @end group
301 @end smallexample
303 Here are some utility functions that are used for operating on @code{job}
304 objects.
306 @smallexample
307 @group
308 /* @r{Find the active job with the indicated @var{pgid}.}  */
309 job *
310 find_job (pid_t pgid)
312   job *j;
313   
314   for (j = first_job; j; j = j->next)
315     if (j->pgid == pgid)
316       return j;
317   return NULL;
319 @end group
321 @group
322 /* @r{Return true if all processes in the job have stopped or completed.}  */
324 job_is_stopped (job *j)
326   process *p;
327   
328   for (p = j->first_process; p; p = p->next)
329     if (!p->completed && !p->stopped)
330       return 0;
331   return 1;
333 @end group
335 @group
336 /* @r{Return true if all processes in the job have completed.}  */
338 job_is_completed (job *j)
340   process *p;
341   
342   for (p = j->first_process; p; p = p->next)
343     if (!p->completed)
344       return 0;
345   return 1;
347 @end group
348 @end smallexample
351 @node Initializing the Shell, Launching Jobs, Data Structures, Implementing a Shell
352 @subsection Initializing the Shell
353 @cindex job control, enabling
354 @cindex subshell
356 When a shell program that normally performs job control is started, it
357 has to be careful in case it has been invoked from another shell that is
358 already doing its own job control.  
360 A subshell that runs interactively has to ensure that it has been placed
361 in the foreground by its parent shell before it can enable job control
362 itself.  It does this by getting its initial process group ID with the
363 @code{getpgrp} function, and comparing it to the process group ID of the
364 current foreground job associated with its controlling terminal (which
365 can be retrieved using the @code{tcgetpgrp} function).
367 If the subshell is not running as a foreground job, it must stop itself
368 by sending a @code{SIGTTIN} signal to its own process group.  It may not
369 arbitrarily put itself into the foreground; it must wait for the user to
370 tell the parent shell to do this.  If the subshell is continued again,
371 it should repeat the check and stop itself again if it is still not in
372 the foreground.
374 @cindex job control, enabling
375 Once the subshell has been placed into the foreground by its parent
376 shell, it can enable its own job control.  It does this by calling
377 @code{setpgid} to put itself into its own process group, and then
378 calling @code{tcsetpgrp} to place this process group into the
379 foreground.
381 When a shell enables job control, it should set itself to ignore all the
382 job control stop signals so that it doesn't accidentally stop itself.
383 You can do this by setting the action for all the stop signals to
384 @code{SIG_IGN}.
386 A subshell that runs non-interactively cannot and should not support job
387 control.  It must leave all processes it creates in the same process
388 group as the shell itself; this allows the non-interactive shell and its
389 child processes to be treated as a single job by the parent shell.  This
390 is easy to do---just don't use any of the job control primitives---but
391 you must remember to make the shell do it.
394 Here is the initialization code for the sample shell that shows how to
395 do all of this.
397 @smallexample
398 /* @r{Keep track of attributes of the shell.}  */
400 #include <sys/types.h>
401 #include <termios.h>
402 #include <unistd.h>
404 pid_t shell_pgid;
405 struct termios shell_tmodes;
406 int shell_terminal;
407 int shell_is_interactive;
410 /* @r{Make sure the shell is running interactively as the foreground job}
411    @r{before proceeding.} */
413 void
414 init_shell ()
416   
417   /* @r{See if we are running interactively.}  */
418   shell_terminal = STDIN_FILENO;
419   shell_is_interactive = isatty (shell_terminal);
421   if (shell_is_interactive)
422     @{
423       /* @r{Loop until we are in the foreground.}  */
424       while (tcgetpgrp (shell_terminal) != (shell_pgid = getpgrp ()))
425         kill (- shell_pgid, SIGTTIN);
427       /* @r{Ignore interactive and job-control signals.}  */
428       signal (SIGINT, SIG_IGN);
429       signal (SIGQUIT, SIG_IGN);
430       signal (SIGTSTP, SIG_IGN);
431       signal (SIGTTIN, SIG_IGN);
432       signal (SIGTTOU, SIG_IGN);
433       signal (SIGCHLD, SIG_IGN);
435       /* @r{Put ourselves in our own process group.}  */
436       shell_pgid = getpid ();
437       if (setpgid (shell_pgid, shell_pgid) < 0)
438         @{
439           perror ("Couldn't put the shell in its own process group");
440           exit (1);
441         @}
443       /* @r{Grab control of the terminal.}  */
444       tcsetpgrp (shell_terminal, shell_pgid);
446       /* @r{Save default terminal attributes for shell.}  */
447       tcgetattr (shell_terminal, &shell_tmodes);
448     @}
450 @end smallexample
453 @node Launching Jobs, Foreground and Background, Initializing the Shell, Implementing a Shell
454 @subsection Launching Jobs
455 @cindex launching jobs
457 Once the shell has taken responsibility for performing job control on
458 its controlling terminal, it can launch jobs in response to commands
459 typed by the user.
461 To create the processes in a process group, you use the same @code{fork}
462 and @code{exec} functions described in @ref{Process Creation Concepts}.
463 Since there are multiple child processes involved, though, things are a
464 little more complicated and you must be careful to do things in the
465 right order.  Otherwise, nasty race conditions can result.
467 You have two choices for how to structure the tree of parent-child
468 relationships among the processes.  You can either make all the
469 processes in the process group be children of the shell process, or you
470 can make one process in group be the ancestor of all the other processes
471 in that group.  The sample shell program presented in this chapter uses
472 the first approach because it makes bookkeeping somewhat simpler.
474 @cindex process group leader
475 @cindex process group ID
476 As each process is forked, it should put itself in the new process group
477 by calling @code{setpgid}; see @ref{Process Group Functions}.  The first
478 process in the new group becomes its @dfn{process group leader}, and its
479 process ID becomes the @dfn{process group ID} for the group.
481 @cindex race conditions, relating to job control
482 The shell should also call @code{setpgid} to put each of its child
483 processes into the new process group.  This is because there is a
484 potential timing problem: each child process must be put in the process
485 group before it begins executing a new program, and the shell depends on
486 having all the child processes in the group before it continues
487 executing.  If both the child processes and the shell call
488 @code{setpgid}, this ensures that the right things happen no matter which
489 process gets to it first.
491 If the job is being launched as a foreground job, the new process group
492 also needs to be put into the foreground on the controlling terminal
493 using @code{tcsetpgrp}.  Again, this should be done by the shell as well
494 as by each of its child processes, to avoid race conditions.
496 The next thing each child process should do is to reset its signal
497 actions.
499 During initialization, the shell process set itself to ignore job
500 control signals; see @ref{Initializing the Shell}.  As a result, any child
501 processes it creates also ignore these signals by inheritance.  This is
502 definitely undesirable, so each child process should explicitly set the
503 actions for these signals back to @code{SIG_DFL} just after it is forked.
505 Since shells follow this convention, applications can assume that they
506 inherit the correct handling of these signals from the parent process.
507 But every application has a responsibility not to mess up the handling
508 of stop signals.  Applications that disable the normal interpretation of
509 the SUSP character should provide some other mechanism for the user to
510 stop the job.  When the user invokes this mechanism, the program should
511 send a @code{SIGTSTP} signal to the process group of the process, not
512 just to the process itself.  @xref{Signaling Another Process}.
514 Finally, each child process should call @code{exec} in the normal way.
515 This is also the point at which redirection of the standard input and 
516 output channels should be handled.  @xref{Duplicating Descriptors},
517 for an explanation of how to do this.
519 Here is the function from the sample shell program that is responsible
520 for launching a program.  The function is executed by each child process
521 immediately after it has been forked by the shell, and never returns.
523 @smallexample
524 void
525 launch_process (process *p, pid_t pgid,
526                 int infile, int outfile, int errfile,
527                 int foreground)
529   pid_t pid;
531   if (shell_is_interactive)
532     @{
533       /* @r{Put the process into the process group and give the process group}
534          @r{the terminal, if appropriate.}
535          @r{This has to be done both by the shell and in the individual}
536          @r{child processes because of potential race conditions.}  */
537       pid = getpid ();
538       if (pgid == 0) pgid = pid;
539       setpgid (pid, pgid);
540       if (foreground)
541         tcsetpgrp (shell_terminal, pgid);
543       /* @r{Set the handling for job control signals back to the default.}  */
544       signal (SIGINT, SIG_DFL);
545       signal (SIGQUIT, SIG_DFL);
546       signal (SIGTSTP, SIG_DFL);
547       signal (SIGTTIN, SIG_DFL);
548       signal (SIGTTOU, SIG_DFL);
549       signal (SIGCHLD, SIG_DFL);
550     @}
552   /* @r{Set the standard input/output channels of the new process.}  */
553   if (infile != STDIN_FILENO)
554     @{
555       dup2 (infile, STDIN_FILENO);
556       close (infile);
557     @}
558   if (outfile != STDOUT_FILENO)
559     @{
560       dup2 (outfile, STDOUT_FILENO);
561       close (outfile);
562     @}
563   if (errfile != STDERR_FILENO)
564     @{
565       dup2 (errfile, STDERR_FILENO);
566       close (errfile);
567     @}    
568   
569   /* @r{Exec the new process.  Make sure we exit.}  */ 
570   execvp (p->argv[0], p->argv);
571   perror ("execvp");
572   exit (1);
574 @end smallexample
576 If the shell is not running interactively, this function does not do
577 anything with process groups or signals.  Remember that a shell not
578 performing job control must keep all of its subprocesses in the same
579 process group as the shell itself.
581 Next, here is the function that actually launches a complete job.
582 After creating the child processes, this function calls some other
583 functions to put the newly created job into the foreground or background;
584 these are discussed in @ref{Foreground and Background}.
586 @smallexample
587 void
588 launch_job (job *j, int foreground)
590   process *p;
591   pid_t pid;
592   int mypipe[2], infile, outfile;
593   
594   infile = j->stdin;
595   for (p = j->first_process; p; p = p->next)
596     @{
597       /* @r{Set up pipes, if necessary.}  */
598       if (p->next)
599         @{
600           if (pipe (mypipe) < 0)
601             @{
602               perror ("pipe");
603               exit (1);
604             @}
605           outfile = mypipe[1];
606         @}
607       else
608         outfile = j->stdout;
610       /* @r{Fork the child processes.}  */
611       pid = fork ();
612       if (pid == 0)
613         /* @r{This is the child process.}  */
614         launch_process (p, j->pgid, infile,
615                         outfile, j->stderr, foreground);
616       else if (pid < 0)
617         @{
618           /* @r{The fork failed.}  */
619           perror ("fork");
620           exit (1);
621         @}
622       else
623         @{
624           /* @r{This is the parent process.}  */
625           p->pid = pid;
626           if (shell_is_interactive)
627             @{
628               if (!j->pgid)
629                 j->pgid = pid;
630               setpgid (pid, j->pgid);
631             @}
632         @}
634       /* @r{Clean up after pipes.}  */
635       if (infile != j->stdin)
636         close (infile);
637       if (outfile != j->stdout)
638         close (outfile);
639       infile = mypipe[0];
640     @}
641   
642   format_job_info (j, "launched");
644   if (!shell_is_interactive)
645     wait_for_job (j);
646   else if (foreground)
647     put_job_in_foreground (j, 0);
648   else
649     put_job_in_background (j, 0);
651 @end smallexample
654 @node Foreground and Background, Stopped and Terminated Jobs, Launching Jobs, Implementing a Shell
655 @subsection Foreground and Background
657 Now let's consider what actions must be taken by the shell when it
658 launches a job into the foreground, and how this differs from what
659 must be done when a background job is launched.
661 @cindex foreground job, launching
662 When a foreground job is launched, the shell must first give it access
663 to the controlling terminal by calling @code{tcsetpgrp}.  Then, the
664 shell should wait for processes in that process group to terminate or
665 stop.  This is discussed in more detail in @ref{Stopped and Terminated
666 Jobs}.
668 When all of the processes in the group have either completed or stopped,
669 the shell should regain control of the terminal for its own process
670 group by calling @code{tcsetpgrp} again.  Since stop signals caused by
671 I/O from a background process or a SUSP character typed by the user
672 are sent to the process group, normally all the processes in the job
673 stop together.
675 The foreground job may have left the terminal in a strange state, so the
676 shell should restore its own saved terminal modes before continuing.  In
677 case the job is merely been stopped, the shell should first save the
678 current terminal modes so that it can restore them later if the job is
679 continued.  The functions for dealing with terminal modes are
680 @code{tcgetattr} and @code{tcsetattr}; these are described in
681 @ref{Terminal Modes}.
683 Here is the sample shell's function for doing all of this.
685 @smallexample
686 @group
687 /* @r{Put job @var{j} in the foreground.  If @var{cont} is nonzero,}
688    @r{restore the saved terminal modes and send the process group a}
689    @r{@code{SIGCONT} signal to wake it up before we block.}  */
691 void
692 put_job_in_foreground (job *j, int cont)
694   /* @r{Put the job into the foreground.}  */
695   tcsetpgrp (shell_terminal, j->pgid);
696 @end group
698 @group
699   /* @r{Send the job a continue signal, if necessary.}  */
700   if (cont)
701     @{
702       tcsetattr (shell_terminal, TCSADRAIN, &j->tmodes);
703       if (kill (- j->pgid, SIGCONT) < 0)
704         perror ("kill (SIGCONT)");
705     @}
706 @end group
707   
708   /* @r{Wait for it to report.}  */
709   wait_for_job (j);
710     
711   /* @r{Put the shell back in the foreground.}  */
712   tcsetpgrp (shell_terminal, shell_pgid);
713     
714 @group
715   /* @r{Restore the shell's terminal modes.}  */
716   tcgetattr (shell_terminal, &j->tmodes);
717   tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes);
719 @end group
720 @end smallexample
722 @cindex background job, launching
723 If the process group is launched as a background job, the shell should
724 remain in the foreground itself and continue to read commands from
725 the terminal.  
727 In the sample shell, there is not much that needs to be done to put
728 a job into the background.  Here is the function it uses:
730 @smallexample
731 /* @r{Put a job in the background.  If the cont argument is true, send}
732    @r{the process group a @code{SIGCONT} signal to wake it up.}  */
734 void
735 put_job_in_background (job *j, int cont)
737   /* @r{Send the job a continue signal, if necessary.}  */
738   if (cont)
739     if (kill (-j->pgid, SIGCONT) < 0)
740       perror ("kill (SIGCONT)");
742 @end smallexample
745 @node Stopped and Terminated Jobs, Continuing Stopped Jobs, Foreground and Background, Implementing a Shell
746 @subsection Stopped and Terminated Jobs
748 @cindex stopped jobs, detecting
749 @cindex terminated jobs, detecting
750 When a foreground process is launched, the shell must block until all of
751 the processes in that job have either terminated or stopped.  It can do
752 this by calling the @code{waitpid} function; see @ref{Process
753 Completion}.  Use the @code{WUNTRACED} option so that status is reported
754 for processes that stop as well as processes that terminate.
756 The shell must also check on the status of background jobs so that it
757 can report terminated and stopped jobs to the user; this can be done by
758 calling @code{waitpid} with the @code{WNOHANG} option.  A good place to
759 put a such a check for terminated and stopped jobs is just before
760 prompting for a new command.
762 @cindex @code{SIGCHLD}, handling of
763 The shell can also receive asynchronous notification that there is
764 status information available for a child process by establishing a
765 handler for @code{SIGCHLD} signals.  @xref{Signal Handling}.
767 In the sample shell program, the @code{SIGCHLD} signal is normally
768 ignored.  This is to avoid reentrancy problems involving the global data
769 structures the shell manipulates.  But at specific times when the shell
770 is not using these data structures---such as when it is waiting for
771 input on the terminal---it makes sense to enable a handler for
772 @code{SIGCHLD}.  The same function that is used to do the synchronous
773 status checks (@code{do_job_notification}, in this case) can also be
774 called from within this handler.
776 Here are the parts of the sample shell program that deal with checking
777 the status of jobs and reporting the information to the user.
779 @smallexample
780 @group
781 /* @r{Store the status of the process @var{pid} that was returned by waitpid.}
782    @r{Return 0 if all went well, nonzero otherwise.}  */
785 mark_process_status (pid_t pid, int status)
787   job *j;
788   process *p;
789 @end group
791 @group
792   if (pid > 0)
793     @{
794       /* @r{Update the record for the process.}  */
795       for (j = first_job; j; j = j->next)
796         for (p = j->first_process; p; p = p->next)
797           if (p->pid == pid)
798             @{
799               p->status = status;
800               if (WIFSTOPPED (status))
801                 p->stopped = 1;
802               else
803                 @{
804                   p->completed = 1;
805                   if (WIFSIGNALED (status))
806                     fprintf (stderr, "%d: Terminated by signal %d.\n",
807                              (int) pid, WTERMSIG (p->status));
808                 @}
809               return 0;
810              @}
811       fprintf (stderr, "No child process %d.\n", pid);
812       return -1;
813     @}
814 @end group
815 @group
816   else if (pid == 0 || errno == ECHILD)
817     /* @r{No processes ready to report.}  */
818     return -1;
819   else @{
820     /* @r{Other weird errors.}  */
821     perror ("waitpid");
822     return -1;
823   @}
825 @end group
827 @group
828 /* @r{Check for processes that have status information available,}
829    @r{without blocking.}  */
831 void
832 update_status (void)
834   int status;
835   pid_t pid;
836   
837   do
838     pid = waitpid (WAIT_ANY, &status, WUNTRACED|WNOHANG);
839   while (!mark_process_status (pid, status));
841 @end group
843 @group
844 /* @r{Check for processes that have status information available,}
845    @r{blocking until all processes in the given job have reported.}  */
847 void
848 wait_for_job (job *j)
850   int status;
851   pid_t pid;
852   
853   do
854     pid = waitpid (WAIT_ANY, &status, WUNTRACED);
855   while (!mark_process_status (pid, status) 
856          && !job_is_stopped (j) 
857          && !job_is_completed (j));
859 @end group
861 @group
862 /* @r{Format information about job status for the user to look at.}  */
864 void
865 format_job_info (job *j, const char *status)
867   fprintf (stderr, "%ld (%s): %s\n", (long)j->pgid, status, j->command);
869 @end group
871 @group
872 /* @r{Notify the user about stopped or terminated jobs.}
873    @r{Delete terminated jobs from the active job list.}  */
875 void
876 do_job_notification (void)
878   job *j, *jlast, *jnext;
879   process *p;
881   /* @r{Update status information for child processes.}  */
882   update_status ();
883   
884   jlast = NULL;
885   for (j = first_job; j; j = jnext)
886     @{
887       jnext = j->next;
889       /* @r{If all processes have completed, tell the user the job has}
890          @r{completed and delete it from the list of active jobs.}  */
891       if (job_is_completed (j)) @{
892         format_job_info (j, "completed");
893         if (jlast)
894           jlast->next = jnext;
895         else
896           first_job = jnext;
897         free_job (j);
898       @}
900       /* @r{Notify the user about stopped jobs,}
901          @r{marking them so that we won't do this more than once.}  */
902       else if (job_is_stopped (j) && !j->notified) @{
903         format_job_info (j, "stopped");
904         j->notified = 1;
905         jlast = j;
906       @}
908       /* @r{Don't say anything about jobs that are still running.}  */
909       else
910         jlast = j;
911     @}
913 @end group
914 @end smallexample
916 @node Continuing Stopped Jobs, Missing Pieces, Stopped and Terminated Jobs, Implementing a Shell
917 @subsection Continuing Stopped Jobs
919 @cindex stopped jobs, continuing
920 The shell can continue a stopped job by sending a @code{SIGCONT} signal
921 to its process group.  If the job is being continued in the foreground,
922 the shell should first invoke @code{tcsetpgrp} to give the job access to
923 the terminal, and restore the saved terminal settings.  After continuing
924 a job in the foreground, the shell should wait for the job to stop or
925 complete, as if the job had just been launched in the foreground.
927 The sample shell program handles both newly created and continued jobs
928 with the same pair of functions, @w{@code{put_job_in_foreground}} and
929 @w{@code{put_job_in_background}}.  The definitions of these functions
930 were given in @ref{Foreground and Background}.  When continuing a
931 stopped job, a nonzero value is passed as the @var{cont} argument to
932 ensure that the @code{SIGCONT} signal is sent and the terminal modes
933 reset, as appropriate.
935 This leaves only a function for updating the shell's internal bookkeeping
936 about the job being continued:
938 @smallexample
939 @group
940 /* @r{Mark a stopped job J as being running again.}  */
942 void
943 mark_job_as_running (job *j)
945   Process *p;
947   for (p = j->first_process; p; p = p->next)
948     p->stopped = 0;
949   j->notified = 0;
951 @end group
953 @group
954 /* @r{Continue the job J.}  */
956 void
957 continue_job (job *j, int foreground)
959   mark_job_as_running (j);
960   if (foreground)
961     put_job_in_foreground (j, 1);
962   else
963     put_job_in_background (j, 1);
965 @end group
966 @end smallexample
968 @node Missing Pieces,  , Continuing Stopped Jobs, Implementing a Shell
969 @subsection The Missing Pieces
971 The code extracts for the sample shell included in this chapter are only
972 a part of the entire shell program.  In particular, nothing at all has
973 been said about how @code{job} and @code{program} data structures are
974 allocated and initialized.
976 Most real shells provide a complex user interface that has support for
977 a command language; variables; abbreviations, substitutions, and pattern
978 matching on file names; and the like.  All of this is far too complicated
979 to explain here!  Instead, we have concentrated on showing how to 
980 implement the core process creation and job control functions that can
981 be called from such a shell.
983 Here is a table summarizing the major entry points we have presented:
985 @table @code
986 @item void init_shell (void)
987 Initialize the shell's internal state.  @xref{Initializing the
988 Shell}.
990 @item void launch_job (job *@var{j}, int @var{foreground})
991 Launch the job @var{j} as either a foreground or background job.
992 @xref{Launching Jobs}.
994 @item void do_job_notification (void)
995 Check for and report any jobs that have terminated or stopped.  Can be
996 called synchronously or within a handler for @code{SIGCHLD} signals.
997 @xref{Stopped and Terminated Jobs}.
999 @item void continue_job (job *@var{j}, int @var{foreground})
1000 Continue the job @var{j}.  @xref{Continuing Stopped Jobs}.
1001 @end table
1003 Of course, a real shell would also want to provide other functions for
1004 managing jobs.  For example, it would be useful to have commands to list
1005 all active jobs or to send a signal (such as @code{SIGKILL}) to a job.
1008 @node Functions for Job Control,  , Implementing a Shell, Job Control
1009 @section Functions for Job Control
1010 @cindex process group functions
1011 @cindex job control functions
1013 This section contains detailed descriptions of the functions relating
1014 to job control.
1016 @menu
1017 * Identifying the Terminal::    Determining the controlling terminal's name.
1018 * Process Group Functions::     Functions for manipulating process groups.
1019 * Terminal Access Functions::   Functions for controlling terminal access.
1020 @end menu
1023 @node Identifying the Terminal, Process Group Functions,  , Functions for Job Control
1024 @subsection Identifying the Controlling Terminal
1025 @cindex controlling terminal, determining
1027 You can use the @code{ctermid} function to get a file name that you can
1028 use to open the controlling terminal.  In the GNU library, it returns
1029 the same string all the time: @code{"/dev/tty"}.  That is a special
1030 ``magic'' file name that refers to the controlling terminal of the
1031 current process (if it has one).  To find the name of the specific
1032 terminal device, use @code{ttyname}; @pxref{Is It a Terminal}.
1034 The function @code{ctermid} is declared in the header file
1035 @file{stdio.h}.
1036 @pindex stdio.h
1038 @comment stdio.h
1039 @comment POSIX.1
1040 @deftypefun {char *} ctermid (char *@var{string})
1041 The @code{ctermid} function returns a string containing the file name of
1042 the controlling terminal for the current process.  If @var{string} is
1043 not a null pointer, it should be an array that can hold at least
1044 @code{L_ctermid} characters; the string is returned in this array.
1045 Otherwise, a pointer to a string in a static area is returned, which
1046 might get overwritten on subsequent calls to this function.
1048 An empty string is returned if the file name cannot be determined for
1049 any reason.  Even if a file name is returned, access to the file it
1050 represents is not guaranteed.
1051 @end deftypefun
1053 @comment stdio.h
1054 @comment POSIX.1
1055 @deftypevr Macro int L_ctermid
1056 The value of this macro is an integer constant expression that
1057 represents the size of a string large enough to hold the file name
1058 returned by @code{ctermid}.
1059 @end deftypevr
1061 See also the @code{isatty} and @code{ttyname} functions, in 
1062 @ref{Is It a Terminal}.
1065 @node Process Group Functions, Terminal Access Functions, Identifying the Terminal, Functions for Job Control
1066 @subsection Process Group Functions
1068 Here are descriptions of the functions for manipulating process groups.
1069 Your program should include the header files @file{sys/types.h} and
1070 @file{unistd.h} to use these functions.
1071 @pindex unistd.h
1072 @pindex sys/types.h
1074 @comment unistd.h
1075 @comment POSIX.1
1076 @deftypefun pid_t setsid (void)
1077 The @code{setsid} function creates a new session.  The calling process
1078 becomes the session leader, and is put in a new process group whose
1079 process group ID is the same as the process ID of that process.  There
1080 are initially no other processes in the new process group, and no other
1081 process groups in the new session.
1083 This function also makes the calling process have no controlling terminal.
1085 The @code{setsid} function returns the new process group ID of the
1086 calling process if successful.  A return value of @code{-1} indicates an
1087 error.  The following @code{errno} error conditions are defined for this
1088 function:
1090 @table @code
1091 @item EPERM
1092 The calling process is already a process group leader, or there is
1093 already another process group around that has the same process group ID.
1094 @end table
1095 @end deftypefun
1097 The @code{getpgrp} function has two definitions: one derived from BSD
1098 Unix, and one from the POSIX.1 standard.  The feature test macros you
1099 have selected (@pxref{Feature Test Macros}) determine which definition
1100 you get.  Specifically, you get the BSD version if you define
1101 @code{_BSD_SOURCE}; otherwise, you get the POSIX version if you define
1102 @code{_POSIX_SOURCE} or @code{_GNU_SOURCE}.  Programs written for old
1103 BSD systems will not include @file{unistd.h}, which defines
1104 @code{getpgrp} specially under @code{_BSD_SOURCE}.  You must link such
1105 programs with the @code{-lbsd-compat} option to get the BSD definition.@refill
1106 @pindex -lbsd-compat
1107 @pindex bsd-compat
1108 @cindex BSD compatibility library
1110 @comment unistd.h
1111 @comment POSIX.1
1112 @deftypefn {POSIX.1 Function} pid_t getpgrp (void)
1113 The POSIX.1 definition of @code{getpgrp} returns the process group ID of
1114 the calling process.
1115 @end deftypefn
1117 @comment unistd.h
1118 @comment BSD
1119 @deftypefn {BSD Function} pid_t getpgrp (pid_t @var{pid})
1120 The BSD definition of @code{getpgrp} returns the process group ID of the
1121 process @var{pid}.  You can supply a value of @code{0} for the @var{pid}
1122 argument to get information about the calling process.
1123 @end deftypefn
1125 @comment unistd.h
1126 @comment POSIX.1
1127 @deftypefun int setpgid (pid_t @var{pid}, pid_t @var{pgid})
1128 The @code{setpgid} function puts the process @var{pid} into the process
1129 group @var{pgid}.  As a special case, either @var{pid} or @var{pgid} can
1130 be zero to indicate the process ID of the calling process.
1132 This function fails on a system that does not support job control.
1133 @xref{Job Control is Optional}, for more information.
1135 If the operation is successful, @code{setpgid} returns zero.  Otherwise
1136 it returns @code{-1}.  The following @code{errno} error conditions are
1137 defined for this function:
1139 @table @code
1140 @item EACCES
1141 The child process named by @var{pid} has executed an @code{exec}
1142 function since it was forked.
1144 @item EINVAL
1145 The value of the @var{pgid} is not valid.
1147 @item ENOSYS
1148 The system doesn't support job control.
1150 @item EPERM
1151 The process indicated by the @var{pid} argument is a session leader,
1152 or is not in the same session as the calling process, or the value of
1153 the @var{pgid} argument doesn't match a process group ID in the same
1154 session as the calling process.
1156 @item ESRCH
1157 The process indicated by the @var{pid} argument is not the calling
1158 process or a child of the calling process.
1159 @end table
1160 @end deftypefun
1162 @comment unistd.h
1163 @comment BSD
1164 @deftypefun int setpgrp (pid_t @var{pid}, pid_t @var{pgid})
1165 This is the BSD Unix name for @code{setpgid}.  Both functions do exactly
1166 the same thing.
1167 @end deftypefun
1170 @node Terminal Access Functions,  , Process Group Functions, Functions for Job Control
1171 @subsection Functions for Controlling Terminal Access
1173 These are the functions for reading or setting the foreground
1174 process group of a terminal.  You should include the header files
1175 @file{sys/types.h} and @file{unistd.h} in your application to use
1176 these functions.
1177 @pindex unistd.h
1178 @pindex sys/types.h
1180 Although these functions take a file descriptor argument to specify
1181 the terminal device, the foreground job is associated with the terminal
1182 file itself and not a particular open file descriptor.
1184 @comment unistd.h
1185 @comment POSIX.1
1186 @deftypefun pid_t tcgetpgrp (int @var{filedes})
1187 This function returns the process group ID of the foreground process
1188 group associated with the terminal open on descriptor @var{filedes}.
1190 If there is no foreground process group, the return value is a number
1191 greater than @code{1} that does not match the process group ID of any
1192 existing process group.  This can happen if all of the processes in the
1193 job that was formerly the foreground job have terminated, and no other
1194 job has yet been moved into the foreground.
1196 In case of an error, a value of @code{-1} is returned.  The
1197 following @code{errno} error conditions are defined for this function:
1199 @table @code
1200 @item EBADF
1201 The @var{filedes} argument is not a valid file descriptor.
1203 @item ENOSYS
1204 The system doesn't support job control.
1206 @item ENOTTY
1207 The terminal file associated with the @var{filedes} argument isn't the
1208 controlling terminal of the calling process.
1209 @end table
1210 @end deftypefun
1212 @comment unistd.h
1213 @comment POSIX.1
1214 @deftypefun int tcsetpgrp (int @var{filedes}, pid_t @var{pgid})
1215 This function is used to set a terminal's foreground process group ID.
1216 The argument @var{filedes} is a descriptor which specifies the terminal;
1217 @var{pgid} specifies the process group.  The calling process must be a
1218 member of the same session as @var{pgid} and must have the same
1219 controlling terminal.
1221 For terminal access purposes, this function is treated as output.  If it
1222 is called from a background process on its controlling terminal,
1223 normally all processes in the process group are sent a @code{SIGTTOU}
1224 signal.  The exception is if the calling process itself is ignoring or
1225 blocking @code{SIGTTOU} signals, in which case the operation is
1226 performed and no signal is sent.
1228 If successful, @code{tcsetpgrp} returns @code{0}.  A return value of
1229 @code{-1} indicates an error.  The following @code{errno} error
1230 conditions are defined for this function:
1232 @table @code
1233 @item EBADF
1234 The @var{filedes} argument is not a valid file descriptor.
1236 @item EINVAL
1237 The @var{pgid} argument is not valid.
1239 @item ENOSYS
1240 The system doesn't support job control.
1242 @item ENOTTY
1243 The @var{filedes} isn't the controlling terminal of the calling process.
1245 @item EPERM
1246 The @var{pgid} isn't a process group in the same session as the calling
1247 process.
1248 @end table
1249 @end deftypefun