1 @node Job Control, Name Service Switch, Inter-Process Communication, Top
2 @c %MENU% All about process groups and sessions
9 @dfn{Job control} refers to the protocol for allowing a user to move
10 between multiple @dfn{process groups} (or @dfn{jobs}) within a single
11 @dfn{login session}. The job control facilities are set up so that
12 appropriate behavior for most programs happens automatically and they
13 need not do anything special about job control. So you can probably
14 ignore the material in this chapter unless you are writing a shell or
17 You need to be familiar with concepts relating to process creation
18 (@pxref{Process Creation Concepts}) and signal handling (@pxref{Signal
19 Handling}) in order to understand this material presented in this
22 @vindex _POSIX_JOB_CONTROL
23 Some old systems do not support job control, but @gnusystems{} always
24 have, and it is a required feature in the 2001 revision of POSIX.1
25 (@pxref{POSIX}). If you need to be portable to old systems, you can
26 use the @code{_POSIX_JOB_CONTROL} macro to test at compile-time
27 whether the system supports job control. @xref{System Options}.
30 * Concepts of Job Control:: Jobs can be controlled by a shell.
31 * Controlling Terminal:: How a process gets its controlling terminal.
32 * Access to the Terminal:: How processes share the controlling terminal.
33 * Orphaned Process Groups:: Jobs left after the user logs out.
34 * Implementing a Shell:: What a shell must do to implement job control.
35 * Functions for Job Control:: Functions to control process groups.
38 @node Concepts of Job Control
39 @section Concepts of Job Control
42 The fundamental purpose of an interactive shell is to read
43 commands from the user's terminal and create processes to execute the
44 programs specified by those commands. It can do this using the
45 @code{fork} (@pxref{Creating a Process}) and @code{exec}
46 (@pxref{Executing a File}) functions.
48 A single command may run just one process---but often one command uses
49 several processes. If you use the @samp{|} operator in a shell command,
50 you explicitly request several programs in their own processes. But
51 even if you run just one program, it can use multiple processes
52 internally. For example, a single compilation command such as @samp{cc
53 -c foo.c} typically uses four processes (though normally only two at any
54 given time). If you run @code{make}, its job is to run other programs
55 in separate processes.
57 The processes belonging to a single command are called a @dfn{process
58 group} or @dfn{job}. This is so that you can operate on all of them at
59 once. For example, typing @kbd{C-c} sends the signal @code{SIGINT} to
60 terminate all the processes in the foreground process group.
63 A @dfn{session} is a larger group of processes. Normally all the
64 processes that stem from a single login belong to the same session.
66 Every process belongs to a process group. When a process is created, it
67 becomes a member of the same process group and session as its parent
68 process. You can put it in another process group using the
69 @code{setpgid} function, provided the process group belongs to the same
72 @cindex session leader
73 The only way to put a process in a different session is to make it the
74 initial process of a new session, or a @dfn{session leader}, using the
75 @code{setsid} function. This also puts the session leader into a new
76 process group, and you can't move it out of that process group again.
78 Usually, new sessions are created by the system login program, and the
79 session leader is the process running the user's login shell.
81 @cindex controlling terminal
82 A shell that supports job control must arrange to control which job can
83 use the terminal at any time. Otherwise there might be multiple jobs
84 trying to read from the terminal at once, and confusion about which
85 process should receive the input typed by the user. To prevent this,
86 the shell must cooperate with the terminal driver using the protocol
87 described in this chapter.
89 @cindex foreground job
90 @cindex background job
91 The shell can give unlimited access to the controlling terminal to only
92 one process group at a time. This is called the @dfn{foreground job} on
93 that controlling terminal. Other process groups managed by the shell
94 that are executing without such access to the terminal are called
95 @dfn{background jobs}.
98 If a background job needs to read from its controlling
99 terminal, it is @dfn{stopped} by the terminal driver; if the
100 @code{TOSTOP} mode is set, likewise for writing. The user can stop
101 a foreground job by typing the SUSP character (@pxref{Special
102 Characters}) and a program can stop any job by sending it a
103 @code{SIGSTOP} signal. It's the responsibility of the shell to notice
104 when jobs stop, to notify the user about them, and to provide mechanisms
105 for allowing the user to interactively continue stopped jobs and switch
106 jobs between foreground and background.
108 @xref{Access to the Terminal}, for more information about I/O to the
109 controlling terminal.
111 @node Controlling Terminal
112 @section Controlling Terminal of a Process
114 One of the attributes of a process is its controlling terminal. Child
115 processes created with @code{fork} inherit the controlling terminal from
116 their parent process. In this way, all the processes in a session
117 inherit the controlling terminal from the session leader. A session
118 leader that has control of a terminal is called the @dfn{controlling
119 process} of that terminal.
121 @cindex controlling process
122 You generally do not need to worry about the exact mechanism used to
123 allocate a controlling terminal to a session, since it is done for you
124 by the system when you log in.
125 @c ??? How does GNU system let a process get a ctl terminal.
127 An individual process disconnects from its controlling terminal when it
128 calls @code{setsid} to become the leader of a new session.
129 @xref{Process Group Functions}.
131 @c !!! explain how it gets a new one (by opening any terminal)
132 @c ??? How you get a controlling terminal is system-dependent.
133 @c We should document how this will work in the GNU system when it is decided.
134 @c What Unix does is not clean and I don't think GNU should use that.
136 @node Access to the Terminal, Orphaned Process Groups, Controlling Terminal, Job Control
137 @section Access to the Controlling Terminal
138 @cindex controlling terminal, access to
140 Processes in the foreground job of a controlling terminal have
141 unrestricted access to that terminal; background processes do not. This
142 section describes in more detail what happens when a process in a
143 background job tries to access its controlling terminal.
145 @cindex @code{SIGTTIN}, from background job
146 When a process in a background job tries to read from its controlling
147 terminal, the process group is usually sent a @code{SIGTTIN} signal.
148 This normally causes all of the processes in that group to stop (unless
149 they handle the signal and don't stop themselves). However, if the
150 reading process is ignoring or blocking this signal, then @code{read}
151 fails with an @code{EIO} error instead.
153 @cindex @code{SIGTTOU}, from background job
154 Similarly, when a process in a background job tries to write to its
155 controlling terminal, the default behavior is to send a @code{SIGTTOU}
156 signal to the process group. However, the behavior is modified by the
157 @code{TOSTOP} bit of the local modes flags (@pxref{Local Modes}). If
158 this bit is not set (which is the default), then writing to the
159 controlling terminal is always permitted without sending a signal.
160 Writing is also permitted if the @code{SIGTTOU} signal is being ignored
161 or blocked by the writing process.
163 Most other terminal operations that a program can do are treated as
164 reading or as writing. (The description of each operation should say
167 For more information about the primitive @code{read} and @code{write}
168 functions, see @ref{I/O Primitives}.
171 @node Orphaned Process Groups, Implementing a Shell, Access to the Terminal, Job Control
172 @section Orphaned Process Groups
173 @cindex orphaned process group
175 When a controlling process terminates, its terminal becomes free and a
176 new session can be established on it. (In fact, another user could log
177 in on the terminal.) This could cause a problem if any processes from
178 the old session are still trying to use that terminal.
180 To prevent problems, process groups that continue running even after the
181 session leader has terminated are marked as @dfn{orphaned process
184 When a process group becomes an orphan, its processes are sent a
185 @code{SIGHUP} signal. Ordinarily, this causes the processes to
186 terminate. However, if a program ignores this signal or establishes a
187 handler for it (@pxref{Signal Handling}), it can continue running as in
188 the orphan process group even after its controlling process terminates;
189 but it still cannot access the terminal any more.
191 @node Implementing a Shell, Functions for Job Control, Orphaned Process Groups, Job Control
192 @section Implementing a Job Control Shell
194 This section describes what a shell must do to implement job control, by
195 presenting an extensive sample program to illustrate the concepts
201 @ref{Data Structures}, introduces the example and presents
202 its primary data structures.
205 @ref{Initializing the Shell}, discusses actions which the shell must
206 perform to prepare for job control.
209 @ref{Launching Jobs}, includes information about how to create jobs
213 @ref{Foreground and Background}, discusses what the shell should
214 do differently when launching a job in the foreground as opposed to
218 @ref{Stopped and Terminated Jobs}, discusses reporting of job status
222 @ref{Continuing Stopped Jobs}, tells you how to continue jobs that
226 @ref{Missing Pieces}, discusses other parts of the shell.
231 * Data Structures:: Introduction to the sample shell.
232 * Initializing the Shell:: What the shell must do to take
233 responsibility for job control.
234 * Launching Jobs:: Creating jobs to execute commands.
235 * Foreground and Background:: Putting a job in foreground of background.
236 * Stopped and Terminated Jobs:: Reporting job status.
237 * Continuing Stopped Jobs:: How to continue a stopped job in
238 the foreground or background.
239 * Missing Pieces:: Other parts of the shell.
242 @node Data Structures, Initializing the Shell, , Implementing a Shell
243 @subsection Data Structures for the Shell
245 All of the program examples included in this chapter are part of
246 a simple shell program. This section presents data structures
247 and utility functions which are used throughout the example.
249 The sample shell deals mainly with two data structures. The
250 @code{job} type contains information about a job, which is a
251 set of subprocesses linked together with pipes. The @code{process} type
252 holds information about a single subprocess. Here are the relevant
253 data structure declarations:
257 /* @r{A process is a single process.} */
258 typedef struct process
260 struct process *next; /* @r{next process in pipeline} */
261 char **argv; /* @r{for exec} */
262 pid_t pid; /* @r{process ID} */
263 char completed; /* @r{true if process has completed} */
264 char stopped; /* @r{true if process has stopped} */
265 int status; /* @r{reported status value} */
270 /* @r{A job is a pipeline of processes.} */
273 struct job *next; /* @r{next active job} */
274 char *command; /* @r{command line, used for messages} */
275 process *first_process; /* @r{list of processes in this job} */
276 pid_t pgid; /* @r{process group ID} */
277 char notified; /* @r{true if user told about stopped job} */
278 struct termios tmodes; /* @r{saved terminal modes} */
279 int stdin, stdout, stderr; /* @r{standard i/o channels} */
282 /* @r{The active jobs are linked into a list. This is its head.} */
283 job *first_job = NULL;
287 Here are some utility functions that are used for operating on @code{job}
292 /* @r{Find the active job with the indicated @var{pgid}.} */
294 find_job (pid_t pgid)
298 for (j = first_job; j; j = j->next)
306 /* @r{Return true if all processes in the job have stopped or completed.} */
308 job_is_stopped (job *j)
312 for (p = j->first_process; p; p = p->next)
313 if (!p->completed && !p->stopped)
320 /* @r{Return true if all processes in the job have completed.} */
322 job_is_completed (job *j)
326 for (p = j->first_process; p; p = p->next)
335 @node Initializing the Shell, Launching Jobs, Data Structures, Implementing a Shell
336 @subsection Initializing the Shell
337 @cindex job control, enabling
340 When a shell program that normally performs job control is started, it
341 has to be careful in case it has been invoked from another shell that is
342 already doing its own job control.
344 A subshell that runs interactively has to ensure that it has been placed
345 in the foreground by its parent shell before it can enable job control
346 itself. It does this by getting its initial process group ID with the
347 @code{getpgrp} function, and comparing it to the process group ID of the
348 current foreground job associated with its controlling terminal (which
349 can be retrieved using the @code{tcgetpgrp} function).
351 If the subshell is not running as a foreground job, it must stop itself
352 by sending a @code{SIGTTIN} signal to its own process group. It may not
353 arbitrarily put itself into the foreground; it must wait for the user to
354 tell the parent shell to do this. If the subshell is continued again,
355 it should repeat the check and stop itself again if it is still not in
358 @cindex job control, enabling
359 Once the subshell has been placed into the foreground by its parent
360 shell, it can enable its own job control. It does this by calling
361 @code{setpgid} to put itself into its own process group, and then
362 calling @code{tcsetpgrp} to place this process group into the
365 When a shell enables job control, it should set itself to ignore all the
366 job control stop signals so that it doesn't accidentally stop itself.
367 You can do this by setting the action for all the stop signals to
370 A subshell that runs non-interactively cannot and should not support job
371 control. It must leave all processes it creates in the same process
372 group as the shell itself; this allows the non-interactive shell and its
373 child processes to be treated as a single job by the parent shell. This
374 is easy to do---just don't use any of the job control primitives---but
375 you must remember to make the shell do it.
378 Here is the initialization code for the sample shell that shows how to
382 /* @r{Keep track of attributes of the shell.} */
384 #include <sys/types.h>
389 struct termios shell_tmodes;
391 int shell_is_interactive;
394 /* @r{Make sure the shell is running interactively as the foreground job}
395 @r{before proceeding.} */
401 /* @r{See if we are running interactively.} */
402 shell_terminal = STDIN_FILENO;
403 shell_is_interactive = isatty (shell_terminal);
405 if (shell_is_interactive)
407 /* @r{Loop until we are in the foreground.} */
408 while (tcgetpgrp (shell_terminal) != (shell_pgid = getpgrp ()))
409 kill (- shell_pgid, SIGTTIN);
411 /* @r{Ignore interactive and job-control signals.} */
412 signal (SIGINT, SIG_IGN);
413 signal (SIGQUIT, SIG_IGN);
414 signal (SIGTSTP, SIG_IGN);
415 signal (SIGTTIN, SIG_IGN);
416 signal (SIGTTOU, SIG_IGN);
417 signal (SIGCHLD, SIG_IGN);
419 /* @r{Put ourselves in our own process group.} */
420 shell_pgid = getpid ();
421 if (setpgid (shell_pgid, shell_pgid) < 0)
423 perror ("Couldn't put the shell in its own process group");
427 /* @r{Grab control of the terminal.} */
428 tcsetpgrp (shell_terminal, shell_pgid);
430 /* @r{Save default terminal attributes for shell.} */
431 tcgetattr (shell_terminal, &shell_tmodes);
437 @node Launching Jobs, Foreground and Background, Initializing the Shell, Implementing a Shell
438 @subsection Launching Jobs
439 @cindex launching jobs
441 Once the shell has taken responsibility for performing job control on
442 its controlling terminal, it can launch jobs in response to commands
445 To create the processes in a process group, you use the same @code{fork}
446 and @code{exec} functions described in @ref{Process Creation Concepts}.
447 Since there are multiple child processes involved, though, things are a
448 little more complicated and you must be careful to do things in the
449 right order. Otherwise, nasty race conditions can result.
451 You have two choices for how to structure the tree of parent-child
452 relationships among the processes. You can either make all the
453 processes in the process group be children of the shell process, or you
454 can make one process in group be the ancestor of all the other processes
455 in that group. The sample shell program presented in this chapter uses
456 the first approach because it makes bookkeeping somewhat simpler.
458 @cindex process group leader
459 @cindex process group ID
460 As each process is forked, it should put itself in the new process group
461 by calling @code{setpgid}; see @ref{Process Group Functions}. The first
462 process in the new group becomes its @dfn{process group leader}, and its
463 process ID becomes the @dfn{process group ID} for the group.
465 @cindex race conditions, relating to job control
466 The shell should also call @code{setpgid} to put each of its child
467 processes into the new process group. This is because there is a
468 potential timing problem: each child process must be put in the process
469 group before it begins executing a new program, and the shell depends on
470 having all the child processes in the group before it continues
471 executing. If both the child processes and the shell call
472 @code{setpgid}, this ensures that the right things happen no matter which
473 process gets to it first.
475 If the job is being launched as a foreground job, the new process group
476 also needs to be put into the foreground on the controlling terminal
477 using @code{tcsetpgrp}. Again, this should be done by the shell as well
478 as by each of its child processes, to avoid race conditions.
480 The next thing each child process should do is to reset its signal
483 During initialization, the shell process set itself to ignore job
484 control signals; see @ref{Initializing the Shell}. As a result, any child
485 processes it creates also ignore these signals by inheritance. This is
486 definitely undesirable, so each child process should explicitly set the
487 actions for these signals back to @code{SIG_DFL} just after it is forked.
489 Since shells follow this convention, applications can assume that they
490 inherit the correct handling of these signals from the parent process.
491 But every application has a responsibility not to mess up the handling
492 of stop signals. Applications that disable the normal interpretation of
493 the SUSP character should provide some other mechanism for the user to
494 stop the job. When the user invokes this mechanism, the program should
495 send a @code{SIGTSTP} signal to the process group of the process, not
496 just to the process itself. @xref{Signaling Another Process}.
498 Finally, each child process should call @code{exec} in the normal way.
499 This is also the point at which redirection of the standard input and
500 output channels should be handled. @xref{Duplicating Descriptors},
501 for an explanation of how to do this.
503 Here is the function from the sample shell program that is responsible
504 for launching a program. The function is executed by each child process
505 immediately after it has been forked by the shell, and never returns.
509 launch_process (process *p, pid_t pgid,
510 int infile, int outfile, int errfile,
515 if (shell_is_interactive)
517 /* @r{Put the process into the process group and give the process group}
518 @r{the terminal, if appropriate.}
519 @r{This has to be done both by the shell and in the individual}
520 @r{child processes because of potential race conditions.} */
522 if (pgid == 0) pgid = pid;
525 tcsetpgrp (shell_terminal, pgid);
527 /* @r{Set the handling for job control signals back to the default.} */
528 signal (SIGINT, SIG_DFL);
529 signal (SIGQUIT, SIG_DFL);
530 signal (SIGTSTP, SIG_DFL);
531 signal (SIGTTIN, SIG_DFL);
532 signal (SIGTTOU, SIG_DFL);
533 signal (SIGCHLD, SIG_DFL);
536 /* @r{Set the standard input/output channels of the new process.} */
537 if (infile != STDIN_FILENO)
539 dup2 (infile, STDIN_FILENO);
542 if (outfile != STDOUT_FILENO)
544 dup2 (outfile, STDOUT_FILENO);
547 if (errfile != STDERR_FILENO)
549 dup2 (errfile, STDERR_FILENO);
553 /* @r{Exec the new process. Make sure we exit.} */
554 execvp (p->argv[0], p->argv);
560 If the shell is not running interactively, this function does not do
561 anything with process groups or signals. Remember that a shell not
562 performing job control must keep all of its subprocesses in the same
563 process group as the shell itself.
565 Next, here is the function that actually launches a complete job.
566 After creating the child processes, this function calls some other
567 functions to put the newly created job into the foreground or background;
568 these are discussed in @ref{Foreground and Background}.
572 launch_job (job *j, int foreground)
576 int mypipe[2], infile, outfile;
579 for (p = j->first_process; p; p = p->next)
581 /* @r{Set up pipes, if necessary.} */
584 if (pipe (mypipe) < 0)
594 /* @r{Fork the child processes.} */
597 /* @r{This is the child process.} */
598 launch_process (p, j->pgid, infile,
599 outfile, j->stderr, foreground);
602 /* @r{The fork failed.} */
608 /* @r{This is the parent process.} */
610 if (shell_is_interactive)
614 setpgid (pid, j->pgid);
618 /* @r{Clean up after pipes.} */
619 if (infile != j->stdin)
621 if (outfile != j->stdout)
626 format_job_info (j, "launched");
628 if (!shell_is_interactive)
631 put_job_in_foreground (j, 0);
633 put_job_in_background (j, 0);
638 @node Foreground and Background, Stopped and Terminated Jobs, Launching Jobs, Implementing a Shell
639 @subsection Foreground and Background
641 Now let's consider what actions must be taken by the shell when it
642 launches a job into the foreground, and how this differs from what
643 must be done when a background job is launched.
645 @cindex foreground job, launching
646 When a foreground job is launched, the shell must first give it access
647 to the controlling terminal by calling @code{tcsetpgrp}. Then, the
648 shell should wait for processes in that process group to terminate or
649 stop. This is discussed in more detail in @ref{Stopped and Terminated
652 When all of the processes in the group have either completed or stopped,
653 the shell should regain control of the terminal for its own process
654 group by calling @code{tcsetpgrp} again. Since stop signals caused by
655 I/O from a background process or a SUSP character typed by the user
656 are sent to the process group, normally all the processes in the job
659 The foreground job may have left the terminal in a strange state, so the
660 shell should restore its own saved terminal modes before continuing. In
661 case the job is merely stopped, the shell should first save the current
662 terminal modes so that it can restore them later if the job is
663 continued. The functions for dealing with terminal modes are
664 @code{tcgetattr} and @code{tcsetattr}; these are described in
665 @ref{Terminal Modes}.
667 Here is the sample shell's function for doing all of this.
671 /* @r{Put job @var{j} in the foreground. If @var{cont} is nonzero,}
672 @r{restore the saved terminal modes and send the process group a}
673 @r{@code{SIGCONT} signal to wake it up before we block.} */
676 put_job_in_foreground (job *j, int cont)
678 /* @r{Put the job into the foreground.} */
679 tcsetpgrp (shell_terminal, j->pgid);
683 /* @r{Send the job a continue signal, if necessary.} */
686 tcsetattr (shell_terminal, TCSADRAIN, &j->tmodes);
687 if (kill (- j->pgid, SIGCONT) < 0)
688 perror ("kill (SIGCONT)");
692 /* @r{Wait for it to report.} */
695 /* @r{Put the shell back in the foreground.} */
696 tcsetpgrp (shell_terminal, shell_pgid);
699 /* @r{Restore the shell's terminal modes.} */
700 tcgetattr (shell_terminal, &j->tmodes);
701 tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes);
706 @cindex background job, launching
707 If the process group is launched as a background job, the shell should
708 remain in the foreground itself and continue to read commands from
711 In the sample shell, there is not much that needs to be done to put
712 a job into the background. Here is the function it uses:
715 /* @r{Put a job in the background. If the cont argument is true, send}
716 @r{the process group a @code{SIGCONT} signal to wake it up.} */
719 put_job_in_background (job *j, int cont)
721 /* @r{Send the job a continue signal, if necessary.} */
723 if (kill (-j->pgid, SIGCONT) < 0)
724 perror ("kill (SIGCONT)");
729 @node Stopped and Terminated Jobs, Continuing Stopped Jobs, Foreground and Background, Implementing a Shell
730 @subsection Stopped and Terminated Jobs
732 @cindex stopped jobs, detecting
733 @cindex terminated jobs, detecting
734 When a foreground process is launched, the shell must block until all of
735 the processes in that job have either terminated or stopped. It can do
736 this by calling the @code{waitpid} function; see @ref{Process
737 Completion}. Use the @code{WUNTRACED} option so that status is reported
738 for processes that stop as well as processes that terminate.
740 The shell must also check on the status of background jobs so that it
741 can report terminated and stopped jobs to the user; this can be done by
742 calling @code{waitpid} with the @code{WNOHANG} option. A good place to
743 put a such a check for terminated and stopped jobs is just before
744 prompting for a new command.
746 @cindex @code{SIGCHLD}, handling of
747 The shell can also receive asynchronous notification that there is
748 status information available for a child process by establishing a
749 handler for @code{SIGCHLD} signals. @xref{Signal Handling}.
751 In the sample shell program, the @code{SIGCHLD} signal is normally
752 ignored. This is to avoid reentrancy problems involving the global data
753 structures the shell manipulates. But at specific times when the shell
754 is not using these data structures---such as when it is waiting for
755 input on the terminal---it makes sense to enable a handler for
756 @code{SIGCHLD}. The same function that is used to do the synchronous
757 status checks (@code{do_job_notification}, in this case) can also be
758 called from within this handler.
760 Here are the parts of the sample shell program that deal with checking
761 the status of jobs and reporting the information to the user.
765 /* @r{Store the status of the process @var{pid} that was returned by waitpid.}
766 @r{Return 0 if all went well, nonzero otherwise.} */
769 mark_process_status (pid_t pid, int status)
778 /* @r{Update the record for the process.} */
779 for (j = first_job; j; j = j->next)
780 for (p = j->first_process; p; p = p->next)
784 if (WIFSTOPPED (status))
789 if (WIFSIGNALED (status))
790 fprintf (stderr, "%d: Terminated by signal %d.\n",
791 (int) pid, WTERMSIG (p->status));
795 fprintf (stderr, "No child process %d.\n", pid);
800 else if (pid == 0 || errno == ECHILD)
801 /* @r{No processes ready to report.} */
804 /* @r{Other weird errors.} */
812 /* @r{Check for processes that have status information available,}
813 @r{without blocking.} */
822 pid = waitpid (WAIT_ANY, &status, WUNTRACED|WNOHANG);
823 while (!mark_process_status (pid, status));
828 /* @r{Check for processes that have status information available,}
829 @r{blocking until all processes in the given job have reported.} */
832 wait_for_job (job *j)
838 pid = waitpid (WAIT_ANY, &status, WUNTRACED);
839 while (!mark_process_status (pid, status)
840 && !job_is_stopped (j)
841 && !job_is_completed (j));
846 /* @r{Format information about job status for the user to look at.} */
849 format_job_info (job *j, const char *status)
851 fprintf (stderr, "%ld (%s): %s\n", (long)j->pgid, status, j->command);
856 /* @r{Notify the user about stopped or terminated jobs.}
857 @r{Delete terminated jobs from the active job list.} */
860 do_job_notification (void)
862 job *j, *jlast, *jnext;
865 /* @r{Update status information for child processes.} */
869 for (j = first_job; j; j = jnext)
873 /* @r{If all processes have completed, tell the user the job has}
874 @r{completed and delete it from the list of active jobs.} */
875 if (job_is_completed (j)) @{
876 format_job_info (j, "completed");
884 /* @r{Notify the user about stopped jobs,}
885 @r{marking them so that we won't do this more than once.} */
886 else if (job_is_stopped (j) && !j->notified) @{
887 format_job_info (j, "stopped");
892 /* @r{Don't say anything about jobs that are still running.} */
900 @node Continuing Stopped Jobs, Missing Pieces, Stopped and Terminated Jobs, Implementing a Shell
901 @subsection Continuing Stopped Jobs
903 @cindex stopped jobs, continuing
904 The shell can continue a stopped job by sending a @code{SIGCONT} signal
905 to its process group. If the job is being continued in the foreground,
906 the shell should first invoke @code{tcsetpgrp} to give the job access to
907 the terminal, and restore the saved terminal settings. After continuing
908 a job in the foreground, the shell should wait for the job to stop or
909 complete, as if the job had just been launched in the foreground.
911 The sample shell program handles both newly created and continued jobs
912 with the same pair of functions, @w{@code{put_job_in_foreground}} and
913 @w{@code{put_job_in_background}}. The definitions of these functions
914 were given in @ref{Foreground and Background}. When continuing a
915 stopped job, a nonzero value is passed as the @var{cont} argument to
916 ensure that the @code{SIGCONT} signal is sent and the terminal modes
917 reset, as appropriate.
919 This leaves only a function for updating the shell's internal bookkeeping
920 about the job being continued:
924 /* @r{Mark a stopped job J as being running again.} */
927 mark_job_as_running (job *j)
931 for (p = j->first_process; p; p = p->next)
938 /* @r{Continue the job J.} */
941 continue_job (job *j, int foreground)
943 mark_job_as_running (j);
945 put_job_in_foreground (j, 1);
947 put_job_in_background (j, 1);
952 @node Missing Pieces, , Continuing Stopped Jobs, Implementing a Shell
953 @subsection The Missing Pieces
955 The code extracts for the sample shell included in this chapter are only
956 a part of the entire shell program. In particular, nothing at all has
957 been said about how @code{job} and @code{program} data structures are
958 allocated and initialized.
960 Most real shells provide a complex user interface that has support for
961 a command language; variables; abbreviations, substitutions, and pattern
962 matching on file names; and the like. All of this is far too complicated
963 to explain here! Instead, we have concentrated on showing how to
964 implement the core process creation and job control functions that can
965 be called from such a shell.
967 Here is a table summarizing the major entry points we have presented:
970 @item void init_shell (void)
971 Initialize the shell's internal state. @xref{Initializing the
974 @item void launch_job (job *@var{j}, int @var{foreground})
975 Launch the job @var{j} as either a foreground or background job.
976 @xref{Launching Jobs}.
978 @item void do_job_notification (void)
979 Check for and report any jobs that have terminated or stopped. Can be
980 called synchronously or within a handler for @code{SIGCHLD} signals.
981 @xref{Stopped and Terminated Jobs}.
983 @item void continue_job (job *@var{j}, int @var{foreground})
984 Continue the job @var{j}. @xref{Continuing Stopped Jobs}.
987 Of course, a real shell would also want to provide other functions for
988 managing jobs. For example, it would be useful to have commands to list
989 all active jobs or to send a signal (such as @code{SIGKILL}) to a job.
992 @node Functions for Job Control, , Implementing a Shell, Job Control
993 @section Functions for Job Control
994 @cindex process group functions
995 @cindex job control functions
997 This section contains detailed descriptions of the functions relating
1001 * Identifying the Terminal:: Determining the controlling terminal's name.
1002 * Process Group Functions:: Functions for manipulating process groups.
1003 * Terminal Access Functions:: Functions for controlling terminal access.
1007 @node Identifying the Terminal, Process Group Functions, , Functions for Job Control
1008 @subsection Identifying the Controlling Terminal
1009 @cindex controlling terminal, determining
1011 You can use the @code{ctermid} function to get a file name that you can
1012 use to open the controlling terminal. In @theglibc{}, it returns
1013 the same string all the time: @code{"/dev/tty"}. That is a special
1014 ``magic'' file name that refers to the controlling terminal of the
1015 current process (if it has one). To find the name of the specific
1016 terminal device, use @code{ttyname}; @pxref{Is It a Terminal}.
1018 The function @code{ctermid} is declared in the header file
1022 @deftypefun {char *} ctermid (char *@var{string})
1023 @standards{POSIX.1, stdio.h}
1024 @safety{@prelim{}@mtsafe{@mtsposix{/!string}}@assafe{}@acsafe{}}
1025 @c This function is a stub by default; the actual implementation, for
1026 @c posix systems, returns a pointer to a string literal if passed a NULL
1027 @c string. It's not clear we want to commit to being MT-Safe in the
1028 @c !string case, so maybe add mtasurace{:ctermid/!string} when we take
1029 @c prelim out, to make room for using a static buffer in the future.
1030 The @code{ctermid} function returns a string containing the file name of
1031 the controlling terminal for the current process. If @var{string} is
1032 not a null pointer, it should be an array that can hold at least
1033 @code{L_ctermid} characters; the string is returned in this array.
1034 Otherwise, a pointer to a string in a static area is returned, which
1035 might get overwritten on subsequent calls to this function.
1037 An empty string is returned if the file name cannot be determined for
1038 any reason. Even if a file name is returned, access to the file it
1039 represents is not guaranteed.
1042 @deftypevr Macro int L_ctermid
1043 @standards{POSIX.1, stdio.h}
1044 The value of this macro is an integer constant expression that
1045 represents the size of a string large enough to hold the file name
1046 returned by @code{ctermid}.
1049 See also the @code{isatty} and @code{ttyname} functions, in
1050 @ref{Is It a Terminal}.
1053 @node Process Group Functions, Terminal Access Functions, Identifying the Terminal, Functions for Job Control
1054 @subsection Process Group Functions
1056 Here are descriptions of the functions for manipulating process groups.
1057 Your program should include the header files @file{sys/types.h} and
1058 @file{unistd.h} to use these functions.
1062 @deftypefun pid_t setsid (void)
1063 @standards{POSIX.1, unistd.h}
1064 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1065 @c This is usually a direct syscall, but if a syscall is not available,
1066 @c we use a stub, or Hurd- and BSD-specific implementations. The former
1067 @c uses a mutex and a hurd critical section, and the latter issues a few
1068 @c syscalls, so both seem safe, the locking on Hurd is safe because of
1069 @c the critical section.
1070 The @code{setsid} function creates a new session. The calling process
1071 becomes the session leader, and is put in a new process group whose
1072 process group ID is the same as the process ID of that process. There
1073 are initially no other processes in the new process group, and no other
1074 process groups in the new session.
1076 This function also makes the calling process have no controlling terminal.
1078 The @code{setsid} function returns the new process group ID of the
1079 calling process if successful. A return value of @code{-1} indicates an
1080 error. The following @code{errno} error conditions are defined for this
1085 The calling process is already a process group leader, or there is
1086 already another process group around that has the same process group ID.
1090 @deftypefun pid_t getsid (pid_t @var{pid})
1091 @standards{SVID, unistd.h}
1092 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1093 @c Stub or direct syscall, except on hurd, where it is equally safe.
1095 The @code{getsid} function returns the process group ID of the session
1096 leader of the specified process. If a @var{pid} is @code{0}, the
1097 process group ID of the session leader of the current process is
1100 In case of error @code{-1} is returned and @code{errno} is set. The
1101 following @code{errno} error conditions are defined for this function:
1105 There is no process with the given process ID @var{pid}.
1107 The calling process and the process specified by @var{pid} are in
1108 different sessions, and the implementation doesn't allow to access the
1109 process group ID of the session leader of the process with ID @var{pid}
1110 from the calling process.
1114 @deftypefun pid_t getpgrp (void)
1115 @standards{POSIX.1, unistd.h}
1116 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1117 The @code{getpgrp} function returns the process group ID of
1118 the calling process.
1121 @deftypefun int getpgid (pid_t @var{pid})
1122 @standards{POSIX.1, unistd.h}
1123 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1124 @c Stub or direct syscall, except on hurd, where it is equally safe.
1126 The @code{getpgid} function
1127 returns the process group ID of the process @var{pid}. You can supply a
1128 value of @code{0} for the @var{pid} argument to get information about
1129 the calling process.
1131 In case of error @code{-1} is returned and @code{errno} is set. The
1132 following @code{errno} error conditions are defined for this function:
1136 There is no process with the given process ID @var{pid}.
1137 The calling process and the process specified by @var{pid} are in
1138 different sessions, and the implementation doesn't allow to access the
1139 process group ID of the process with ID @var{pid} from the calling
1144 @deftypefun int setpgid (pid_t @var{pid}, pid_t @var{pgid})
1145 @standards{POSIX.1, unistd.h}
1146 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1147 @c Stub or direct syscall, except on hurd, where it is equally safe.
1148 The @code{setpgid} function puts the process @var{pid} into the process
1149 group @var{pgid}. As a special case, either @var{pid} or @var{pgid} can
1150 be zero to indicate the process ID of the calling process.
1152 If the operation is successful, @code{setpgid} returns zero. Otherwise
1153 it returns @code{-1}. The following @code{errno} error conditions are
1154 defined for this function:
1158 The child process named by @var{pid} has executed an @code{exec}
1159 function since it was forked.
1162 The value of the @var{pgid} is not valid.
1165 The system doesn't support job control.
1168 The process indicated by the @var{pid} argument is a session leader,
1169 or is not in the same session as the calling process, or the value of
1170 the @var{pgid} argument doesn't match a process group ID in the same
1171 session as the calling process.
1174 The process indicated by the @var{pid} argument is not the calling
1175 process or a child of the calling process.
1179 @deftypefun int setpgrp (pid_t @var{pid}, pid_t @var{pgid})
1180 @standards{BSD, unistd.h}
1181 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1182 @c Direct syscall or setpgid wrapper.
1183 This is the BSD Unix name for @code{setpgid}. Both functions do exactly
1188 @node Terminal Access Functions, , Process Group Functions, Functions for Job Control
1189 @subsection Functions for Controlling Terminal Access
1191 These are the functions for reading or setting the foreground
1192 process group of a terminal. You should include the header files
1193 @file{sys/types.h} and @file{unistd.h} in your application to use
1198 Although these functions take a file descriptor argument to specify
1199 the terminal device, the foreground job is associated with the terminal
1200 file itself and not a particular open file descriptor.
1202 @deftypefun pid_t tcgetpgrp (int @var{filedes})
1203 @standards{POSIX.1, unistd.h}
1204 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1205 @c Stub, or ioctl on BSD and GNU/Linux.
1206 This function returns the process group ID of the foreground process
1207 group associated with the terminal open on descriptor @var{filedes}.
1209 If there is no foreground process group, the return value is a number
1210 greater than @code{1} that does not match the process group ID of any
1211 existing process group. This can happen if all of the processes in the
1212 job that was formerly the foreground job have terminated, and no other
1213 job has yet been moved into the foreground.
1215 In case of an error, a value of @code{-1} is returned. The
1216 following @code{errno} error conditions are defined for this function:
1220 The @var{filedes} argument is not a valid file descriptor.
1223 The system doesn't support job control.
1226 The terminal file associated with the @var{filedes} argument isn't the
1227 controlling terminal of the calling process.
1231 @deftypefun int tcsetpgrp (int @var{filedes}, pid_t @var{pgid})
1232 @standards{POSIX.1, unistd.h}
1233 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1234 @c Stub, or ioctl on BSD and GNU/Linux.
1235 This function is used to set a terminal's foreground process group ID.
1236 The argument @var{filedes} is a descriptor which specifies the terminal;
1237 @var{pgid} specifies the process group. The calling process must be a
1238 member of the same session as @var{pgid} and must have the same
1239 controlling terminal.
1241 For terminal access purposes, this function is treated as output. If it
1242 is called from a background process on its controlling terminal,
1243 normally all processes in the process group are sent a @code{SIGTTOU}
1244 signal. The exception is if the calling process itself is ignoring or
1245 blocking @code{SIGTTOU} signals, in which case the operation is
1246 performed and no signal is sent.
1248 If successful, @code{tcsetpgrp} returns @code{0}. A return value of
1249 @code{-1} indicates an error. The following @code{errno} error
1250 conditions are defined for this function:
1254 The @var{filedes} argument is not a valid file descriptor.
1257 The @var{pgid} argument is not valid.
1260 The system doesn't support job control.
1263 The @var{filedes} isn't the controlling terminal of the calling process.
1266 The @var{pgid} isn't a process group in the same session as the calling
1271 @deftypefun pid_t tcgetsid (int @var{fildes})
1272 @standards{Unix98, termios.h}
1273 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1274 @c Ioctl call, if available, or tcgetpgrp followed by getsid.
1275 This function is used to obtain the process group ID of the session
1276 for which the terminal specified by @var{fildes} is the controlling terminal.
1277 If the call is successful the group ID is returned. Otherwise the
1278 return value is @code{(pid_t) -1} and the global variable @code{errno}
1279 is set to the following value:
1282 The @var{filedes} argument is not a valid file descriptor.
1285 The calling process does not have a controlling terminal, or the file
1286 is not the controlling terminal.