The Linux Programming Interface

(nextflipdebug5) #1

1386 Chapter 64


this argument o. Use of this argument is a convenience for certain interac-
tive programs (e.g., script(1)) that use a pseudoterminal and need to set the
attributes of the slave device to be the same as those of the terminal under
which the program is run.
–If the slaveWS argument is non-NULL, perform an ioctl() TIOCSWINSZ operation
to set the window size of the pseudoterminal slave to the values in the
winsize structure pointed to by this argument a. This step is performed for
the same reason as the previous step.
–Use dup2() to duplicate the slave file descriptor to be the standard input,
output, and error for the child s. At this point, the child can now exec an
arbitrary program, and that program can use the standard file descriptors
to communicate with the pseudoterminal. The execed program can per-
form all of the usual terminal-oriented operations that can be performed
by a program running on a conventional terminal.

As with fork(), ptyFork() returns the process ID of the child in the parent process, 0
in the child process, or –1 on error.
Eventually, the child process created by ptyFork() will terminate. If the parent
doesn’t terminate at the same time, then it must wait on the child to eliminate the
resulting zombie. However, this step can often be eliminated, since applications
that employ pseudoterminals are commonly designed so that the parent does ter-
minate at the same time as the child.
BSD derivatives provide two related, nonstandard functions for working with
pseudoterminals. The first of these is openpty(), which opens a pseudoterminal
pair, returns the file descriptors for the master and slave, optionally returns
the name of the slave device, and optionally sets the terminal attributes and
window size from arguments analogous to slaveTermios and slaveWS. The other
function, forkpty(), is the same as our ptyFork(), except that it doesn’t provide
an analog of the snLen argument. On Linux, both of these functions are pro-
vided by glibc and are documented in the openpty(3) manual page.

Listing 64-2: Implementation of ptyFork()
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––pty/pty_fork.c
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include "pty_master_open.h"
#include "pty_fork.h" /* Declares ptyFork() */
#include "tlpi_hdr.h"

#define MAX_SNAME 1000

pid_t
ptyFork(int *masterFd, char *slaveName, size_t snLen,
const struct termios *slaveTermios, const struct winsize *slaveWS)
{
int mfd, slaveFd, savedErrno;
pid_t childPid;
char slname[MAX_SNAME];
Free download pdf