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