| lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | @node Job Control, Name Service Switch, Inter-Process Communication, Top | 
 | 2 | @c %MENU% All about process groups and sessions | 
 | 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 | 
 | 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 | 
 | 15 | login program. | 
 | 16 |  | 
 | 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 | 
 | 20 | chapter. | 
 | 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 | 
 | 36 | The fundamental purpose of an interactive shell is to read | 
 | 37 | commands from the user's terminal and create processes to execute the | 
 | 38 | programs 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 |  | 
 | 42 | A single command may run just one process---but often one command uses | 
 | 43 | several processes.  If you use the @samp{|} operator in a shell command, | 
 | 44 | you explicitly request several programs in their own processes.  But | 
 | 45 | even if you run just one program, it can use multiple processes | 
 | 46 | internally.  For example, a single compilation command such as @samp{cc | 
 | 47 | -c foo.c} typically uses four processes (though normally only two at any | 
 | 48 | given time).  If you run @code{make}, its job is to run other programs | 
 | 49 | in separate processes. | 
 | 50 |  | 
 | 51 | The processes belonging to a single command are called a @dfn{process | 
 | 52 | group} or @dfn{job}.  This is so that you can operate on all of them at | 
 | 53 | once.  For example, typing @kbd{C-c} sends the signal @code{SIGINT} to | 
 | 54 | terminate all the processes in the foreground process group. | 
 | 55 |  | 
 | 56 | @cindex session | 
 | 57 | A @dfn{session} is a larger group of processes.  Normally all the | 
 | 58 | processes that stem from a single login belong to the same session. | 
 | 59 |  | 
 | 60 | Every process belongs to a process group.  When a process is created, it | 
 | 61 | becomes a member of the same process group and session as its parent | 
 | 62 | process.  You can put it in another process group using the | 
 | 63 | @code{setpgid} function, provided the process group belongs to the same | 
 | 64 | session. | 
 | 65 |  | 
 | 66 | @cindex session leader | 
 | 67 | The only way to put a process in a different session is to make it the | 
 | 68 | initial 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 | 
 | 70 | process group, and you can't move it out of that process group again. | 
 | 71 |  | 
 | 72 | Usually, new sessions are created by the system login program, and the | 
 | 73 | session leader is the process running the user's login shell. | 
 | 74 |  | 
 | 75 | @cindex controlling terminal | 
 | 76 | A shell that supports job control must arrange to control which job can | 
 | 77 | use the terminal at any time.  Otherwise there might be multiple jobs | 
 | 78 | trying to read from the terminal at once, and confusion about which | 
 | 79 | process should receive the input typed by the user.  To prevent this, | 
 | 80 | the shell must cooperate with the terminal driver using the protocol | 
 | 81 | described in this chapter. | 
 | 82 |  | 
 | 83 | @cindex foreground job | 
 | 84 | @cindex background job | 
 | 85 | The shell can give unlimited access to the controlling terminal to only | 
 | 86 | one process group at a time.  This is called the @dfn{foreground job} on | 
 | 87 | that controlling terminal.  Other process groups managed by the shell | 
 | 88 | that are executing without such access to the terminal are called | 
 | 89 | @dfn{background jobs}. | 
 | 90 |  | 
 | 91 | @cindex stopped job | 
 | 92 | If a background job needs to read from its controlling | 
 | 93 | terminal, it is @dfn{stopped} by the terminal driver; if the | 
 | 94 | @code{TOSTOP} mode is set, likewise for writing.  The user can stop | 
 | 95 | a foreground job by typing the SUSP character (@pxref{Special | 
 | 96 | Characters}) and a program can stop any job by sending it a | 
 | 97 | @code{SIGSTOP} signal.  It's the responsibility of the shell to notice | 
 | 98 | when jobs stop, to notify the user about them, and to provide mechanisms | 
 | 99 | for allowing the user to interactively continue stopped jobs and switch | 
 | 100 | jobs between foreground and background. | 
 | 101 |  | 
 | 102 | @xref{Access to the Terminal}, for more information about I/O to the | 
 | 103 | controlling terminal, | 
 | 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 |  | 
 | 109 | Not all operating systems support job control.  @gnusystems{} do | 
 | 110 | support job control, but if you are using @theglibc{} on some other | 
 | 111 | system, that system may not support job control itself. | 
 | 112 |  | 
 | 113 | You can use the @code{_POSIX_JOB_CONTROL} macro to test at compile-time | 
 | 114 | whether the system supports job control.  @xref{System Options}. | 
 | 115 |  | 
 | 116 | If job control is not supported, then there can be only one process | 
 | 117 | group per session, which behaves as if it were always in the foreground. | 
 | 118 | The functions for creating additional process groups simply fail with | 
 | 119 | the error code @code{ENOSYS}. | 
 | 120 |  | 
 | 121 | The macros naming the various job control signals (@pxref{Job Control | 
 | 122 | Signals}) are defined even if job control is not supported.  However, | 
 | 123 | the system never generates these signals, and attempts to send a job | 
 | 124 | control signal or examine or specify their actions report errors or do | 
 | 125 | nothing. | 
 | 126 |  | 
 | 127 |  | 
 | 128 | @node Controlling Terminal, Access to the Terminal, Job Control is Optional, Job Control | 
 | 129 | @section Controlling Terminal of a Process | 
 | 130 |  | 
 | 131 | One of the attributes of a process is its controlling terminal.  Child | 
 | 132 | processes created with @code{fork} inherit the controlling terminal from | 
 | 133 | their parent process.  In this way, all the processes in a session | 
 | 134 | inherit the controlling terminal from the session leader.  A session | 
 | 135 | leader that has control of a terminal is called the @dfn{controlling | 
 | 136 | process} of that terminal. | 
 | 137 |  | 
 | 138 | @cindex controlling process | 
 | 139 | You generally do not need to worry about the exact mechanism used to | 
 | 140 | allocate a controlling terminal to a session, since it is done for you | 
 | 141 | by the system when you log in. | 
 | 142 | @c ??? How does GNU system let a process get a ctl terminal. | 
 | 143 |  | 
 | 144 | An individual process disconnects from its controlling terminal when it | 
 | 145 | calls @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 |  | 
 | 157 | Processes in the foreground job of a controlling terminal have | 
 | 158 | unrestricted access to that terminal; background processes do not.  This | 
 | 159 | section describes in more detail what happens when a process in a | 
 | 160 | background job tries to access its controlling terminal. | 
 | 161 |  | 
 | 162 | @cindex @code{SIGTTIN}, from background job | 
 | 163 | When a process in a background job tries to read from its controlling | 
 | 164 | terminal, the process group is usually sent a @code{SIGTTIN} signal. | 
 | 165 | This normally causes all of the processes in that group to stop (unless | 
 | 166 | they handle the signal and don't stop themselves).  However, if the | 
 | 167 | reading process is ignoring or blocking this signal, then @code{read} | 
 | 168 | fails with an @code{EIO} error instead. | 
 | 169 |  | 
 | 170 | @cindex @code{SIGTTOU}, from background job | 
 | 171 | Similarly, when a process in a background job tries to write to its | 
 | 172 | controlling terminal, the default behavior is to send a @code{SIGTTOU} | 
 | 173 | signal to the process group.  However, the behavior is modified by the | 
 | 174 | @code{TOSTOP} bit of the local modes flags (@pxref{Local Modes}).  If | 
 | 175 | this bit is not set (which is the default), then writing to the | 
 | 176 | controlling terminal is always permitted without sending a signal. | 
 | 177 | Writing is also permitted if the @code{SIGTTOU} signal is being ignored | 
 | 178 | or blocked by the writing process. | 
 | 179 |  | 
 | 180 | Most other terminal operations that a program can do are treated as | 
 | 181 | reading or as writing.  (The description of each operation should say | 
 | 182 | which.) | 
 | 183 |  | 
 | 184 | For more information about the primitive @code{read} and @code{write} | 
 | 185 | functions, 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 |  | 
 | 192 | When a controlling process terminates, its terminal becomes free and a | 
 | 193 | new session can be established on it.  (In fact, another user could log | 
 | 194 | in on the terminal.)  This could cause a problem if any processes from | 
 | 195 | the old session are still trying to use that terminal. | 
 | 196 |  | 
 | 197 | To prevent problems, process groups that continue running even after the | 
 | 198 | session leader has terminated are marked as @dfn{orphaned process | 
 | 199 | groups}. | 
 | 200 |  | 
 | 201 | When a process group becomes an orphan, its processes are sent a | 
 | 202 | @code{SIGHUP} signal.  Ordinarily, this causes the processes to | 
 | 203 | terminate.  However, if a program ignores this signal or establishes a | 
 | 204 | handler for it (@pxref{Signal Handling}), it can continue running as in | 
 | 205 | the orphan process group even after its controlling process terminates; | 
 | 206 | but 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 |  | 
 | 211 | This section describes what a shell must do to implement job control, by | 
 | 212 | presenting an extensive sample program to illustrate the concepts | 
 | 213 | involved. | 
 | 214 |  | 
 | 215 | @iftex | 
 | 216 | @itemize @bullet | 
 | 217 | @item | 
 | 218 | @ref{Data Structures}, introduces the example and presents | 
 | 219 | its primary data structures. | 
 | 220 |  | 
 | 221 | @item | 
 | 222 | @ref{Initializing the Shell}, discusses actions which the shell must | 
 | 223 | perform to prepare for job control. | 
 | 224 |  | 
 | 225 | @item | 
 | 226 | @ref{Launching Jobs}, includes information about how to create jobs | 
 | 227 | to execute commands. | 
 | 228 |  | 
 | 229 | @item | 
 | 230 | @ref{Foreground and Background}, discusses what the shell should | 
 | 231 | do differently when launching a job in the foreground as opposed to | 
 | 232 | a background job. | 
 | 233 |  | 
 | 234 | @item | 
 | 235 | @ref{Stopped and Terminated Jobs}, discusses reporting of job status | 
 | 236 | back to the shell. | 
 | 237 |  | 
 | 238 | @item | 
 | 239 | @ref{Continuing Stopped Jobs}, tells you how to continue jobs that | 
 | 240 | have 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 |  | 
 | 262 | All of the program examples included in this chapter are part of | 
 | 263 | a simple shell program.  This section presents data structures | 
 | 264 | and utility functions which are used throughout the example. | 
 | 265 |  | 
 | 266 | The sample shell deals mainly with two data structures.  The | 
 | 267 | @code{job} type contains information about a job, which is a | 
 | 268 | set of subprocesses linked together with pipes.  The @code{process} type | 
 | 269 | holds information about a single subprocess.  Here are the relevant | 
 | 270 | data structure declarations: | 
 | 271 |  | 
 | 272 | @smallexample | 
 | 273 | @group | 
 | 274 | /* @r{A process is a single process.}  */ | 
 | 275 | typedef 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.}  */ | 
 | 288 | typedef 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.}   */ | 
 | 300 | job *first_job = NULL; | 
 | 301 | @end group | 
 | 302 | @end smallexample | 
 | 303 |  | 
 | 304 | Here are some utility functions that are used for operating on @code{job} | 
 | 305 | objects. | 
 | 306 |  | 
 | 307 | @smallexample | 
 | 308 | @group | 
 | 309 | /* @r{Find the active job with the indicated @var{pgid}.}  */ | 
 | 310 | job * | 
 | 311 | find_job (pid_t pgid) | 
 | 312 | @{ | 
 | 313 |   job *j; | 
 | 314 |  | 
 | 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.}  */ | 
 | 324 | int | 
 | 325 | job_is_stopped (job *j) | 
 | 326 | @{ | 
 | 327 |   process *p; | 
 | 328 |  | 
 | 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.}  */ | 
 | 338 | int | 
 | 339 | job_is_completed (job *j) | 
 | 340 | @{ | 
 | 341 |   process *p; | 
 | 342 |  | 
 | 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 |  | 
 | 357 | When a shell program that normally performs job control is started, it | 
 | 358 | has to be careful in case it has been invoked from another shell that is | 
 | 359 | already doing its own job control. | 
 | 360 |  | 
 | 361 | A subshell that runs interactively has to ensure that it has been placed | 
 | 362 | in the foreground by its parent shell before it can enable job control | 
 | 363 | itself.  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 | 
 | 365 | current foreground job associated with its controlling terminal (which | 
 | 366 | can be retrieved using the @code{tcgetpgrp} function). | 
 | 367 |  | 
 | 368 | If the subshell is not running as a foreground job, it must stop itself | 
 | 369 | by sending a @code{SIGTTIN} signal to its own process group.  It may not | 
 | 370 | arbitrarily put itself into the foreground; it must wait for the user to | 
 | 371 | tell the parent shell to do this.  If the subshell is continued again, | 
 | 372 | it should repeat the check and stop itself again if it is still not in | 
 | 373 | the foreground. | 
 | 374 |  | 
 | 375 | @cindex job control, enabling | 
 | 376 | Once the subshell has been placed into the foreground by its parent | 
 | 377 | shell, 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 | 
 | 379 | calling @code{tcsetpgrp} to place this process group into the | 
 | 380 | foreground. | 
 | 381 |  | 
 | 382 | When a shell enables job control, it should set itself to ignore all the | 
 | 383 | job control stop signals so that it doesn't accidentally stop itself. | 
 | 384 | You can do this by setting the action for all the stop signals to | 
 | 385 | @code{SIG_IGN}. | 
 | 386 |  | 
 | 387 | A subshell that runs non-interactively cannot and should not support job | 
 | 388 | control.  It must leave all processes it creates in the same process | 
 | 389 | group as the shell itself; this allows the non-interactive shell and its | 
 | 390 | child processes to be treated as a single job by the parent shell.  This | 
 | 391 | is easy to do---just don't use any of the job control primitives---but | 
 | 392 | you must remember to make the shell do it. | 
 | 393 |  | 
 | 394 |  | 
 | 395 | Here is the initialization code for the sample shell that shows how to | 
 | 396 | do 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 |  | 
 | 405 | pid_t shell_pgid; | 
 | 406 | struct termios shell_tmodes; | 
 | 407 | int shell_terminal; | 
 | 408 | int shell_is_interactive; | 
 | 409 |  | 
 | 410 |  | 
 | 411 | /* @r{Make sure the shell is running interactively as the foreground job} | 
 | 412 |    @r{before proceeding.} */ | 
 | 413 |  | 
 | 414 | void | 
 | 415 | init_shell () | 
 | 416 | @{ | 
 | 417 |  | 
 | 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 |  | 
 | 458 | Once the shell has taken responsibility for performing job control on | 
 | 459 | its controlling terminal, it can launch jobs in response to commands | 
 | 460 | typed by the user. | 
 | 461 |  | 
 | 462 | To create the processes in a process group, you use the same @code{fork} | 
 | 463 | and @code{exec} functions described in @ref{Process Creation Concepts}. | 
 | 464 | Since there are multiple child processes involved, though, things are a | 
 | 465 | little more complicated and you must be careful to do things in the | 
 | 466 | right order.  Otherwise, nasty race conditions can result. | 
 | 467 |  | 
 | 468 | You have two choices for how to structure the tree of parent-child | 
 | 469 | relationships among the processes.  You can either make all the | 
 | 470 | processes in the process group be children of the shell process, or you | 
 | 471 | can make one process in group be the ancestor of all the other processes | 
 | 472 | in that group.  The sample shell program presented in this chapter uses | 
 | 473 | the first approach because it makes bookkeeping somewhat simpler. | 
 | 474 |  | 
 | 475 | @cindex process group leader | 
 | 476 | @cindex process group ID | 
 | 477 | As each process is forked, it should put itself in the new process group | 
 | 478 | by calling @code{setpgid}; see @ref{Process Group Functions}.  The first | 
 | 479 | process in the new group becomes its @dfn{process group leader}, and its | 
 | 480 | process ID becomes the @dfn{process group ID} for the group. | 
 | 481 |  | 
 | 482 | @cindex race conditions, relating to job control | 
 | 483 | The shell should also call @code{setpgid} to put each of its child | 
 | 484 | processes into the new process group.  This is because there is a | 
 | 485 | potential timing problem: each child process must be put in the process | 
 | 486 | group before it begins executing a new program, and the shell depends on | 
 | 487 | having all the child processes in the group before it continues | 
 | 488 | executing.  If both the child processes and the shell call | 
 | 489 | @code{setpgid}, this ensures that the right things happen no matter which | 
 | 490 | process gets to it first. | 
 | 491 |  | 
 | 492 | If the job is being launched as a foreground job, the new process group | 
 | 493 | also needs to be put into the foreground on the controlling terminal | 
 | 494 | using @code{tcsetpgrp}.  Again, this should be done by the shell as well | 
 | 495 | as by each of its child processes, to avoid race conditions. | 
 | 496 |  | 
 | 497 | The next thing each child process should do is to reset its signal | 
 | 498 | actions. | 
 | 499 |  | 
 | 500 | During initialization, the shell process set itself to ignore job | 
 | 501 | control signals; see @ref{Initializing the Shell}.  As a result, any child | 
 | 502 | processes it creates also ignore these signals by inheritance.  This is | 
 | 503 | definitely undesirable, so each child process should explicitly set the | 
 | 504 | actions for these signals back to @code{SIG_DFL} just after it is forked. | 
 | 505 |  | 
 | 506 | Since shells follow this convention, applications can assume that they | 
 | 507 | inherit the correct handling of these signals from the parent process. | 
 | 508 | But every application has a responsibility not to mess up the handling | 
 | 509 | of stop signals.  Applications that disable the normal interpretation of | 
 | 510 | the SUSP character should provide some other mechanism for the user to | 
 | 511 | stop the job.  When the user invokes this mechanism, the program should | 
 | 512 | send a @code{SIGTSTP} signal to the process group of the process, not | 
 | 513 | just to the process itself.  @xref{Signaling Another Process}. | 
 | 514 |  | 
 | 515 | Finally, each child process should call @code{exec} in the normal way. | 
 | 516 | This is also the point at which redirection of the standard input and | 
 | 517 | output channels should be handled.  @xref{Duplicating Descriptors}, | 
 | 518 | for an explanation of how to do this. | 
 | 519 |  | 
 | 520 | Here is the function from the sample shell program that is responsible | 
 | 521 | for launching a program.  The function is executed by each child process | 
 | 522 | immediately after it has been forked by the shell, and never returns. | 
 | 523 |  | 
 | 524 | @smallexample | 
 | 525 | void | 
 | 526 | launch_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); | 
 | 568 |     @} | 
 | 569 |  | 
 | 570 |   /* @r{Exec the new process.  Make sure we exit.}  */ | 
 | 571 |   execvp (p->argv[0], p->argv); | 
 | 572 |   perror ("execvp"); | 
 | 573 |   exit (1); | 
 | 574 | @} | 
 | 575 | @end smallexample | 
 | 576 |  | 
 | 577 | If the shell is not running interactively, this function does not do | 
 | 578 | anything with process groups or signals.  Remember that a shell not | 
 | 579 | performing job control must keep all of its subprocesses in the same | 
 | 580 | process group as the shell itself. | 
 | 581 |  | 
 | 582 | Next, here is the function that actually launches a complete job. | 
 | 583 | After creating the child processes, this function calls some other | 
 | 584 | functions to put the newly created job into the foreground or background; | 
 | 585 | these are discussed in @ref{Foreground and Background}. | 
 | 586 |  | 
 | 587 | @smallexample | 
 | 588 | void | 
 | 589 | launch_job (job *j, int foreground) | 
 | 590 | @{ | 
 | 591 |   process *p; | 
 | 592 |   pid_t pid; | 
 | 593 |   int mypipe[2], infile, outfile; | 
 | 594 |  | 
 | 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 |     @} | 
 | 642 |  | 
 | 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 |  | 
 | 658 | Now let's consider what actions must be taken by the shell when it | 
 | 659 | launches a job into the foreground, and how this differs from what | 
 | 660 | must be done when a background job is launched. | 
 | 661 |  | 
 | 662 | @cindex foreground job, launching | 
 | 663 | When a foreground job is launched, the shell must first give it access | 
 | 664 | to the controlling terminal by calling @code{tcsetpgrp}.  Then, the | 
 | 665 | shell should wait for processes in that process group to terminate or | 
 | 666 | stop.  This is discussed in more detail in @ref{Stopped and Terminated | 
 | 667 | Jobs}. | 
 | 668 |  | 
 | 669 | When all of the processes in the group have either completed or stopped, | 
 | 670 | the shell should regain control of the terminal for its own process | 
 | 671 | group by calling @code{tcsetpgrp} again.  Since stop signals caused by | 
 | 672 | I/O from a background process or a SUSP character typed by the user | 
 | 673 | are sent to the process group, normally all the processes in the job | 
 | 674 | stop together. | 
 | 675 |  | 
 | 676 | The foreground job may have left the terminal in a strange state, so the | 
 | 677 | shell should restore its own saved terminal modes before continuing.  In | 
 | 678 | case the job is merely stopped, the shell should first save the current | 
 | 679 | terminal modes so that it can restore them later if the job is | 
 | 680 | continued.  The functions for dealing with terminal modes are | 
 | 681 | @code{tcgetattr} and @code{tcsetattr}; these are described in | 
 | 682 | @ref{Terminal Modes}. | 
 | 683 |  | 
 | 684 | Here 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 |  | 
 | 692 | void | 
 | 693 | put_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 | 
 | 708 |  | 
 | 709 |   /* @r{Wait for it to report.}  */ | 
 | 710 |   wait_for_job (j); | 
 | 711 |  | 
 | 712 |   /* @r{Put the shell back in the foreground.}  */ | 
 | 713 |   tcsetpgrp (shell_terminal, shell_pgid); | 
 | 714 |  | 
 | 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 | 
 | 724 | If the process group is launched as a background job, the shell should | 
 | 725 | remain in the foreground itself and continue to read commands from | 
 | 726 | the terminal. | 
 | 727 |  | 
 | 728 | In the sample shell, there is not much that needs to be done to put | 
 | 729 | a 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 |  | 
 | 735 | void | 
 | 736 | put_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 | 
 | 751 | When a foreground process is launched, the shell must block until all of | 
 | 752 | the processes in that job have either terminated or stopped.  It can do | 
 | 753 | this by calling the @code{waitpid} function; see @ref{Process | 
 | 754 | Completion}.  Use the @code{WUNTRACED} option so that status is reported | 
 | 755 | for processes that stop as well as processes that terminate. | 
 | 756 |  | 
 | 757 | The shell must also check on the status of background jobs so that it | 
 | 758 | can report terminated and stopped jobs to the user; this can be done by | 
 | 759 | calling @code{waitpid} with the @code{WNOHANG} option.  A good place to | 
 | 760 | put a such a check for terminated and stopped jobs is just before | 
 | 761 | prompting for a new command. | 
 | 762 |  | 
 | 763 | @cindex @code{SIGCHLD}, handling of | 
 | 764 | The shell can also receive asynchronous notification that there is | 
 | 765 | status information available for a child process by establishing a | 
 | 766 | handler for @code{SIGCHLD} signals.  @xref{Signal Handling}. | 
 | 767 |  | 
 | 768 | In the sample shell program, the @code{SIGCHLD} signal is normally | 
 | 769 | ignored.  This is to avoid reentrancy problems involving the global data | 
 | 770 | structures the shell manipulates.  But at specific times when the shell | 
 | 771 | is not using these data structures---such as when it is waiting for | 
 | 772 | input on the terminal---it makes sense to enable a handler for | 
 | 773 | @code{SIGCHLD}.  The same function that is used to do the synchronous | 
 | 774 | status checks (@code{do_job_notification}, in this case) can also be | 
 | 775 | called from within this handler. | 
 | 776 |  | 
 | 777 | Here are the parts of the sample shell program that deal with checking | 
 | 778 | the 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 |  | 
 | 785 | int | 
 | 786 | mark_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 |  | 
 | 832 | void | 
 | 833 | update_status (void) | 
 | 834 | @{ | 
 | 835 |   int status; | 
 | 836 |   pid_t pid; | 
 | 837 |  | 
 | 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 |  | 
 | 848 | void | 
 | 849 | wait_for_job (job *j) | 
 | 850 | @{ | 
 | 851 |   int status; | 
 | 852 |   pid_t pid; | 
 | 853 |  | 
 | 854 |   do | 
 | 855 |     pid = waitpid (WAIT_ANY, &status, WUNTRACED); | 
 | 856 |   while (!mark_process_status (pid, status) | 
 | 857 |          && !job_is_stopped (j) | 
 | 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 |  | 
 | 865 | void | 
 | 866 | format_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 |  | 
 | 876 | void | 
 | 877 | do_job_notification (void) | 
 | 878 | @{ | 
 | 879 |   job *j, *jlast, *jnext; | 
 | 880 |   process *p; | 
 | 881 |  | 
 | 882 |   /* @r{Update status information for child processes.}  */ | 
 | 883 |   update_status (); | 
 | 884 |  | 
 | 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 | 
 | 921 | The shell can continue a stopped job by sending a @code{SIGCONT} signal | 
 | 922 | to its process group.  If the job is being continued in the foreground, | 
 | 923 | the shell should first invoke @code{tcsetpgrp} to give the job access to | 
 | 924 | the terminal, and restore the saved terminal settings.  After continuing | 
 | 925 | a job in the foreground, the shell should wait for the job to stop or | 
 | 926 | complete, as if the job had just been launched in the foreground. | 
 | 927 |  | 
 | 928 | The sample shell program handles both newly created and continued jobs | 
 | 929 | with the same pair of functions, @w{@code{put_job_in_foreground}} and | 
 | 930 | @w{@code{put_job_in_background}}.  The definitions of these functions | 
 | 931 | were given in @ref{Foreground and Background}.  When continuing a | 
 | 932 | stopped job, a nonzero value is passed as the @var{cont} argument to | 
 | 933 | ensure that the @code{SIGCONT} signal is sent and the terminal modes | 
 | 934 | reset, as appropriate. | 
 | 935 |  | 
 | 936 | This leaves only a function for updating the shell's internal bookkeeping | 
 | 937 | about the job being continued: | 
 | 938 |  | 
 | 939 | @smallexample | 
 | 940 | @group | 
 | 941 | /* @r{Mark a stopped job J as being running again.}  */ | 
 | 942 |  | 
 | 943 | void | 
 | 944 | mark_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 |  | 
 | 957 | void | 
 | 958 | continue_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 |  | 
 | 972 | The code extracts for the sample shell included in this chapter are only | 
 | 973 | a part of the entire shell program.  In particular, nothing at all has | 
 | 974 | been said about how @code{job} and @code{program} data structures are | 
 | 975 | allocated and initialized. | 
 | 976 |  | 
 | 977 | Most real shells provide a complex user interface that has support for | 
 | 978 | a command language; variables; abbreviations, substitutions, and pattern | 
 | 979 | matching on file names; and the like.  All of this is far too complicated | 
 | 980 | to explain here!  Instead, we have concentrated on showing how to | 
 | 981 | implement the core process creation and job control functions that can | 
 | 982 | be called from such a shell. | 
 | 983 |  | 
 | 984 | Here is a table summarizing the major entry points we have presented: | 
 | 985 |  | 
 | 986 | @table @code | 
 | 987 | @item void init_shell (void) | 
 | 988 | Initialize the shell's internal state.  @xref{Initializing the | 
 | 989 | Shell}. | 
 | 990 |  | 
 | 991 | @item void launch_job (job *@var{j}, int @var{foreground}) | 
 | 992 | Launch the job @var{j} as either a foreground or background job. | 
 | 993 | @xref{Launching Jobs}. | 
 | 994 |  | 
 | 995 | @item void do_job_notification (void) | 
 | 996 | Check for and report any jobs that have terminated or stopped.  Can be | 
 | 997 | called 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}) | 
 | 1001 | Continue the job @var{j}.  @xref{Continuing Stopped Jobs}. | 
 | 1002 | @end table | 
 | 1003 |  | 
 | 1004 | Of course, a real shell would also want to provide other functions for | 
 | 1005 | managing jobs.  For example, it would be useful to have commands to list | 
 | 1006 | all 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 |  | 
 | 1014 | This section contains detailed descriptions of the functions relating | 
 | 1015 | to 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 |  | 
 | 1028 | You can use the @code{ctermid} function to get a file name that you can | 
 | 1029 | use to open the controlling terminal.  In @theglibc{}, it returns | 
 | 1030 | the same string all the time: @code{"/dev/tty"}.  That is a special | 
 | 1031 | ``magic'' file name that refers to the controlling terminal of the | 
 | 1032 | current process (if it has one).  To find the name of the specific | 
 | 1033 | terminal device, use @code{ttyname}; @pxref{Is It a Terminal}. | 
 | 1034 |  | 
 | 1035 | The function @code{ctermid} is declared in the header file | 
 | 1036 | @file{stdio.h}. | 
 | 1037 | @pindex stdio.h | 
 | 1038 |  | 
 | 1039 | @comment stdio.h | 
 | 1040 | @comment POSIX.1 | 
 | 1041 | @deftypefun {char *} ctermid (char *@var{string}) | 
 | 1042 | @safety{@prelim{}@mtsafe{@mtsposix{/!string}}@assafe{}@acsafe{}} | 
 | 1043 | @c This function is a stub by default; the actual implementation, for | 
 | 1044 | @c posix systems, returns a pointer to a string literal if passed a NULL | 
 | 1045 | @c string.  It's not clear we want to commit to being MT-Safe in the | 
 | 1046 | @c !string case, so maybe add mtasurace{:ctermid/!string} when we take | 
 | 1047 | @c prelim out, to make room for using a static buffer in the future. | 
 | 1048 | The @code{ctermid} function returns a string containing the file name of | 
 | 1049 | the controlling terminal for the current process.  If @var{string} is | 
 | 1050 | not a null pointer, it should be an array that can hold at least | 
 | 1051 | @code{L_ctermid} characters; the string is returned in this array. | 
 | 1052 | Otherwise, a pointer to a string in a static area is returned, which | 
 | 1053 | might get overwritten on subsequent calls to this function. | 
 | 1054 |  | 
 | 1055 | An empty string is returned if the file name cannot be determined for | 
 | 1056 | any reason.  Even if a file name is returned, access to the file it | 
 | 1057 | represents is not guaranteed. | 
 | 1058 | @end deftypefun | 
 | 1059 |  | 
 | 1060 | @comment stdio.h | 
 | 1061 | @comment POSIX.1 | 
 | 1062 | @deftypevr Macro int L_ctermid | 
 | 1063 | The value of this macro is an integer constant expression that | 
 | 1064 | represents the size of a string large enough to hold the file name | 
 | 1065 | returned by @code{ctermid}. | 
 | 1066 | @end deftypevr | 
 | 1067 |  | 
 | 1068 | See also the @code{isatty} and @code{ttyname} functions, in | 
 | 1069 | @ref{Is It a Terminal}. | 
 | 1070 |  | 
 | 1071 |  | 
 | 1072 | @node Process Group Functions, Terminal Access Functions, Identifying the Terminal, Functions for Job Control | 
 | 1073 | @subsection Process Group Functions | 
 | 1074 |  | 
 | 1075 | Here are descriptions of the functions for manipulating process groups. | 
 | 1076 | Your program should include the header files @file{sys/types.h} and | 
 | 1077 | @file{unistd.h} to use these functions. | 
 | 1078 | @pindex unistd.h | 
 | 1079 | @pindex sys/types.h | 
 | 1080 |  | 
 | 1081 | @comment unistd.h | 
 | 1082 | @comment POSIX.1 | 
 | 1083 | @deftypefun pid_t setsid (void) | 
 | 1084 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1085 | @c This is usually a direct syscall, but if a syscall is not available, | 
 | 1086 | @c we use a stub, or Hurd- and BSD-specific implementations.  The former | 
 | 1087 | @c uses a mutex and a hurd critical section, and the latter issues a few | 
 | 1088 | @c syscalls, so both seem safe, the locking on Hurd is safe because of | 
 | 1089 | @c the critical section. | 
 | 1090 | The @code{setsid} function creates a new session.  The calling process | 
 | 1091 | becomes the session leader, and is put in a new process group whose | 
 | 1092 | process group ID is the same as the process ID of that process.  There | 
 | 1093 | are initially no other processes in the new process group, and no other | 
 | 1094 | process groups in the new session. | 
 | 1095 |  | 
 | 1096 | This function also makes the calling process have no controlling terminal. | 
 | 1097 |  | 
 | 1098 | The @code{setsid} function returns the new process group ID of the | 
 | 1099 | calling process if successful.  A return value of @code{-1} indicates an | 
 | 1100 | error.  The following @code{errno} error conditions are defined for this | 
 | 1101 | function: | 
 | 1102 |  | 
 | 1103 | @table @code | 
 | 1104 | @item EPERM | 
 | 1105 | The calling process is already a process group leader, or there is | 
 | 1106 | already another process group around that has the same process group ID. | 
 | 1107 | @end table | 
 | 1108 | @end deftypefun | 
 | 1109 |  | 
 | 1110 | @comment unistd.h | 
 | 1111 | @comment SVID | 
 | 1112 | @deftypefun pid_t getsid (pid_t @var{pid}) | 
 | 1113 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1114 | @c Stub or direct syscall, except on hurd, where it is equally safe. | 
 | 1115 |  | 
 | 1116 | The @code{getsid} function returns the process group ID of the session | 
 | 1117 | leader of the specified process.  If a @var{pid} is @code{0}, the | 
 | 1118 | process group ID of the session leader of the current process is | 
 | 1119 | returned. | 
 | 1120 |  | 
 | 1121 | In case of error @code{-1} is returned and @code{errno} is set.  The | 
 | 1122 | following @code{errno} error conditions are defined for this function: | 
 | 1123 |  | 
 | 1124 | @table @code | 
 | 1125 | @item ESRCH | 
 | 1126 | There is no process with the given process ID @var{pid}. | 
 | 1127 | @item EPERM | 
 | 1128 | The calling process and the process specified by @var{pid} are in | 
 | 1129 | different sessions, and the implementation doesn't allow to access the | 
 | 1130 | process group ID of the session leader of the process with ID @var{pid} | 
 | 1131 | from the calling process. | 
 | 1132 | @end table | 
 | 1133 | @end deftypefun | 
 | 1134 |  | 
 | 1135 | @comment unistd.h | 
 | 1136 | @comment POSIX.1 | 
 | 1137 | @deftypefun pid_t getpgrp (void) | 
 | 1138 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1139 | The @code{getpgrp} function returns the process group ID of | 
 | 1140 | the calling process. | 
 | 1141 | @end deftypefun | 
 | 1142 |  | 
 | 1143 | @comment unistd.h | 
 | 1144 | @comment POSIX.1 | 
 | 1145 | @deftypefun int getpgid (pid_t @var{pid}) | 
 | 1146 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1147 | @c Stub or direct syscall, except on hurd, where it is equally safe. | 
 | 1148 |  | 
 | 1149 | The @code{getpgid} function | 
 | 1150 | returns the process group ID of the process @var{pid}.  You can supply a | 
 | 1151 | value of @code{0} for the @var{pid} argument to get information about | 
 | 1152 | the calling process. | 
 | 1153 |  | 
 | 1154 | In case of error @code{-1} is returned and @code{errno} is set.  The | 
 | 1155 | following @code{errno} error conditions are defined for this function: | 
 | 1156 |  | 
 | 1157 | @table @code | 
 | 1158 | @item ESRCH | 
 | 1159 | There is no process with the given process ID @var{pid}. | 
 | 1160 | The calling process and the process specified by @var{pid} are in | 
 | 1161 | different sessions, and the implementation doesn't allow to access the | 
 | 1162 | process group ID of the process with ID @var{pid} from the calling | 
 | 1163 | process. | 
 | 1164 | @end table | 
 | 1165 | @end deftypefun | 
 | 1166 |  | 
 | 1167 | @comment unistd.h | 
 | 1168 | @comment POSIX.1 | 
 | 1169 | @deftypefun int setpgid (pid_t @var{pid}, pid_t @var{pgid}) | 
 | 1170 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1171 | @c Stub or direct syscall, except on hurd, where it is equally safe. | 
 | 1172 | The @code{setpgid} function puts the process @var{pid} into the process | 
 | 1173 | group @var{pgid}.  As a special case, either @var{pid} or @var{pgid} can | 
 | 1174 | be zero to indicate the process ID of the calling process. | 
 | 1175 |  | 
 | 1176 | This function fails on a system that does not support job control. | 
 | 1177 | @xref{Job Control is Optional}, for more information. | 
 | 1178 |  | 
 | 1179 | If the operation is successful, @code{setpgid} returns zero.  Otherwise | 
 | 1180 | it returns @code{-1}.  The following @code{errno} error conditions are | 
 | 1181 | defined for this function: | 
 | 1182 |  | 
 | 1183 | @table @code | 
 | 1184 | @item EACCES | 
 | 1185 | The child process named by @var{pid} has executed an @code{exec} | 
 | 1186 | function since it was forked. | 
 | 1187 |  | 
 | 1188 | @item EINVAL | 
 | 1189 | The value of the @var{pgid} is not valid. | 
 | 1190 |  | 
 | 1191 | @item ENOSYS | 
 | 1192 | The system doesn't support job control. | 
 | 1193 |  | 
 | 1194 | @item EPERM | 
 | 1195 | The process indicated by the @var{pid} argument is a session leader, | 
 | 1196 | or is not in the same session as the calling process, or the value of | 
 | 1197 | the @var{pgid} argument doesn't match a process group ID in the same | 
 | 1198 | session as the calling process. | 
 | 1199 |  | 
 | 1200 | @item ESRCH | 
 | 1201 | The process indicated by the @var{pid} argument is not the calling | 
 | 1202 | process or a child of the calling process. | 
 | 1203 | @end table | 
 | 1204 | @end deftypefun | 
 | 1205 |  | 
 | 1206 | @comment unistd.h | 
 | 1207 | @comment BSD | 
 | 1208 | @deftypefun int setpgrp (pid_t @var{pid}, pid_t @var{pgid}) | 
 | 1209 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1210 | @c Direct syscall or setpgid wrapper. | 
 | 1211 | This is the BSD Unix name for @code{setpgid}.  Both functions do exactly | 
 | 1212 | the same thing. | 
 | 1213 | @end deftypefun | 
 | 1214 |  | 
 | 1215 |  | 
 | 1216 | @node Terminal Access Functions,  , Process Group Functions, Functions for Job Control | 
 | 1217 | @subsection Functions for Controlling Terminal Access | 
 | 1218 |  | 
 | 1219 | These are the functions for reading or setting the foreground | 
 | 1220 | process group of a terminal.  You should include the header files | 
 | 1221 | @file{sys/types.h} and @file{unistd.h} in your application to use | 
 | 1222 | these functions. | 
 | 1223 | @pindex unistd.h | 
 | 1224 | @pindex sys/types.h | 
 | 1225 |  | 
 | 1226 | Although these functions take a file descriptor argument to specify | 
 | 1227 | the terminal device, the foreground job is associated with the terminal | 
 | 1228 | file itself and not a particular open file descriptor. | 
 | 1229 |  | 
 | 1230 | @comment unistd.h | 
 | 1231 | @comment POSIX.1 | 
 | 1232 | @deftypefun pid_t tcgetpgrp (int @var{filedes}) | 
 | 1233 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1234 | @c Stub, or ioctl on BSD and GNU/Linux. | 
 | 1235 | This function returns the process group ID of the foreground process | 
 | 1236 | group associated with the terminal open on descriptor @var{filedes}. | 
 | 1237 |  | 
 | 1238 | If there is no foreground process group, the return value is a number | 
 | 1239 | greater than @code{1} that does not match the process group ID of any | 
 | 1240 | existing process group.  This can happen if all of the processes in the | 
 | 1241 | job that was formerly the foreground job have terminated, and no other | 
 | 1242 | job has yet been moved into the foreground. | 
 | 1243 |  | 
 | 1244 | In case of an error, a value of @code{-1} is returned.  The | 
 | 1245 | following @code{errno} error conditions are defined for this function: | 
 | 1246 |  | 
 | 1247 | @table @code | 
 | 1248 | @item EBADF | 
 | 1249 | The @var{filedes} argument is not a valid file descriptor. | 
 | 1250 |  | 
 | 1251 | @item ENOSYS | 
 | 1252 | The system doesn't support job control. | 
 | 1253 |  | 
 | 1254 | @item ENOTTY | 
 | 1255 | The terminal file associated with the @var{filedes} argument isn't the | 
 | 1256 | controlling terminal of the calling process. | 
 | 1257 | @end table | 
 | 1258 | @end deftypefun | 
 | 1259 |  | 
 | 1260 | @comment unistd.h | 
 | 1261 | @comment POSIX.1 | 
 | 1262 | @deftypefun int tcsetpgrp (int @var{filedes}, pid_t @var{pgid}) | 
 | 1263 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1264 | @c Stub, or ioctl on BSD and GNU/Linux. | 
 | 1265 | This function is used to set a terminal's foreground process group ID. | 
 | 1266 | The argument @var{filedes} is a descriptor which specifies the terminal; | 
 | 1267 | @var{pgid} specifies the process group.  The calling process must be a | 
 | 1268 | member of the same session as @var{pgid} and must have the same | 
 | 1269 | controlling terminal. | 
 | 1270 |  | 
 | 1271 | For terminal access purposes, this function is treated as output.  If it | 
 | 1272 | is called from a background process on its controlling terminal, | 
 | 1273 | normally all processes in the process group are sent a @code{SIGTTOU} | 
 | 1274 | signal.  The exception is if the calling process itself is ignoring or | 
 | 1275 | blocking @code{SIGTTOU} signals, in which case the operation is | 
 | 1276 | performed and no signal is sent. | 
 | 1277 |  | 
 | 1278 | If successful, @code{tcsetpgrp} returns @code{0}.  A return value of | 
 | 1279 | @code{-1} indicates an error.  The following @code{errno} error | 
 | 1280 | conditions are defined for this function: | 
 | 1281 |  | 
 | 1282 | @table @code | 
 | 1283 | @item EBADF | 
 | 1284 | The @var{filedes} argument is not a valid file descriptor. | 
 | 1285 |  | 
 | 1286 | @item EINVAL | 
 | 1287 | The @var{pgid} argument is not valid. | 
 | 1288 |  | 
 | 1289 | @item ENOSYS | 
 | 1290 | The system doesn't support job control. | 
 | 1291 |  | 
 | 1292 | @item ENOTTY | 
 | 1293 | The @var{filedes} isn't the controlling terminal of the calling process. | 
 | 1294 |  | 
 | 1295 | @item EPERM | 
 | 1296 | The @var{pgid} isn't a process group in the same session as the calling | 
 | 1297 | process. | 
 | 1298 | @end table | 
 | 1299 | @end deftypefun | 
 | 1300 |  | 
 | 1301 | @comment termios.h | 
 | 1302 | @comment Unix98 | 
 | 1303 | @deftypefun pid_t tcgetsid (int @var{fildes}) | 
 | 1304 | @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}} | 
 | 1305 | @c Ioctl call, if available, or tcgetpgrp followed by getsid. | 
 | 1306 | This function is used to obtain the process group ID of the session | 
 | 1307 | for which the terminal specified by @var{fildes} is the controlling terminal. | 
 | 1308 | If the call is successful the group ID is returned.  Otherwise the | 
 | 1309 | return value is @code{(pid_t) -1} and the global variable @var{errno} | 
 | 1310 | is set to the following value: | 
 | 1311 | @table @code | 
 | 1312 | @item EBADF | 
 | 1313 | The @var{filedes} argument is not a valid file descriptor. | 
 | 1314 |  | 
 | 1315 | @item ENOTTY | 
 | 1316 | The calling process does not have a controlling terminal, or the file | 
 | 1317 | is not the controlling terminal. | 
 | 1318 | @end table | 
 | 1319 | @end deftypefun |