@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC417Št�”›Job Control

‰IDX1904Š‰IDX1905Š‰IDX1906Š‰IDX1907ŠB�”˜Job control@ refers to the protocol for allowing a user to move between multiple Bprocess groups@ (or Bjobs@) within a single Blogin session@. The job control facilities are set up so that appropriate behavior for most programs happens automatically and they need not do anything special about job control. So you can probably ignore the material in this chapter unless you are writing a shell or login program.
You need to be familiar with concepts relating to process creation (see section ‰ŠP�”›Process Creation Concepts@�”˜) and signal handling (see section ‰ŠP�”›Signal Handling@�”˜) in order to understand this material presented in this chapter.
ˆ‰SEC418Št�”›Concepts of Job Control

‰IDX1908Š@�”˜The fundamental purpose of an interactive shell is to read commands from the user's terminal and create processes to execute the programs specified by those commands. It can do this using the Hfork@ (see section ‰ŠP�”›Creating a Process@�”˜) and Hexec@ (see section ‰ŠP�”›Executing a File@�”˜) functions.
A single command may run just one process--but often one command uses several processes. If you use the H`|'@ operator in a shell command, you explicitly request several programs in their own processes. But even if you run just one program, it can use multiple processes internally. For example, a single compilation command such as H`cc -c foo.c'@ typically uses four processes (though normally only two at any given time). If you run Hmake@, its job is to run other programs in separate processes.
The processes belonging to a single command are called a Bprocess group@ or Bjob@. This is so that you can operate on all of them at once. For example, typing HC-c@ sends the signal HSIGINT@ to terminate all the processes in the foreground process group.
‰IDX1909Š@�”˜A Bsession@ is a larger group of processes. Normally all the processes that stem from a single login belong to the same session.
Every process belongs to a process group. When a process is created, it becomes a member of the same process group and session as its parent process. You can put it in another process group using the Hsetpgid@ function, provided the process group belongs to the same session.
‰IDX1910Š@�”˜The only way to put a process in a different session is to make it the initial process of a new session, or a Bsession leader@, using the Hsetsid@ function. This also puts the session leader into a new process group, and you can't move it out of that process group again.
Usually, new sessions are created by the system login program, and the session leader is the process running the user's login shell.
‰IDX1911Š@�”˜A shell that supports job control must arrange to control which job can use the terminal at any time. Otherwise there might be multiple jobs trying to read from the terminal at once, and confusion about which process should receive the input typed by the user. To prevent this, the shell must cooperate with the terminal driver using the protocol described in this chapter.
‰IDX1912Š‰IDX1913Š@�”˜The shell can give unlimited access to the controlling terminal to only one process group at a time. This is called the Bforeground job@ on that controlling terminal. Other process groups managed by the shell that are executing without such access to the terminal are called Bbackground jobs@.
‰IDX1914Š@�”˜If a background job needs to read from its controlling terminal, it is Bstopped@ by the terminal driver; if the HTOSTOP@ mode is set, likewise for writing. The user can stop a foreground job by typing the SUSP character (see section ‰ŠP�”›Special Characters@�”˜) and a program can stop any job by sending it a HSIGSTOP@ signal. It's the responsibility of the shell to notice when jobs stop, to notify the user about them, and to provide mechanisms for allowing the user to interactively continue stopped jobs and switch jobs between foreground and background.
See section ‰ŠP�”›Access to the Controlling Terminal@�”˜, for more information about I/O to the controlling terminal,
ˆ‰SEC419Št�”›Job Control is Optional

‰IDX1915Š
@�”˜Not all operating systems support job control. The GNU system does support job control, but if you are using the GNU library on some other system, that system may not support job control itself.
You can use the H_POSIX_JOB_CONTROL@ macro to test at compile-time whether the system supports job control. See section ‰ŠP�”›Overall System Options@�”˜.
If job control is not supported, then there can be only one process group per session, which behaves as if it were always in the foreground. The functions for creating additional process groups simply fail with the error code HENOSYS@.
The macros naming the various job control signals (see section ‰ŠP�”›Job Control Signals@�”˜) are defined even if job control is not supported. However, the system never generates these signals, and attempts to send a job control signal or examine or specify their actions report errors or do nothing.
ˆ‰SEC420Št�”›Controlling Terminal of a Process

@�”˜One of the attributes of a process is its controlling terminal. Child processes created with Hfork@ inherit the controlling terminal from their parent process. In this way, all the processes in a session inherit the controlling terminal from the session leader. A session leader that has control of a terminal is called the Bcontrolling process@ of that terminal.
‰IDX1916Š@�”˜You generally do not need to worry about the exact mechanism used to allocate a controlling terminal to a session, since it is done for you by the system when you log in.
An individual process disconnects from its controlling terminal when it calls Hsetsid@ to become the leader of a new session. See section ‰ŠP�”›Process Group Functions@�”˜.
ˆ‰SEC421Št�”›Access to the Controlling Terminal

‰IDX1917Š
@�”˜Processes in the foreground job of a controlling terminal have unrestricted access to that terminal; background processes do not. This section describes in more detail what happens when a process in a background job tries to access its controlling terminal.
‰IDX1918Š@�”˜When a process in a background job tries to read from its controlling terminal, the process group is usually sent a HSIGTTIN@ signal. This normally causes all of the processes in that group to stop (unless they handle the signal and don't stop themselves). However, if the reading process is ignoring or blocking this signal, then Hread@ fails with an HEIO@ error instead.
‰IDX1919Š@�”˜Similarly, when a process in a background job tries to write to its controlling terminal, the default behavior is to send a HSIGTTOU@ signal to the process group. However, the behavior is modified by the HTOSTOP@ bit of the local modes flags (see section ‰ŠP�”›Local Modes@�”˜). If this bit is not set (which is the default), then writing to the controlling terminal is always permitted without sending a signal. Writing is also permitted if the HSIGTTOU@ signal is being ignored or blocked by the writing process.
Most other terminal operations that a program can do are treated as reading or as writing. (The description of each operation should say which.)
For more information about the primitive Hread@ and Hwrite@ functions, see section ‰ŠP�”›Input and Output Primitives@�”˜.
ˆ‰SEC422Št�”›Orphaned Process Groups

‰IDX1920Š
@�”˜When a controlling process terminates, its terminal becomes free and a new session can be established on it. (In fact, another user could log in on the terminal.) This could cause a problem if any processes from the old session are still trying to use that terminal.
To prevent problems, process groups that continue running even after the session leader has terminated are marked as Borphaned process groups@.
When a process group becomes an orphan, its processes are sent a HSIGHUP@ signal. Ordinarily, this causes the processes to terminate. However, if a program ignores this signal or establishes a handler for it (see section ‰ŠP�”›Signal Handling@�”˜), it can continue running as in the orphan process group even after its controlling process terminates; but it still cannot access the terminal any more.
ˆ‰SEC423Št�”›Implementing a Job Control Shell

@�”˜This section describes what a shell must do to implement job control, by presenting an extensive sample program to illustrate the concepts involved. þÂ
• section ‰ŠP�”›Data Structures for the Shell@�”˜, introduces the example and presents its primary data structures.
• section ‰ŠP�”›Initializing the Shell@�”˜, discusses actions which the shell must perform to prepare for job control.
• section ‰ŠP�”›Launching Jobs@�”˜, includes information about how to create jobs to execute commands.
• section ‰ŠP�”›Foreground and Background@�”˜, discusses what the shell should do differently when launching a job in the foreground as opposed to a background job.
• section ‰ŠP�”›Stopped and Terminated Jobs@�”˜, discusses reporting of job status back to the shell.
• section ‰ŠP�”›Continuing Stopped Jobs@�”˜, tells you how to continue jobs that have been stopped.
• section ‰ŠP�”›The Missing Pieces@�”˜, discusses other parts of the shell.Àð
ˆ‰SEC424ŠT�”›Data Structures for the Shell

@�”˜All of the program examples included in this chapter are part of a simple shell program. This section presents data structures and utility functions which are used throughout the example.
The sample shell deals mainly with two data structures. The Hjob@ type contains information about a job, which is a set of subprocesses linked together with pipes. The Hprocess@ type holds information about a single subprocess. Here are the relevant data structure declarations: /* A process is a single process. */
typedef struct process
{
struct process *next; /* next process in pipeline */
char **argv; /* for exec */
pid_t pid; /* process ID */
char completed; /* true if process has completed */
char stopped; /* true if process has stopped */
int status; /* reported status value */
} process;

/* A job is a pipeline of processes. */
typedef struct job
{
struct job *next; /* next active job */
char *command; /* command line, used for messages */
process *first_process; /* list of processes in this job */
pid_t pgid; /* process group ID */
char notified; /* true if user told about stopped job */
struct termios tmodes; /* saved terminal modes */
int stdin, stdout, stderr; /* standard i/o channels */
} job;

/* The active jobs are linked into a list. This is its head. */
job *first_job = NULL;
Here are some utility functions that are used for operating on Hjob@ objects. /* Find the active job with the indicated Bpgid@. */
job *
find_job (pid_t pgid)
{
job *j;

for (j = first_job; j; j = j->next)
if (j->pgid == pgid)
return j;
return NULL;
}

/* Return true if all processes in the job have stopped or completed. */
int
job_is_stopped (job *j)
{
process *p;

for (p = j->first_process; p; p = p->next)
if (!p->completed && !p->stopped)
return 0;
return 1;
}

/* Return true if all processes in the job have completed. */
int
job_is_completed (job *j)
{
process *p;

for (p = j->first_process; p; p = p->next)
if (!p->completed)
return 0;
return 1;
}
ˆ‰SEC425ŠT�”›Initializing the Shell

‰IDX1921Š‰IDX1922Š
@�”˜When a shell program that normally performs job control is started, it has to be careful in case it has been invoked from another shell that is already doing its own job control.
A subshell that runs interactively has to ensure that it has been placed in the foreground by its parent shell before it can enable job control itself. It does this by getting its initial process group ID with the Hgetpgrp@ function, and comparing it to the process group ID of the current foreground job associated with its controlling terminal (which can be retrieved using the Htcgetpgrp@ function).
If the subshell is not running as a foreground job, it must stop itself by sending a HSIGTTIN@ signal to its own process group. It may not arbitrarily put itself into the foreground; it must wait for the user to tell the parent shell to do this. If the subshell is continued again, it should repeat the check and stop itself again if it is still not in the foreground.
‰IDX1923Š@�”˜Once the subshell has been placed into the foreground by its parent shell, it can enable its own job control. It does this by calling Hsetpgid@ to put itself into its own process group, and then calling Htcsetpgrp@ to place this process group into the foreground.
When a shell enables job control, it should set itself to ignore all the job control stop signals so that it doesn't accidentally stop itself. You can do this by setting the action for all the stop signals to HSIG_IGN@.
A subshell that runs non-interactively cannot and should not support job control. It must leave all processes it creates in the same process group as the shell itself; this allows the non-interactive shell and its child processes to be treated as a single job by the parent shell. This is easy to do--just don't use any of the job control primitives--but you must remember to make the shell do it.
Here is the initialization code for the sample shell that shows how to do all of this. /* Keep track of attributes of the shell. */

#include <sys/types.h>
#include <termios.h>
#include <unistd.h>

pid_t shell_pgid;
struct termios shell_tmodes;
int shell_terminal;
int shell_is_interactive;

/* Make sure the shell is running interactively as the foreground job
before proceeding. */

void
init_shell ()
{

/* See if we are running interactively. */
shell_terminal = STDIN_FILENO;
shell_is_interactive = isatty (shell_terminal);

if (shell_is_interactive)
{
/* Loop until we are in the foreground. */
while (tcgetpgrp (shell_terminal) != (shell_pgid = getpgrp ()))
kill (- shell_pgid, SIGTTIN);

/* Ignore interactive and job-control signals. */
signal (SIGINT, SIG_IGN);
signal (SIGQUIT, SIG_IGN);
signal (SIGTSTP, SIG_IGN);
signal (SIGTTIN, SIG_IGN);
signal (SIGTTOU, SIG_IGN);
signal (SIGCHLD, SIG_IGN);

/* Put ourselves in our own process group. */
shell_pgid = getpid ();
if (setpgid (shell_pgid, shell_pgid) < 0)
{
perror ("Couldn't put the shell in its own process group");
exit (1);
}

/* Grab control of the terminal. */
tcsetpgrp (shell_terminal, shell_pgid);

/* Save default terminal attributes for shell. */
tcgetattr (shell_terminal, &shell_tmodes);
}
}
ˆ‰SEC426ŠT�”›Launching Jobs

‰IDX1924Š
@�”˜Once the shell has taken responsibility for performing job control on its controlling terminal, it can launch jobs in response to commands typed by the user.
To create the processes in a process group, you use the same Hfork@ and Hexec@ functions described in section ‰ŠP�”›Process Creation Concepts@�”˜. Since there are multiple child processes involved, though, things are a little more complicated and you must be careful to do things in the right order. Otherwise, nasty race conditions can result.
You have two choices for how to structure the tree of parent-child relationships among the processes. You can either make all the processes in the process group be children of the shell process, or you can make one process in group be the ancestor of all the other processes in that group. The sample shell program presented in this chapter uses the first approach because it makes bookkeeping somewhat simpler.
‰IDX1925Š‰IDX1926Š@�”˜As each process is forked, it should put itself in the new process group by calling Hsetpgid@; see section ‰ŠP�”›Process Group Functions@�”˜. The first process in the new group becomes its Bprocess group leader@, and its process ID becomes the Bprocess group ID@ for the group.
‰IDX1927Š@�”˜The shell should also call Hsetpgid@ to put each of its child processes into the new process group. This is because there is a potential timing problem: each child process must be put in the process group before it begins executing a new program, and the shell depends on having all the child processes in the group before it continues executing. If both the child processes and the shell call Hsetpgid@, this ensures that the right things happen no matter which process gets to it first.
If the job is being launched as a foreground job, the new process group also needs to be put into the foreground on the controlling terminal using Htcsetpgrp@. Again, this should be done by the shell as well as by each of its child processes, to avoid race conditions.
The next thing each child process should do is to reset its signal actions.
During initialization, the shell process set itself to ignore job control signals; see section ‰ŠP�”›Initializing the Shell@�”˜. As a result, any child processes it creates also ignore these signals by inheritance. This is definitely undesirable, so each child process should explicitly set the actions for these signals back to HSIG_DFL@ just after it is forked.
Since shells follow this convention, applications can assume that they inherit the correct handling of these signals from the parent process. But every application has a responsibility not to mess up the handling of stop signals. Applications that disable the normal interpretation of the SUSP character should provide some other mechanism for the user to stop the job. When the user invokes this mechanism, the program should send a HSIGTSTP@ signal to the process group of the process, not just to the process itself. See section ‰ŠP�”›Signaling Another Process@�”˜.
Finally, each child process should call Hexec@ in the normal way. This is also the point at which redirection of the standard input and output channels should be handled. See section ‰ŠP�”›Duplicating Descriptors@�”˜, for an explanation of how to do this.
Here is the function from the sample shell program that is responsible for launching a program. The function is executed by each child process immediately after it has been forked by the shell, and never returns. void
launch_process (process *p, pid_t pgid,
int infile, int outfile, int errfile,
int foreground)
{
pid_t pid;

if (shell_is_interactive)
{
/* Put the process into the process group and give the process group
the terminal, if appropriate.
This has to be done both by the shell and in the individual
child processes because of potential race conditions. */
pid = getpid ();
if (pgid == 0) pgid = pid;
setpgid (pid, pgid);
if (foreground)
tcsetpgrp (shell_terminal, pgid);

/* Set the handling for job control signals back to the default. */
signal (SIGINT, SIG_DFL);
signal (SIGQUIT, SIG_DFL);
signal (SIGTSTP, SIG_DFL);
signal (SIGTTIN, SIG_DFL);
signal (SIGTTOU, SIG_DFL);
signal (SIGCHLD, SIG_DFL);
}

/* Set the standard input/output channels of the new process. */
if (infile != STDIN_FILENO)
{
dup2 (infile, STDIN_FILENO);
close (infile);
}
if (outfile != STDOUT_FILENO)
{
dup2 (outfile, STDOUT_FILENO);
close (outfile);
}
if (errfile != STDERR_FILENO)
{
dup2 (errfile, STDERR_FILENO);
close (errfile);
}

/* Exec the new process. Make sure we exit. */
execvp (p->argv[0], p->argv);
perror ("execvp");
exit (1);
}
If the shell is not running interactively, this function does not do anything with process groups or signals. Remember that a shell not performing job control must keep all of its subprocesses in the same process group as the shell itself.
Next, here is the function that actually launches a complete job. After creating the child processes, this function calls some other functions to put the newly created job into the foreground or background; these are discussed in section ‰ŠP�”›Foreground and Background@�”˜. void
launch_job (job *j, int foreground)
{
process *p;
pid_t pid;
int mypipe[2], infile, outfile;

infile = j->stdin;
for (p = j->first_process; p; p = p->next)
{
/* Set up pipes, if necessary. */
if (p->next)
{
if (pipe (mypipe) < 0)
{
perror ("pipe");
exit (1);
}
outfile = mypipe[1];
}
else
outfile = j->stdout;

/* Fork the child processes. */
pid = fork ();
if (pid == 0)
/* This is the child process. */
launch_process (p, j->pgid, infile,
outfile, j->stderr, foreground);
else if (pid < 0)
{
/* The fork failed. */
perror ("fork");
exit (1);
}
else
{
/* This is the parent process. */
p->pid = pid;
if (shell_is_interactive)
{
if (!j->pgid)
j->pgid = pid;
setpgid (pid, j->pgid);
}
}

/* Clean up after pipes. */
if (infile != j->stdin)
close (infile);
if (outfile != j->stdout)
close (outfile);
infile = mypipe[0];
}

format_job_info (j, "launched");

if (!shell_is_interactive)
wait_for_job (j);
else if (foreground)
put_job_in_foreground (j, 0);
else
put_job_in_background (j, 0);
}
ˆ‰SEC427ŠT�”›Foreground and Background

@�”˜Now let's consider what actions must be taken by the shell when it launches a job into the foreground, and how this differs from what must be done when a background job is launched.
‰IDX1928Š@�”˜When a foreground job is launched, the shell must first give it access to the controlling terminal by calling Htcsetpgrp@. Then, the shell should wait for processes in that process group to terminate or stop. This is discussed in more detail in section ‰ŠP�”›Stopped and Terminated Jobs@�”˜.
When all of the processes in the group have either completed or stopped, the shell should regain control of the terminal for its own process group by calling Htcsetpgrp@ again. Since stop signals caused by I/O from a background process or a SUSP character typed by the user are sent to the process group, normally all the processes in the job stop together.
The foreground job may have left the terminal in a strange state, so the shell should restore its own saved terminal modes before continuing. In case the job is merely been stopped, the shell should first save the current terminal modes so that it can restore them later if the job is continued. The functions for dealing with terminal modes are Htcgetattr@ and Htcsetattr@; these are described in section ‰ŠP�”›Terminal Modes@�”˜.
Here is the sample shell's function for doing all of this. /* Put job Bj@ in the foreground. If Bcont@ is nonzero,
restore the saved terminal modes and send the process group a
HSIGCONT@ signal to wake it up before we block. */

void
put_job_in_foreground (job *j, int cont)
{
/* Put the job into the foreground. */
tcsetpgrp (shell_terminal, j->pgid);

/* Send the job a continue signal, if necessary. */
if (cont)
{
tcsetattr (shell_terminal, TCSADRAIN, &j->tmodes);
if (kill (- j->pgid, SIGCONT) < 0)
perror ("kill (SIGCONT)");
}

/* Wait for it to report. */
wait_for_job (j);

/* Put the shell back in the foreground. */
tcsetpgrp (shell_terminal, shell_pgid);

/* Restore the shell's terminal modes. */
tcgetattr (shell_terminal, &j->tmodes);
tcsetattr (shell_terminal, TCSADRAIN, &shell_tmodes);
}
‰IDX1929Š@�”˜If the process group is launched as a background job, the shell should remain in the foreground itself and continue to read commands from the terminal.
In the sample shell, there is not much that needs to be done to put a job into the background. Here is the function it uses: /* Put a job in the background. If the cont argument is true, send
the process group a HSIGCONT@ signal to wake it up. */

void
put_job_in_background (job *j, int cont)
{
/* Send the job a continue signal, if necessary. */
if (cont)
if (kill (-j->pgid, SIGCONT) < 0)
perror ("kill (SIGCONT)");
}
ˆ‰SEC428ŠT�”›Stopped and Terminated Jobs

‰IDX1930Š‰IDX1931Š@�”˜When a foreground process is launched, the shell must block until all of the processes in that job have either terminated or stopped. It can do this by calling the Hwaitpid@ function; see section ‰ŠP�”›Process Completion@�”˜. Use the HWUNTRACED@ option so that status is reported for processes that stop as well as processes that terminate.
The shell must also check on the status of background jobs so that it can report terminated and stopped jobs to the user; this can be done by calling Hwaitpid@ with the HWNOHANG@ option. A good place to put a such a check for terminated and stopped jobs is just before prompting for a new command.
‰IDX1932Š@�”˜The shell can also receive asynchronous notification that there is status information available for a child process by establishing a handler for HSIGCHLD@ signals. See section ‰ŠP�”›Signal Handling@�”˜.
In the sample shell program, the HSIGCHLD@ signal is normally ignored. This is to avoid reentrancy problems involving the global data structures the shell manipulates. But at specific times when the shell is not using these data structures--such as when it is waiting for input on the terminal--it makes sense to enable a handler for HSIGCHLD@. The same function that is used to do the synchronous status checks (Hdo_job_notification@, in this case) can also be called from within this handler.
Here are the parts of the sample shell program that deal with checking the status of jobs and reporting the information to the user. /* Store the status of the process Bpid@ that was returned by waitpid.
Return 0 if all went well, nonzero otherwise. */

int
mark_process_status (pid_t pid, int status)
{
job *j;
process *p;

if (pid > 0)
{
/* Update the record for the process. */
for (j = first_job; j; j = j->next)
for (p = j->first_process; p; p = p->next)
if (p->pid == pid)
{
p->status = status;
if (WIFSTOPPED (status))
p->stopped = 1;
else
{
p->completed = 1;
if (WIFSIGNALED (status))
fprintf (stderr, "%d: Terminated by signal %d.\n",
(int) pid, WTERMSIG (p->status));
}
return 0;
}
fprintf (stderr, "No child process %d.\n", pid);
return -1;
}
else if (pid == 0 || errno == ECHILD)
/* No processes ready to report. */
return -1;
else {
/* Other weird errors. */
perror ("waitpid");
return -1;
}
}

/* Check for processes that have status information available,
without blocking. */

void
update_status (void)
{
int status;
pid_t pid;

do
pid = waitpid (WAIT_ANY, &status, WUNTRACED|WNOHANG);
while (!mark_process_status (pid, status));
}

/* Check for processes that have status information available,
blocking until all processes in the given job have reported. */

void
wait_for_job (job *j)
{
int status;
pid_t pid;

do
pid = waitpid (WAIT_ANY, &status, WUNTRACED);
while (!mark_process_status (pid, status)
&& !job_is_stopped (j)
&& !job_is_completed (j));
}

/* Format information about job status for the user to look at. */

void
format_job_info (job *j, const char *status)
{
fprintf (stderr, "%ld (%s): %s\n", (long)j->pgid, status, j->command);
}

/* Notify the user about stopped or terminated jobs.
Delete terminated jobs from the active job list. */

void
do_job_notification (void)
{
job *j, *jlast, *jnext;
process *p;

/* Update status information for child processes. */
update_status ();

jlast = NULL;
for (j = first_job; j; j = jnext)
{
jnext = j->next;

/* If all processes have completed, tell the user the job has
completed and delete it from the list of active jobs. */
if (job_is_completed (j)) {
format_job_info (j, "completed");
if (jlast)
jlast->next = jnext;
else
first_job = jnext;
free_job (j);
}

/* Notify the user about stopped jobs,
marking them so that we won't do this more than once. */
else if (job_is_stopped (j) && !j->notified) {
format_job_info (j, "stopped");
j->notified = 1;
jlast = j;
}

/* Don't say anything about jobs that are still running. */
else
jlast = j;
}
}
ˆ‰SEC429ŠT�”›Continuing Stopped Jobs

‰IDX1933Š@�”˜The shell can continue a stopped job by sending a HSIGCONT@ signal to its process group. If the job is being continued in the foreground, the shell should first invoke Htcsetpgrp@ to give the job access to the terminal, and restore the saved terminal settings. After continuing a job in the foreground, the shell should wait for the job to stop or complete, as if the job had just been launched in the foreground.
The sample shell program handles both newly created and continued jobs with the same pair of functions, Hput_job_in_foreground@ and Hput_job_in_background@. The definitions of these functions were given in section ‰ŠP�”›Foreground and Background@�”˜. When continuing a stopped job, a nonzero value is passed as the Bcont@ argument to ensure that the HSIGCONT@ signal is sent and the terminal modes reset, as appropriate.
This leaves only a function for updating the shell's internal bookkeeping about the job being continued: /* Mark a stopped job J as being running again. */

void
mark_job_as_running (job *j)
{
Process *p;

for (p = j->first_process; p; p = p->next)
p->stopped = 0;
j->notified = 0;
}

/* Continue the job J. */

void
continue_job (job *j, int foreground)
{
mark_job_as_running (j);
if (foreground)
put_job_in_foreground (j, 1);
else
put_job_in_background (j, 1);
}
ˆ‰SEC430ŠT�”›The Missing Pieces

@�”˜The code extracts for the sample shell included in this chapter are only a part of the entire shell program. In particular, nothing at all has been said about how Hjob@ and Hprogram@ data structures are allocated and initialized.
Most real shells provide a complex user interface that has support for a command language; variables; abbreviations, substitutions, and pattern matching on file names; and the like. All of this is far too complicated to explain here! Instead, we have concentrated on showing how to implement the core process creation and job control functions that can be called from such a shell.
Here is a table summarizing the major entry points we have presented:
Hvoid init_shell (void)
Â@Initialize the shell's internal state. See section ‰ŠP�”›Initializing the Shell@�”˜.
ÀHvoid launch_job (job *JjH, int JforegroundH)
Â@Launch the job Bj@ as either a foreground or background job. See section ‰ŠP�”›Launching Jobs@�”˜.
ÀHvoid do_job_notification (void)
Â@Check for and report any jobs that have terminated or stopped. Can be called synchronously or within a handler for HSIGCHLD@ signals. See section ‰ŠP�”›Stopped and Terminated Jobs@�”˜.
ÀHvoid continue_job (job *JjH, int JforegroundH)
Â@Continue the job Bj@. See section ‰ŠP�”›Continuing Stopped Jobs@�”˜.À

Of course, a real shell would also want to provide other functions for managing jobs. For example, it would be useful to have commands to list all active jobs or to send a signal (such as HSIGKILL@) to a job.
ˆ‰SEC431Št�”›Functions for Job Control

‰IDX1934Š‰IDX1935Š
@�”˜This section contains detailed descriptions of the functions relating to job control.
ˆ‰SEC432ŠT�”›Identifying the Controlling Terminal

‰IDX1936Š
@�”˜You can use the Hctermid@ function to get a file name that you can use to open the controlling terminal. In the GNU library, it returns the same string all the time: H"/dev/tty"@. That is a special "magic" file name that refers to the controlling terminal of the current process (if it has one). To find the name of the specific terminal device, use Httyname@; see section ‰ŠP�”›Identifying Terminals@�”˜.
The function Hctermid@ is declared in the header file H`stdio.h'@. ‰IDX1937Š

A�”˜Function:@ char * Dctermid@ B(char *Bstring@)
Â‰IDX1938Š@�”˜The Hctermid@ function returns a string containing the file name of the controlling terminal for the current process. If Bstring@ is not a null pointer, it should be an array that can hold at least HL_ctermid@ characters; the string is returned in this array. Otherwise, a pointer to a string in a static area is returned, which might get overwritten on subsequent calls to this function.
An empty string is returned if the file name cannot be determined for any reason. Even if a file name is returned, access to the file it represents is not guaranteed.À

AMacro:@ int DL_ctermid
Â‰IDX1939Š@�”˜The value of this macro is an integer constant expression that represents the size of a string large enough to hold the file name returned by Hctermid@.À

See also the Hisatty@ and Httyname@ functions, in section ‰ŠP�”›Identifying Terminals@�”˜.
ˆ‰SEC433ŠT�”›Process Group Functions

@�”˜Here are descriptions of the functions for manipulating process groups. Your program should include the header files H`sys/types.h'@ and H`unistd.h'@ to use these functions. ‰IDX1940Š‰IDX1941Š

A�”˜Function:@ pid_t Dsetsid@ B(void)
Â‰IDX1942Š@�”˜The Hsetsid@ function creates a new session. The calling process becomes the session leader, and is put in a new process group whose process group ID is the same as the process ID of that process. There are initially no other processes in the new process group, and no other process groups in the new session.
This function also makes the calling process have no controlling terminal.
The Hsetsid@ function returns the new process group ID of the calling process if successful. A return value of H-1@ indicates an error. The following Herrno@ error conditions are defined for this function:
HEPERM
Ä@The calling process is already a process group leader, or there is already another process group around that has the same process group ID.Â
À

The Hgetpgrp@ function has two definitions: one derived from BSD Unix, and one from the POSIX.1 standard. The feature test macros you have selected (see section ‰ŠP�”›Feature Test Macros@�”˜) determine which definition you get. Specifically, you get the BSD version if you define H_BSD_SOURCE@; otherwise, you get the POSIX version if you define H_POSIX_SOURCE@ or H_GNU_SOURCE@. Programs written for old BSD systems will not include H`unistd.h'@, which defines Hgetpgrp@ specially under H_BSD_SOURCE@. You must link such programs with the H-lbsd-compat@ option to get the BSD definition.‰IDX1943Š@�”˜ ‰IDX1944Š‰IDX1945Š

A�”˜POSIX.1 Function:@ pid_t Dgetpgrp@ B(void)
Â‰IDX1946Š@�”˜The POSIX.1 definition of Hgetpgrp@ returns the process group ID of the calling process.À

ABSD Function:@ pid_t Dgetpgrp@ B(pid_t Bpid@)
Â‰IDX1947Š@�”˜The BSD definition of Hgetpgrp@ returns the process group ID of the process Bpid@. You can supply a value of H0@ for the Bpid@ argument to get information about the calling process.À

AFunction:@ int Dsetpgid@ B(pid_t Bpid@, pid_t Bpgid@)
Â‰IDX1948Š@�”˜The Hsetpgid@ function puts the process Bpid@ into the process group Bpgid@. As a special case, either Bpid@ or Bpgid@ can be zero to indicate the process ID of the calling process.
This function fails on a system that does not support job control. See section ‰ŠP�”›Job Control is Optional@�”˜, for more information.
If the operation is successful, Hsetpgid@ returns zero. Otherwise it returns H-1@. The following Herrno@ error conditions are defined for this function:
HEACCES
Ä@The child process named by Bpid@ has executed an Hexec@ function since it was forked.
ÂHEINVAL
Ä@The value of the Bpgid@ is not valid.
ÂHENOSYS
Ä@The system doesn't support job control.
ÂHEPERM
Ä@The process indicated by the Bpid@ argument is a session leader, or is not in the same session as the calling process, or the value of the Bpgid@ argument doesn't match a process group ID in the same session as the calling process.
ÂHESRCH
Ä@The process indicated by the Bpid@ argument is not the calling process or a child of the calling process.Â
À

AFunction:@ int Dsetpgrp@ B(pid_t Bpid@, pid_t Bpgid@)
Â‰IDX1949Š@�”˜This is the BSD Unix name for Hsetpgid@. Both functions do exactly the same thing.À

ˆ‰SEC434ŠT�”›Functions for Controlling Terminal Access

@�”˜These are the functions for reading or setting the foreground process group of a terminal. You should include the header files H`sys/types.h'@ and H`unistd.h'@ in your application to use these functions. ‰IDX1950Š‰IDX1951Š
@�”˜Although these functions take a file descriptor argument to specify the terminal device, the foreground job is associated with the terminal file itself and not a particular open file descriptor.

AFunction:@ pid_t Dtcgetpgrp@ B(int Bfiledes@)
Â‰IDX1952Š@�”˜This function returns the process group ID of the foreground process group associated with the terminal open on descriptor Bfiledes@.
If there is no foreground process group, the return value is a number greater than H1@ that does not match the process group ID of any existing process group. This can happen if all of the processes in the job that was formerly the foreground job have terminated, and no other job has yet been moved into the foreground.
In case of an error, a value of H-1@ is returned. The following Herrno@ error conditions are defined for this function:
HEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor.
ÂHENOSYS
Ä@The system doesn't support job control.
ÂHENOTTY
Ä@The terminal file associated with the Bfiledes@ argument isn't the controlling terminal of the calling process.Â
À

AFunction:@ int Dtcsetpgrp@ B(int Bfiledes@, pid_t Bpgid@)
Â‰IDX1953Š@�”˜This function is used to set a terminal's foreground process group ID. The argument Bfiledes@ is a descriptor which specifies the terminal; Bpgid@ specifies the process group. The calling process must be a member of the same session as Bpgid@ and must have the same controlling terminal.
For terminal access purposes, this function is treated as output. If it is called from a background process on its controlling terminal, normally all processes in the process group are sent a HSIGTTOU@ signal. The exception is if the calling process itself is ignoring or blocking HSIGTTOU@ signals, in which case the operation is performed and no signal is sent.
If successful, Htcsetpgrp@ returns H0@. A return value of H-1@ indicates an error. The following Herrno@ error conditions are defined for this function:
HEBADF
Ä@The Bfiledes@ argument is not a valid file descriptor.
ÂHEINVAL
Ä@The Bpgid@ argument is not valid.
ÂHENOSYS
Ä@The system doesn't support job control.
ÂHENOTTY
Ä@The Bfiledes@ isn't the controlling terminal of the calling process.
ÂHEPERM
Ä@The Bpgid@ isn't a process group in the same session as the calling process.Â
À

Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.