Running In The Background

In Chapter 17 (p. 369), I described how to move a process into the background after it had begun running. A typical use for this is to read passwords and then go into the background to sleep before using the passwords to do real work.

Moving a process into the background is tricky. It also differs from system to system. Fortunately, Expect incorporates this same functionality inside of the spawn routines. Because moving processes into the background is such a common task for programs that use the Expect library, it is available through a separate interface.

To move a process into the background, fork a process, call exp_disconnect in the child process, and then call exit in the parent process. Here is code to do this:

    switch (fork()) {
    case 0: /* child */
        exp_disconnect();
        break;
    case −1: /* error */
        perror("fork");
    default: /* parent */
        exit(0);
    }

Calling exp_disconnect disassociates the process from the controlling terminal. If you wish to move a process into the background in a different way, you must set the integer variable exp_disconnected to 1. (Initially it is 0.) This allows processes spawned after this point to be started correctly. The exp_disconnect function sets exp_disconnected to 1.

int exp_disconnected;

exp_disconnected is also shared with the Expect program. If you invoke Expect’s disconnect command, it will also set exp_disconnected to 1.

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.