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;
864 /* @r{Update status information for child processes.} */
868 for (j = first_job; j; j = jnext)
872 /* @r{If all processes have completed, tell the user the job has}
873 @r{completed and delete it from the list of active jobs.} */
874 if (job_is_completed (j)) @{
875 format_job_info (j, "completed");
883 /* @r{Notify the user about stopped jobs,}
884 @r{marking them so that we won't do this more than once.} */
885 else if (job_is_stopped (j) && !j->notified) @{
886 format_job_info (j, "stopped");
891 /* @r{Don't say anything about jobs that are still running.} */
899 @node Continuing Stopped Jobs, Missing Pieces, Stopped and Terminated Jobs, Implementing a Shell
900 @subsection Continuing Stopped Jobs
902 @cindex stopped jobs, continuing
903 The shell can continue a stopped job by sending a @code{SIGCONT} signal
904 to its process group. If the job is being continued in the foreground,
905 the shell should first invoke @code{tcsetpgrp} to give the job access to
906 the terminal, and restore the saved terminal settings. After continuing
907 a job in the foreground, the shell should wait for the job to stop or
908 complete, as if the job had just been launched in the foreground.
910 The sample shell program handles both newly created and continued jobs
911 with the same pair of functions, @w{@code{put_job_in_foreground}} and
912 @w{@code{put_job_in_background}}. The definitions of these functions
913 were given in @ref{Foreground and Background}. When continuing a
914 stopped job, a nonzero value is passed as the @var{cont} argument to
915 ensure that the @code{SIGCONT} signal is sent and the terminal modes
916 reset, as appropriate.
918 This leaves only a function for updating the shell's internal bookkeeping
919 about the job being continued:
923 /* @r{Mark a stopped job J as being running again.} */
926 mark_job_as_running (job *j)
930 for (p = j->first_process; p; p = p->next)
937 /* @r{Continue the job J.} */
940 continue_job (job *j, int foreground)
942 mark_job_as_running (j);
944 put_job_in_foreground (j, 1);
946 put_job_in_background (j, 1);
951 @node Missing Pieces, , Continuing Stopped Jobs, Implementing a Shell
952 @subsection The Missing Pieces
954 The code extracts for the sample shell included in this chapter are only
955 a part of the entire shell program. In particular, nothing at all has
956 been said about how @code{job} and @code{program} data structures are
957 allocated and initialized.
959 Most real shells provide a complex user interface that has support for
960 a command language; variables; abbreviations, substitutions, and pattern
961 matching on file names; and the like. All of this is far too complicated
962 to explain here! Instead, we have concentrated on showing how to
963 implement the core process creation and job control functions that can
964 be called from such a shell.
966 Here is a table summarizing the major entry points we have presented:
969 @item void init_shell (void)
970 Initialize the shell's internal state. @xref{Initializing the
973 @item void launch_job (job *@var{j}, int @var{foreground})
974 Launch the job @var{j} as either a foreground or background job.
975 @xref{Launching Jobs}.
977 @item void do_job_notification (void)
978 Check for and report any jobs that have terminated or stopped. Can be
979 called synchronously or within a handler for @code{SIGCHLD} signals.
980 @xref{Stopped and Terminated Jobs}.
982 @item void continue_job (job *@var{j}, int @var{foreground})
983 Continue the job @var{j}. @xref{Continuing Stopped Jobs}.
986 Of course, a real shell would also want to provide other functions for
987 managing jobs. For example, it would be useful to have commands to list
988 all active jobs or to send a signal (such as @code{SIGKILL}) to a job.
991 @node Functions for Job Control, , Implementing a Shell, Job Control
992 @section Functions for Job Control
993 @cindex process group functions
994 @cindex job control functions
996 This section contains detailed descriptions of the functions relating
1000 * Identifying the Terminal:: Determining the controlling terminal's name.
1001 * Process Group Functions:: Functions for manipulating process groups.
1002 * Terminal Access Functions:: Functions for controlling terminal access.
1006 @node Identifying the Terminal, Process Group Functions, , Functions for Job Control
1007 @subsection Identifying the Controlling Terminal
1008 @cindex controlling terminal, determining
1010 You can use the @code{ctermid} function to get a file name that you can
1011 use to open the controlling terminal. In @theglibc{}, it returns
1012 the same string all the time: @code{"/dev/tty"}. That is a special
1013 ``magic'' file name that refers to the controlling terminal of the
1014 current process (if it has one). To find the name of the specific
1015 terminal device, use @code{ttyname}; @pxref{Is It a Terminal}.
1017 The function @code{ctermid} is declared in the header file
1021 @deftypefun {char *} ctermid (char *@var{string})
1022 @standards{POSIX.1, stdio.h}
1023 @safety{@prelim{}@mtsafe{@mtsposix{/!string}}@assafe{}@acsafe{}}
1024 @c This function is a stub by default; the actual implementation, for
1025 @c posix systems, returns a pointer to a string literal if passed a NULL
1026 @c string. It's not clear we want to commit to being MT-Safe in the
1027 @c !string case, so maybe add mtasurace{:ctermid/!string} when we take
1028 @c prelim out, to make room for using a static buffer in the future.
1029 The @code{ctermid} function returns a string containing the file name of
1030 the controlling terminal for the current process. If @var{string} is
1031 not a null pointer, it should be an array that can hold at least
1032 @code{L_ctermid} characters; the string is returned in this array.
1033 Otherwise, a pointer to a string in a static area is returned, which
1034 might get overwritten on subsequent calls to this function.
1036 An empty string is returned if the file name cannot be determined for
1037 any reason. Even if a file name is returned, access to the file it
1038 represents is not guaranteed.
1041 @deftypevr Macro int L_ctermid
1042 @standards{POSIX.1, stdio.h}
1043 The value of this macro is an integer constant expression that
1044 represents the size of a string large enough to hold the file name
1045 returned by @code{ctermid}.
1048 See also the @code{isatty} and @code{ttyname} functions, in
1049 @ref{Is It a Terminal}.
1052 @node Process Group Functions, Terminal Access Functions, Identifying the Terminal, Functions for Job Control
1053 @subsection Process Group Functions
1055 Here are descriptions of the functions for manipulating process groups.
1056 Your program should include the header files @file{sys/types.h} and
1057 @file{unistd.h} to use these functions.
1061 @deftypefun pid_t setsid (void)
1062 @standards{POSIX.1, unistd.h}
1063 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1064 @c This is usually a direct syscall, but if a syscall is not available,
1065 @c we use a stub, or Hurd- and BSD-specific implementations. The former
1066 @c uses a mutex and a hurd critical section, and the latter issues a few
1067 @c syscalls, so both seem safe, the locking on Hurd is safe because of
1068 @c the critical section.
1069 The @code{setsid} function creates a new session. The calling process
1070 becomes the session leader, and is put in a new process group whose
1071 process group ID is the same as the process ID of that process. There
1072 are initially no other processes in the new process group, and no other
1073 process groups in the new session.
1075 This function also makes the calling process have no controlling terminal.
1077 The @code{setsid} function returns the new process group ID of the
1078 calling process if successful. A return value of @code{-1} indicates an
1079 error. The following @code{errno} error conditions are defined for this
1084 The calling process is already a process group leader, or there is
1085 already another process group around that has the same process group ID.
1089 @deftypefun pid_t getsid (pid_t @var{pid})
1090 @standards{SVID, unistd.h}
1091 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1092 @c Stub or direct syscall, except on hurd, where it is equally safe.
1094 The @code{getsid} function returns the process group ID of the session
1095 leader of the specified process. If a @var{pid} is @code{0}, the
1096 process group ID of the session leader of the current process is
1099 In case of error @code{-1} is returned and @code{errno} is set. The
1100 following @code{errno} error conditions are defined for this function:
1104 There is no process with the given process ID @var{pid}.
1106 The calling process and the process specified by @var{pid} are in
1107 different sessions, and the implementation doesn't allow to access the
1108 process group ID of the session leader of the process with ID @var{pid}
1109 from the calling process.
1113 @deftypefun pid_t getpgrp (void)
1114 @standards{POSIX.1, unistd.h}
1115 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1116 The @code{getpgrp} function returns the process group ID of
1117 the calling process.
1120 @deftypefun int getpgid (pid_t @var{pid})
1121 @standards{POSIX.1, unistd.h}
1122 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1123 @c Stub or direct syscall, except on hurd, where it is equally safe.
1125 The @code{getpgid} function
1126 returns the process group ID of the process @var{pid}. You can supply a
1127 value of @code{0} for the @var{pid} argument to get information about
1128 the calling process.
1130 In case of error @code{-1} is returned and @code{errno} is set. The
1131 following @code{errno} error conditions are defined for this function:
1135 There is no process with the given process ID @var{pid}.
1136 The calling process and the process specified by @var{pid} are in
1137 different sessions, and the implementation doesn't allow to access the
1138 process group ID of the process with ID @var{pid} from the calling
1143 @deftypefun int setpgid (pid_t @var{pid}, pid_t @var{pgid})
1144 @standards{POSIX.1, unistd.h}
1145 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1146 @c Stub or direct syscall, except on hurd, where it is equally safe.
1147 The @code{setpgid} function puts the process @var{pid} into the process
1148 group @var{pgid}. As a special case, either @var{pid} or @var{pgid} can
1149 be zero to indicate the process ID of the calling process.
1151 If the operation is successful, @code{setpgid} returns zero. Otherwise
1152 it returns @code{-1}. The following @code{errno} error conditions are
1153 defined for this function:
1157 The child process named by @var{pid} has executed an @code{exec}
1158 function since it was forked.
1161 The value of the @var{pgid} is not valid.
1164 The system doesn't support job control.
1167 The process indicated by the @var{pid} argument is a session leader,
1168 or is not in the same session as the calling process, or the value of
1169 the @var{pgid} argument doesn't match a process group ID in the same
1170 session as the calling process.
1173 The process indicated by the @var{pid} argument is not the calling
1174 process or a child of the calling process.
1178 @deftypefun int setpgrp (pid_t @var{pid}, pid_t @var{pgid})
1179 @standards{BSD, unistd.h}
1180 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1181 @c Direct syscall or setpgid wrapper.
1182 This is the BSD Unix name for @code{setpgid}. Both functions do exactly
1187 @node Terminal Access Functions, , Process Group Functions, Functions for Job Control
1188 @subsection Functions for Controlling Terminal Access
1190 These are the functions for reading or setting the foreground
1191 process group of a terminal. You should include the header files
1192 @file{sys/types.h} and @file{unistd.h} in your application to use
1197 Although these functions take a file descriptor argument to specify
1198 the terminal device, the foreground job is associated with the terminal
1199 file itself and not a particular open file descriptor.
1201 @deftypefun pid_t tcgetpgrp (int @var{filedes})
1202 @standards{POSIX.1, unistd.h}
1203 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1204 @c Stub, or ioctl on BSD and GNU/Linux.
1205 This function returns the process group ID of the foreground process
1206 group associated with the terminal open on descriptor @var{filedes}.
1208 If there is no foreground process group, the return value is a number
1209 greater than @code{1} that does not match the process group ID of any
1210 existing process group. This can happen if all of the processes in the
1211 job that was formerly the foreground job have terminated, and no other
1212 job has yet been moved into the foreground.
1214 In case of an error, a value of @code{-1} is returned. The
1215 following @code{errno} error conditions are defined for this function:
1219 The @var{filedes} argument is not a valid file descriptor.
1222 The system doesn't support job control.
1225 The terminal file associated with the @var{filedes} argument isn't the
1226 controlling terminal of the calling process.
1230 @deftypefun int tcsetpgrp (int @var{filedes}, pid_t @var{pgid})
1231 @standards{POSIX.1, unistd.h}
1232 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1233 @c Stub, or ioctl on BSD and GNU/Linux.
1234 This function is used to set a terminal's foreground process group ID.
1235 The argument @var{filedes} is a descriptor which specifies the terminal;
1236 @var{pgid} specifies the process group. The calling process must be a
1237 member of the same session as @var{pgid} and must have the same
1238 controlling terminal.
1240 For terminal access purposes, this function is treated as output. If it
1241 is called from a background process on its controlling terminal,
1242 normally all processes in the process group are sent a @code{SIGTTOU}
1243 signal. The exception is if the calling process itself is ignoring or
1244 blocking @code{SIGTTOU} signals, in which case the operation is
1245 performed and no signal is sent.
1247 If successful, @code{tcsetpgrp} returns @code{0}. A return value of
1248 @code{-1} indicates an error. The following @code{errno} error
1249 conditions are defined for this function:
1253 The @var{filedes} argument is not a valid file descriptor.
1256 The @var{pgid} argument is not valid.
1259 The system doesn't support job control.
1262 The @var{filedes} isn't the controlling terminal of the calling process.
1265 The @var{pgid} isn't a process group in the same session as the calling
1270 @deftypefun pid_t tcgetsid (int @var{fildes})
1271 @standards{Unix98, termios.h}
1272 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1273 @c Ioctl call, if available, or tcgetpgrp followed by getsid.
1274 This function is used to obtain the process group ID of the session
1275 for which the terminal specified by @var{fildes} is the controlling terminal.
1276 If the call is successful the group ID is returned. Otherwise the
1277 return value is @code{(pid_t) -1} and the global variable @code{errno}
1278 is set to the following value:
1281 The @var{filedes} argument is not a valid file descriptor.
1284 The calling process does not have a controlling terminal, or the file
1285 is not the controlling terminal.