Home | History | Annotate | Line # | Download | only in sh
jobs.c revision 1.99
      1  1.99       kre /*	$NetBSD: jobs.c,v 1.99 2018/09/04 01:09:28 kre Exp $	*/
      2  1.15       cgd 
      3   1.1       cgd /*-
      4   1.8       jtc  * Copyright (c) 1991, 1993
      5   1.8       jtc  *	The Regents of the University of California.  All rights reserved.
      6   1.1       cgd  *
      7   1.1       cgd  * This code is derived from software contributed to Berkeley by
      8   1.1       cgd  * Kenneth Almquist.
      9   1.1       cgd  *
     10   1.1       cgd  * Redistribution and use in source and binary forms, with or without
     11   1.1       cgd  * modification, are permitted provided that the following conditions
     12   1.1       cgd  * are met:
     13   1.1       cgd  * 1. Redistributions of source code must retain the above copyright
     14   1.1       cgd  *    notice, this list of conditions and the following disclaimer.
     15   1.1       cgd  * 2. Redistributions in binary form must reproduce the above copyright
     16   1.1       cgd  *    notice, this list of conditions and the following disclaimer in the
     17   1.1       cgd  *    documentation and/or other materials provided with the distribution.
     18  1.58       agc  * 3. Neither the name of the University nor the names of its contributors
     19   1.1       cgd  *    may be used to endorse or promote products derived from this software
     20   1.1       cgd  *    without specific prior written permission.
     21   1.1       cgd  *
     22   1.1       cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23   1.1       cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24   1.1       cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25   1.1       cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26   1.1       cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27   1.1       cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28   1.1       cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29   1.1       cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30   1.1       cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31   1.1       cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32   1.1       cgd  * SUCH DAMAGE.
     33   1.1       cgd  */
     34   1.1       cgd 
     35  1.22  christos #include <sys/cdefs.h>
     36   1.1       cgd #ifndef lint
     37  1.15       cgd #if 0
     38  1.16  christos static char sccsid[] = "@(#)jobs.c	8.5 (Berkeley) 5/4/95";
     39  1.15       cgd #else
     40  1.99       kre __RCSID("$NetBSD: jobs.c,v 1.99 2018/09/04 01:09:28 kre Exp $");
     41  1.15       cgd #endif
     42   1.1       cgd #endif /* not lint */
     43   1.1       cgd 
     44  1.95       kre #include <stdio.h>
     45  1.16  christos #include <fcntl.h>
     46  1.16  christos #include <signal.h>
     47  1.16  christos #include <errno.h>
     48  1.16  christos #include <unistd.h>
     49  1.16  christos #include <stdlib.h>
     50  1.26      fair #include <paths.h>
     51  1.16  christos #include <sys/types.h>
     52  1.16  christos #include <sys/param.h>
     53  1.16  christos #ifdef BSD
     54  1.16  christos #include <sys/wait.h>
     55  1.16  christos #include <sys/time.h>
     56  1.16  christos #include <sys/resource.h>
     57  1.16  christos #endif
     58  1.19  christos #include <sys/ioctl.h>
     59  1.16  christos 
     60   1.1       cgd #include "shell.h"
     61   1.1       cgd #if JOBS
     62  1.19  christos #if OLD_TTY_DRIVER
     63   1.1       cgd #include "sgtty.h"
     64  1.19  christos #else
     65  1.19  christos #include <termios.h>
     66  1.19  christos #endif
     67   1.1       cgd #undef CEOF			/* syntax.h redefines this */
     68   1.1       cgd #endif
     69  1.16  christos #include "redir.h"
     70  1.16  christos #include "show.h"
     71   1.1       cgd #include "main.h"
     72   1.1       cgd #include "parser.h"
     73   1.1       cgd #include "nodes.h"
     74   1.1       cgd #include "jobs.h"
     75  1.95       kre #include "var.h"
     76   1.1       cgd #include "options.h"
     77  1.69  christos #include "builtins.h"
     78   1.1       cgd #include "trap.h"
     79   1.1       cgd #include "syntax.h"
     80   1.1       cgd #include "input.h"
     81   1.1       cgd #include "output.h"
     82   1.1       cgd #include "memalloc.h"
     83   1.1       cgd #include "error.h"
     84   1.1       cgd #include "mystring.h"
     85   1.1       cgd 
     86   1.1       cgd 
     87  1.91       kre #ifndef	WCONTINUED
     88  1.91       kre #define	WCONTINUED 0		/* So we can compile on old systems */
     89  1.91       kre #endif
     90  1.91       kre #ifndef	WIFCONTINUED
     91  1.91       kre #define	WIFCONTINUED(x)	(0)		/* ditto */
     92  1.91       kre #endif
     93  1.91       kre 
     94  1.91       kre 
     95  1.55  christos static struct job *jobtab;		/* array of jobs */
     96  1.55  christos static int njobs;			/* size of array */
     97  1.55  christos static int jobs_invalid;		/* set in child */
     98  1.55  christos MKINIT pid_t backgndpid = -1;	/* pid of last background process */
     99   1.1       cgd #if JOBS
    100   1.1       cgd int initialpgrp;		/* pgrp of shell on invocation */
    101  1.55  christos static int curjob = -1;		/* current job */
    102   1.1       cgd #endif
    103  1.44  christos static int ttyfd = -1;
    104   1.1       cgd 
    105  1.55  christos STATIC void restartjob(struct job *);
    106  1.55  christos STATIC void freejob(struct job *);
    107  1.55  christos STATIC struct job *getjob(const char *, int);
    108  1.95       kre STATIC int dowait(int, struct job *, struct job **);
    109  1.68  christos #define WBLOCK	1
    110  1.68  christos #define WNOFREE 2
    111  1.91       kre #define WSILENT 4
    112  1.90       kre STATIC int jobstatus(const struct job *, int);
    113  1.55  christos STATIC int waitproc(int, struct job *, int *);
    114  1.55  christos STATIC void cmdtxt(union node *);
    115  1.55  christos STATIC void cmdlist(union node *, int);
    116  1.55  christos STATIC void cmdputs(const char *);
    117  1.78       kre inline static void cmdputi(int);
    118   1.1       cgd 
    119  1.66  dholland #ifdef SYSV
    120  1.66  dholland STATIC int onsigchild(void);
    121  1.66  dholland #endif
    122  1.66  dholland 
    123  1.44  christos #ifdef OLD_TTY_DRIVER
    124  1.55  christos static pid_t tcgetpgrp(int fd);
    125  1.55  christos static int tcsetpgrp(int fd, pid_t pgrp);
    126  1.44  christos 
    127  1.44  christos static pid_t
    128  1.55  christos tcgetpgrp(int fd)
    129  1.44  christos {
    130  1.44  christos 	pid_t pgrp;
    131  1.44  christos 	if (ioctl(fd, TIOCGPGRP, (char *)&pgrp) == -1)
    132  1.44  christos 		return -1;
    133  1.44  christos 	else
    134  1.44  christos 		return pgrp;
    135  1.44  christos }
    136  1.44  christos 
    137  1.44  christos static int
    138  1.55  christos tcsetpgrp(int fd, pid_tpgrp)
    139  1.44  christos {
    140  1.44  christos 	return ioctl(fd, TIOCSPGRP, (char *)&pgrp);
    141  1.44  christos }
    142  1.44  christos #endif
    143   1.8       jtc 
    144  1.80       kre static void
    145  1.80       kre ttyfd_change(int from, int to)
    146  1.80       kre {
    147  1.80       kre 	if (ttyfd == from)
    148  1.80       kre 		ttyfd = to;
    149  1.80       kre }
    150  1.80       kre 
    151   1.1       cgd /*
    152   1.1       cgd  * Turn job control on and off.
    153   1.1       cgd  *
    154   1.1       cgd  * Note:  This code assumes that the third arg to ioctl is a character
    155   1.1       cgd  * pointer, which is true on Berkeley systems but not System V.  Since
    156   1.1       cgd  * System V doesn't have job control yet, this isn't a problem now.
    157   1.1       cgd  */
    158   1.1       cgd 
    159   1.1       cgd MKINIT int jobctl;
    160   1.1       cgd 
    161   1.1       cgd void
    162  1.55  christos setjobctl(int on)
    163  1.13       cgd {
    164   1.8       jtc #ifdef OLD_TTY_DRIVER
    165   1.1       cgd 	int ldisc;
    166   1.8       jtc #endif
    167   1.1       cgd 
    168   1.1       cgd 	if (on == jobctl || rootshell == 0)
    169   1.1       cgd 		return;
    170   1.1       cgd 	if (on) {
    171  1.44  christos #if defined(FIOCLEX) || defined(FD_CLOEXEC)
    172  1.57  christos 		int i;
    173  1.80       kre 
    174  1.44  christos 		if (ttyfd != -1)
    175  1.80       kre 			sh_close(ttyfd);
    176  1.45  christos 		if ((ttyfd = open("/dev/tty", O_RDWR)) == -1) {
    177  1.45  christos 			for (i = 0; i < 3; i++) {
    178  1.45  christos 				if (isatty(i) && (ttyfd = dup(i)) != -1)
    179  1.45  christos 					break;
    180  1.45  christos 			}
    181  1.45  christos 			if (i == 3)
    182  1.45  christos 				goto out;
    183  1.45  christos 		}
    184  1.76  christos 		ttyfd = to_upper_fd(ttyfd);	/* Move to a high fd */
    185  1.80       kre 		register_sh_fd(ttyfd, ttyfd_change);
    186  1.18   mycroft #else
    187  1.44  christos 		out2str("sh: Need FIOCLEX or FD_CLOEXEC to support job control");
    188  1.44  christos 		goto out;
    189  1.18   mycroft #endif
    190  1.44  christos 		do { /* while we are in the background */
    191  1.44  christos 			if ((initialpgrp = tcgetpgrp(ttyfd)) < 0) {
    192  1.80       kre  out:
    193   1.8       jtc 				out2str("sh: can't access tty; job control turned off\n");
    194   1.8       jtc 				mflag = 0;
    195   1.1       cgd 				return;
    196   1.1       cgd 			}
    197   1.1       cgd 			if (initialpgrp == -1)
    198  1.10       jtc 				initialpgrp = getpgrp();
    199  1.10       jtc 			else if (initialpgrp != getpgrp()) {
    200  1.44  christos 				killpg(0, SIGTTIN);
    201   1.1       cgd 				continue;
    202   1.1       cgd 			}
    203   1.1       cgd 		} while (0);
    204  1.44  christos 
    205   1.8       jtc #ifdef OLD_TTY_DRIVER
    206  1.44  christos 		if (ioctl(ttyfd, TIOCGETD, (char *)&ldisc) < 0
    207  1.44  christos 		    || ldisc != NTTYDISC) {
    208   1.8       jtc 			out2str("sh: need new tty driver to run job control; job control turned off\n");
    209   1.8       jtc 			mflag = 0;
    210   1.1       cgd 			return;
    211   1.1       cgd 		}
    212   1.8       jtc #endif
    213  1.47  christos 		setsignal(SIGTSTP, 0);
    214  1.47  christos 		setsignal(SIGTTOU, 0);
    215  1.47  christos 		setsignal(SIGTTIN, 0);
    216  1.64        tv 		if (getpgrp() != rootpid && setpgid(0, rootpid) == -1)
    217  1.47  christos 			error("Cannot set process group (%s) at %d",
    218  1.47  christos 			    strerror(errno), __LINE__);
    219  1.47  christos 		if (tcsetpgrp(ttyfd, rootpid) == -1)
    220  1.47  christos 			error("Cannot set tty process group (%s) at %d",
    221  1.47  christos 			    strerror(errno), __LINE__);
    222   1.1       cgd 	} else { /* turning job control off */
    223  1.64        tv 		if (getpgrp() != initialpgrp && setpgid(0, initialpgrp) == -1)
    224  1.47  christos 			error("Cannot set process group (%s) at %d",
    225  1.47  christos 			    strerror(errno), __LINE__);
    226  1.47  christos 		if (tcsetpgrp(ttyfd, initialpgrp) == -1)
    227  1.47  christos 			error("Cannot set tty process group (%s) at %d",
    228  1.47  christos 			    strerror(errno), __LINE__);
    229  1.80       kre 		sh_close(ttyfd);
    230  1.44  christos 		ttyfd = -1;
    231  1.47  christos 		setsignal(SIGTSTP, 0);
    232  1.47  christos 		setsignal(SIGTTOU, 0);
    233  1.47  christos 		setsignal(SIGTTIN, 0);
    234   1.1       cgd 	}
    235   1.1       cgd 	jobctl = on;
    236   1.1       cgd }
    237   1.1       cgd 
    238   1.1       cgd 
    239   1.1       cgd #ifdef mkinit
    240  1.16  christos INCLUDE <stdlib.h>
    241   1.1       cgd 
    242   1.1       cgd SHELLPROC {
    243   1.1       cgd 	backgndpid = -1;
    244   1.1       cgd #if JOBS
    245   1.1       cgd 	jobctl = 0;
    246   1.1       cgd #endif
    247   1.1       cgd }
    248   1.1       cgd 
    249   1.1       cgd #endif
    250   1.1       cgd 
    251   1.1       cgd 
    252   1.1       cgd 
    253   1.1       cgd #if JOBS
    254  1.71       dsl static int
    255  1.71       dsl do_fgcmd(const char *arg_ptr)
    256  1.13       cgd {
    257   1.1       cgd 	struct job *jp;
    258  1.47  christos 	int i;
    259   1.1       cgd 	int status;
    260   1.1       cgd 
    261  1.91       kre 	if (jobs_invalid)
    262  1.91       kre 		error("No current jobs");
    263  1.71       dsl 	jp = getjob(arg_ptr, 0);
    264   1.1       cgd 	if (jp->jobctl == 0)
    265   1.1       cgd 		error("job not created under job control");
    266  1.55  christos 	out1fmt("%s", jp->ps[0].cmd);
    267  1.55  christos 	for (i = 1; i < jp->nprocs; i++)
    268  1.55  christos 		out1fmt(" | %s", jp->ps[i].cmd );
    269  1.55  christos 	out1c('\n');
    270  1.55  christos 	flushall();
    271  1.47  christos 
    272  1.48  christos 	for (i = 0; i < jp->nprocs; i++)
    273  1.47  christos 	    if (tcsetpgrp(ttyfd, jp->ps[i].pid) != -1)
    274  1.47  christos 		    break;
    275  1.47  christos 
    276  1.48  christos 	if (i >= jp->nprocs) {
    277  1.47  christos 		error("Cannot set tty process group (%s) at %d",
    278  1.47  christos 		    strerror(errno), __LINE__);
    279  1.47  christos 	}
    280   1.1       cgd 	restartjob(jp);
    281   1.1       cgd 	INTOFF;
    282   1.1       cgd 	status = waitforjob(jp);
    283   1.1       cgd 	INTON;
    284   1.1       cgd 	return status;
    285   1.1       cgd }
    286   1.1       cgd 
    287  1.71       dsl int
    288  1.71       dsl fgcmd(int argc, char **argv)
    289  1.71       dsl {
    290  1.71       dsl 	nextopt("");
    291  1.71       dsl 	return do_fgcmd(*argptr);
    292  1.71       dsl }
    293  1.71       dsl 
    294  1.71       dsl int
    295  1.71       dsl fgcmd_percent(int argc, char **argv)
    296  1.71       dsl {
    297  1.71       dsl 	nextopt("");
    298  1.71       dsl 	return do_fgcmd(*argv);
    299  1.71       dsl }
    300  1.71       dsl 
    301  1.55  christos static void
    302  1.55  christos set_curjob(struct job *jp, int mode)
    303  1.55  christos {
    304  1.55  christos 	struct job *jp1, *jp2;
    305  1.55  christos 	int i, ji;
    306  1.55  christos 
    307  1.55  christos 	ji = jp - jobtab;
    308  1.55  christos 
    309  1.55  christos 	/* first remove from list */
    310  1.55  christos 	if (ji == curjob)
    311  1.55  christos 		curjob = jp->prev_job;
    312  1.55  christos 	else {
    313  1.55  christos 		for (i = 0; i < njobs; i++) {
    314  1.55  christos 			if (jobtab[i].prev_job != ji)
    315  1.55  christos 				continue;
    316  1.55  christos 			jobtab[i].prev_job = jp->prev_job;
    317  1.55  christos 			break;
    318  1.55  christos 		}
    319  1.55  christos 	}
    320  1.55  christos 
    321  1.55  christos 	/* Then re-insert in correct position */
    322  1.55  christos 	switch (mode) {
    323  1.55  christos 	case 0:	/* job being deleted */
    324  1.55  christos 		jp->prev_job = -1;
    325  1.55  christos 		break;
    326  1.55  christos 	case 1:	/* newly created job or backgrounded job,
    327  1.55  christos 		   put after all stopped jobs. */
    328  1.55  christos 		if (curjob != -1 && jobtab[curjob].state == JOBSTOPPED) {
    329  1.55  christos 			for (jp1 = jobtab + curjob; ; jp1 = jp2) {
    330  1.55  christos 				if (jp1->prev_job == -1)
    331  1.55  christos 					break;
    332  1.55  christos 				jp2 = jobtab + jp1->prev_job;
    333  1.55  christos 				if (jp2->state != JOBSTOPPED)
    334  1.55  christos 					break;
    335  1.55  christos 			}
    336  1.55  christos 			jp->prev_job = jp1->prev_job;
    337  1.55  christos 			jp1->prev_job = ji;
    338  1.55  christos 			break;
    339  1.55  christos 		}
    340  1.55  christos 		/* FALLTHROUGH */
    341  1.55  christos 	case 2:	/* newly stopped job - becomes curjob */
    342  1.55  christos 		jp->prev_job = curjob;
    343  1.55  christos 		curjob = ji;
    344  1.55  christos 		break;
    345  1.55  christos 	}
    346  1.55  christos }
    347   1.1       cgd 
    348  1.13       cgd int
    349  1.55  christos bgcmd(int argc, char **argv)
    350  1.13       cgd {
    351   1.1       cgd 	struct job *jp;
    352  1.55  christos 	int i;
    353   1.1       cgd 
    354  1.55  christos 	nextopt("");
    355  1.91       kre 	if (jobs_invalid)
    356  1.91       kre 		error("No current jobs");
    357   1.1       cgd 	do {
    358  1.55  christos 		jp = getjob(*argptr, 0);
    359   1.1       cgd 		if (jp->jobctl == 0)
    360   1.1       cgd 			error("job not created under job control");
    361  1.55  christos 		set_curjob(jp, 1);
    362  1.56       agc 		out1fmt("[%ld] %s", (long)(jp - jobtab + 1), jp->ps[0].cmd);
    363  1.55  christos 		for (i = 1; i < jp->nprocs; i++)
    364  1.55  christos 			out1fmt(" | %s", jp->ps[i].cmd );
    365  1.55  christos 		out1c('\n');
    366  1.55  christos 		flushall();
    367   1.1       cgd 		restartjob(jp);
    368  1.55  christos 	} while (*argptr && *++argptr);
    369   1.1       cgd 	return 0;
    370   1.1       cgd }
    371   1.1       cgd 
    372   1.1       cgd 
    373   1.1       cgd STATIC void
    374  1.55  christos restartjob(struct job *jp)
    375  1.13       cgd {
    376   1.1       cgd 	struct procstat *ps;
    377   1.1       cgd 	int i;
    378   1.1       cgd 
    379   1.1       cgd 	if (jp->state == JOBDONE)
    380   1.1       cgd 		return;
    381   1.1       cgd 	INTOFF;
    382  1.48  christos 	for (i = 0; i < jp->nprocs; i++)
    383  1.47  christos 		if (killpg(jp->ps[i].pid, SIGCONT) != -1)
    384  1.47  christos 			break;
    385  1.48  christos 	if (i >= jp->nprocs)
    386  1.47  christos 		error("Cannot continue job (%s)", strerror(errno));
    387   1.1       cgd 	for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
    388  1.23  christos 		if (WIFSTOPPED(ps->status)) {
    389  1.92       kre 			VTRACE(DBG_JOBS, (
    390  1.94       kre 			   "restartjob: [%zu] pid %d status change"
    391  1.92       kre 			   " from %#x (stopped) to -1 (running)\n",
    392  1.92       kre 			   (size_t)(jp-jobtab+1), ps->pid, ps->status));
    393   1.1       cgd 			ps->status = -1;
    394  1.55  christos 			jp->state = JOBRUNNING;
    395   1.1       cgd 		}
    396   1.1       cgd 	}
    397   1.1       cgd 	INTON;
    398   1.1       cgd }
    399   1.1       cgd #endif
    400   1.1       cgd 
    401  1.78       kre inline static void
    402  1.77       kre cmdputi(int n)
    403  1.77       kre {
    404  1.77       kre 	char str[20];
    405  1.77       kre 
    406  1.77       kre 	fmtstr(str, sizeof str, "%d", n);
    407  1.77       kre 	cmdputs(str);
    408  1.77       kre }
    409  1.77       kre 
    410  1.55  christos static void
    411  1.55  christos showjob(struct output *out, struct job *jp, int mode)
    412  1.55  christos {
    413  1.55  christos 	int procno;
    414  1.55  christos 	int st;
    415  1.55  christos 	struct procstat *ps;
    416  1.55  christos 	int col;
    417  1.55  christos 	char s[64];
    418  1.55  christos 
    419  1.55  christos #if JOBS
    420  1.55  christos 	if (mode & SHOW_PGID) {
    421  1.55  christos 		/* just output process (group) id of pipeline */
    422  1.55  christos 		outfmt(out, "%ld\n", (long)jp->ps->pid);
    423  1.55  christos 		return;
    424  1.55  christos 	}
    425  1.55  christos #endif
    426  1.55  christos 
    427  1.55  christos 	procno = jp->nprocs;
    428  1.55  christos 	if (!procno)
    429  1.55  christos 		return;
    430  1.55  christos 
    431  1.55  christos 	if (mode & SHOW_PID)
    432  1.55  christos 		mode |= SHOW_MULTILINE;
    433  1.55  christos 
    434  1.55  christos 	if ((procno > 1 && !(mode & SHOW_MULTILINE))
    435  1.55  christos 	    || (mode & SHOW_SIGNALLED)) {
    436  1.55  christos 		/* See if we have more than one status to report */
    437  1.55  christos 		ps = jp->ps;
    438  1.55  christos 		st = ps->status;
    439  1.55  christos 		do {
    440  1.55  christos 			int st1 = ps->status;
    441  1.55  christos 			if (st1 != st)
    442  1.55  christos 				/* yes - need multi-line output */
    443  1.55  christos 				mode |= SHOW_MULTILINE;
    444  1.55  christos 			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
    445  1.55  christos 				continue;
    446  1.55  christos 			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
    447  1.55  christos 			    && st1 != SIGINT && st1 != SIGPIPE))
    448  1.55  christos 				mode |= SHOW_ISSIG;
    449  1.55  christos 
    450  1.55  christos 		} while (ps++, --procno);
    451  1.55  christos 		procno = jp->nprocs;
    452  1.55  christos 	}
    453  1.55  christos 
    454  1.55  christos 	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
    455  1.55  christos 		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
    456  1.87       kre 			VTRACE(DBG_JOBS, ("showjob: freeing job %d\n",
    457  1.87       kre 			    jp - jobtab + 1));
    458  1.55  christos 			freejob(jp);
    459  1.55  christos 		}
    460  1.55  christos 		return;
    461  1.55  christos 	}
    462  1.55  christos 
    463  1.55  christos 	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
    464  1.55  christos 		if (ps == jp->ps)
    465  1.56       agc 			fmtstr(s, 16, "[%ld] %c ",
    466  1.56       agc 				(long)(jp - jobtab + 1),
    467  1.55  christos #if JOBS
    468  1.98       kre 				jp - jobtab == curjob ?
    469  1.98       kre 									  '+' :
    470  1.98       kre 				curjob != -1 &&
    471  1.98       kre 				    jp - jobtab == jobtab[curjob].prev_job ?
    472  1.98       kre 									  '-' :
    473  1.55  christos #endif
    474  1.55  christos 				' ');
    475  1.55  christos 		else
    476  1.55  christos 			fmtstr(s, 16, "      " );
    477  1.55  christos 		col = strlen(s);
    478  1.55  christos 		if (mode & SHOW_PID) {
    479  1.55  christos 			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
    480  1.55  christos 			     col += strlen(s + col);
    481  1.55  christos 		}
    482  1.55  christos 		if (ps->status == -1) {
    483  1.55  christos 			scopy("Running", s + col);
    484  1.55  christos 		} else if (WIFEXITED(ps->status)) {
    485  1.55  christos 			st = WEXITSTATUS(ps->status);
    486  1.55  christos 			if (st)
    487  1.55  christos 				fmtstr(s + col, 16, "Done(%d)", st);
    488  1.55  christos 			else
    489  1.55  christos 				fmtstr(s + col, 16, "Done");
    490  1.55  christos 		} else {
    491  1.55  christos #if JOBS
    492  1.91       kre 			if (WIFSTOPPED(ps->status))
    493  1.55  christos 				st = WSTOPSIG(ps->status);
    494  1.55  christos 			else /* WIFSIGNALED(ps->status) */
    495  1.55  christos #endif
    496  1.55  christos 				st = WTERMSIG(ps->status);
    497  1.55  christos 			st &= 0x7f;
    498  1.55  christos 			if (st < NSIG && sys_siglist[st])
    499  1.55  christos 				scopyn(sys_siglist[st], s + col, 32);
    500  1.55  christos 			else
    501  1.55  christos 				fmtstr(s + col, 16, "Signal %d", st);
    502  1.55  christos 			if (WCOREDUMP(ps->status)) {
    503  1.55  christos 				col += strlen(s + col);
    504  1.55  christos 				scopyn(" (core dumped)", s + col,  64 - col);
    505  1.55  christos 			}
    506  1.55  christos 		}
    507  1.55  christos 		col += strlen(s + col);
    508  1.55  christos 		outstr(s, out);
    509  1.55  christos 		do {
    510  1.55  christos 			outc(' ', out);
    511  1.55  christos 			col++;
    512  1.55  christos 		} while (col < 30);
    513  1.55  christos 		outstr(ps->cmd, out);
    514  1.55  christos 		if (mode & SHOW_MULTILINE) {
    515  1.55  christos 			if (procno > 0) {
    516  1.55  christos 				outc(' ', out);
    517  1.55  christos 				outc('|', out);
    518  1.55  christos 			}
    519  1.55  christos 		} else {
    520  1.55  christos 			while (--procno >= 0)
    521  1.55  christos 				outfmt(out, " | %s", (++ps)->cmd );
    522  1.55  christos 		}
    523  1.55  christos 		outc('\n', out);
    524  1.55  christos 	}
    525  1.55  christos 	flushout(out);
    526  1.95       kre 	jp->flags &= ~JOBCHANGED;
    527  1.55  christos 	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
    528  1.55  christos 		freejob(jp);
    529  1.55  christos }
    530  1.55  christos 
    531   1.1       cgd int
    532  1.55  christos jobscmd(int argc, char **argv)
    533  1.13       cgd {
    534  1.55  christos 	int mode, m;
    535  1.55  christos 
    536  1.55  christos 	mode = 0;
    537  1.55  christos 	while ((m = nextopt("lp")))
    538  1.55  christos 		if (m == 'l')
    539  1.55  christos 			mode = SHOW_PID;
    540  1.55  christos 		else
    541  1.55  christos 			mode = SHOW_PGID;
    542  1.91       kre 	if (!iflag)
    543  1.91       kre 		mode |= SHOW_NO_FREE;
    544  1.55  christos 	if (*argptr)
    545  1.55  christos 		do
    546  1.55  christos 			showjob(out1, getjob(*argptr,0), mode);
    547  1.55  christos 		while (*++argptr);
    548  1.55  christos 	else
    549  1.55  christos 		showjobs(out1, mode);
    550   1.1       cgd 	return 0;
    551   1.1       cgd }
    552   1.1       cgd 
    553   1.1       cgd 
    554   1.1       cgd /*
    555   1.1       cgd  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
    556   1.1       cgd  * statuses have changed since the last call to showjobs.
    557   1.1       cgd  *
    558   1.1       cgd  * If the shell is interrupted in the process of creating a job, the
    559   1.1       cgd  * result may be a job structure containing zero processes.  Such structures
    560   1.1       cgd  * will be freed here.
    561   1.1       cgd  */
    562   1.1       cgd 
    563   1.1       cgd void
    564  1.55  christos showjobs(struct output *out, int mode)
    565  1.13       cgd {
    566   1.1       cgd 	int jobno;
    567   1.1       cgd 	struct job *jp;
    568  1.47  christos 	int silent = 0, gotpid;
    569   1.1       cgd 
    570  1.87       kre 	CTRACE(DBG_JOBS, ("showjobs(%x) called\n", mode));
    571  1.47  christos 
    572  1.47  christos 	/* If not even one one job changed, there is nothing to do */
    573  1.95       kre 	gotpid = dowait(WSILENT, NULL, NULL);
    574  1.95       kre 	while (dowait(WSILENT, NULL, NULL) > 0)
    575  1.47  christos 		continue;
    576  1.47  christos #ifdef JOBS
    577  1.47  christos 	/*
    578  1.47  christos 	 * Check if we are not in our foreground group, and if not
    579  1.47  christos 	 * put us in it.
    580  1.47  christos 	 */
    581  1.54  christos 	if (mflag && gotpid != -1 && tcgetpgrp(ttyfd) != getpid()) {
    582  1.47  christos 		if (tcsetpgrp(ttyfd, getpid()) == -1)
    583  1.47  christos 			error("Cannot set tty process group (%s) at %d",
    584  1.47  christos 			    strerror(errno), __LINE__);
    585  1.87       kre 		VTRACE(DBG_JOBS|DBG_INPUT, ("repaired tty process group\n"));
    586  1.47  christos 		silent = 1;
    587  1.47  christos 	}
    588  1.47  christos #endif
    589  1.55  christos 	if (jobs_invalid)
    590  1.55  christos 		return;
    591  1.55  christos 
    592   1.1       cgd 	for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
    593  1.55  christos 		if (!jp->used)
    594   1.1       cgd 			continue;
    595   1.1       cgd 		if (jp->nprocs == 0) {
    596   1.1       cgd 			freejob(jp);
    597   1.1       cgd 			continue;
    598   1.1       cgd 		}
    599  1.95       kre 		if ((mode & SHOW_CHANGED) && !(jp->flags & JOBCHANGED))
    600   1.1       cgd 			continue;
    601  1.95       kre 		if (silent && (jp->flags & JOBCHANGED)) {
    602  1.95       kre 			jp->flags &= ~JOBCHANGED;
    603  1.47  christos 			continue;
    604  1.47  christos 		}
    605  1.55  christos 		showjob(out, jp, mode);
    606   1.1       cgd 	}
    607   1.1       cgd }
    608   1.1       cgd 
    609   1.1       cgd /*
    610   1.1       cgd  * Mark a job structure as unused.
    611   1.1       cgd  */
    612   1.1       cgd 
    613   1.1       cgd STATIC void
    614  1.55  christos freejob(struct job *jp)
    615  1.55  christos {
    616   1.1       cgd 	INTOFF;
    617  1.41  christos 	if (jp->ps != &jp->ps0) {
    618   1.1       cgd 		ckfree(jp->ps);
    619  1.41  christos 		jp->ps = &jp->ps0;
    620  1.41  christos 	}
    621  1.41  christos 	jp->nprocs = 0;
    622   1.1       cgd 	jp->used = 0;
    623   1.1       cgd #if JOBS
    624  1.55  christos 	set_curjob(jp, 0);
    625   1.1       cgd #endif
    626   1.1       cgd 	INTON;
    627   1.1       cgd }
    628   1.1       cgd 
    629  1.90       kre /*
    630  1.90       kre  * Extract the status of a completed job (for $?)
    631  1.90       kre  */
    632  1.90       kre STATIC int
    633  1.90       kre jobstatus(const struct job *jp, int raw)
    634  1.90       kre {
    635  1.90       kre 	int status = 0;
    636  1.90       kre 	int retval;
    637  1.90       kre 
    638  1.90       kre 	if (pipefail && jp->nprocs) {
    639  1.90       kre 		int i;
    640  1.90       kre 
    641  1.90       kre 		for (i = 0; i < jp->nprocs; i++)
    642  1.90       kre 			if (jp->ps[i].status != 0)
    643  1.90       kre 				status = jp->ps[i].status;
    644  1.90       kre 	} else
    645  1.90       kre 		status = jp->ps[jp->nprocs ? jp->nprocs - 1 : 0].status;
    646  1.90       kre 
    647  1.90       kre 	if (raw)
    648  1.90       kre 		return status;
    649  1.90       kre 
    650  1.90       kre 	if (WIFEXITED(status))
    651  1.90       kre 		retval = WEXITSTATUS(status);
    652  1.90       kre #if JOBS
    653  1.90       kre 	else if (WIFSTOPPED(status))
    654  1.90       kre 		retval = WSTOPSIG(status) + 128;
    655  1.90       kre #endif
    656  1.90       kre 	else {
    657  1.90       kre 		/* XXX: limits number of signals */
    658  1.90       kre 		retval = WTERMSIG(status) + 128;
    659  1.90       kre 	}
    660  1.90       kre 
    661  1.90       kre 	return retval;
    662  1.90       kre }
    663  1.90       kre 
    664   1.1       cgd 
    665   1.1       cgd 
    666   1.1       cgd int
    667  1.55  christos waitcmd(int argc, char **argv)
    668  1.13       cgd {
    669  1.95       kre 	struct job *job, *last;
    670  1.90       kre 	int retval;
    671   1.1       cgd 	struct job *jp;
    672  1.95       kre 	int i;
    673  1.95       kre 	int any = 0;
    674  1.95       kre 	int found;
    675  1.95       kre 	char *pid = NULL, *fpid;
    676  1.95       kre 	char **arg;
    677  1.95       kre 	char idstring[20];
    678  1.95       kre 
    679  1.95       kre 	while ((i = nextopt("np:")) != '\0') {
    680  1.95       kre 		switch (i) {
    681  1.95       kre 		case 'n':
    682  1.95       kre 			any = 1;
    683  1.95       kre 			break;
    684  1.95       kre 		case 'p':
    685  1.95       kre 			if (pid)
    686  1.95       kre 				error("more than one -p unsupported");
    687  1.95       kre 			pid = optionarg;
    688  1.95       kre 			break;
    689  1.95       kre 		}
    690  1.95       kre 	}
    691   1.1       cgd 
    692  1.95       kre 	if (pid != NULL) {
    693  1.95       kre 		if (!validname(pid, '\0', NULL))
    694  1.95       kre 			error("invalid name: -p '%s'", pid);
    695  1.95       kre 		if (unsetvar(pid, 0))
    696  1.95       kre 			error("%s readonly", pid);
    697  1.95       kre 	}
    698  1.55  christos 
    699  1.91       kre 	/*
    700  1.91       kre 	 * If we have forked, and not yet created any new jobs, then
    701  1.91       kre 	 * we have no children, whatever jobtab claims,
    702  1.91       kre 	 * so simply return in that case.
    703  1.91       kre 	 *
    704  1.91       kre 	 * The return code is 127 if we had any pid args (none are found)
    705  1.95       kre 	 * or if we had -n (nothing exited), but 0 for plain old "wait".
    706  1.91       kre 	 */
    707  1.95       kre 	if (jobs_invalid) {
    708  1.95       kre 		CTRACE(DBG_WAIT, ("builtin wait%s%s in child, invalid jobtab\n",
    709  1.95       kre 		    any ? " -n" : "", *argptr ? " pid..." : ""));
    710  1.95       kre 		return (any || *argptr) ? 127 : 0;
    711  1.95       kre 	}
    712  1.91       kre 
    713  1.95       kre 	/* clear stray flags left from previous waitcmd */
    714  1.95       kre 	for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    715  1.95       kre 		jp->flags &= ~JOBWANTED;
    716  1.95       kre 		jp->ref = NULL;
    717   1.1       cgd 	}
    718  1.55  christos 
    719  1.95       kre 	CTRACE(DBG_WAIT,
    720  1.95       kre 	    ("builtin wait%s%s\n", any ? " -n" : "", *argptr ? " pid..." : ""));
    721  1.95       kre 
    722  1.95       kre 	/*
    723  1.95       kre 	 * First, validate the jobnum args, count how many refer to
    724  1.95       kre 	 * (different) running jobs, and if we had -n, and found that one has
    725  1.95       kre 	 * already finished, we return that one.   Otherwise remember
    726  1.95       kre 	 * which ones we are looking for (JOBWANTED).
    727  1.95       kre 	 */
    728  1.95       kre 	found = 0;
    729  1.95       kre 	last = NULL;
    730  1.95       kre 	for (arg = argptr; *arg; arg++) {
    731  1.95       kre 		last = jp = getjob(*arg, 1);
    732  1.95       kre 		if (!jp)
    733  1.55  christos 			continue;
    734  1.95       kre 		if (jp->ref == NULL)
    735  1.95       kre 			jp->ref = *arg;
    736  1.95       kre 		if (any && jp->state == JOBDONE) {
    737  1.95       kre 			/*
    738  1.95       kre 			 * We just want any of them, and this one is
    739  1.95       kre 			 * ready for consumption, bon apetit ...
    740  1.95       kre 			 */
    741  1.95       kre 			retval = jobstatus(jp, 0);
    742  1.95       kre 			if (pid)
    743  1.95       kre 				setvar(pid, *arg, 0);
    744  1.95       kre 			if (!iflag)
    745  1.95       kre 				freejob(jp);
    746  1.95       kre 			CTRACE(DBG_WAIT, ("wait -n found %s already done: %d\n",			    *arg, retval));
    747  1.95       kre 			return retval;
    748  1.55  christos 		}
    749  1.95       kre 		if (!(jp->flags & JOBWANTED)) {
    750  1.95       kre 			/*
    751  1.95       kre 			 * It is possible to list the same job several
    752  1.95       kre 			 * times - the obvious "wait 1 1 1" or
    753  1.95       kre 			 * "wait %% %2 102" where job 2 is current and pid 102
    754  1.95       kre 			 * However many times it is requested, it is found once.
    755  1.95       kre 			 */
    756  1.95       kre 			found++;
    757  1.95       kre 			jp->flags |= JOBWANTED;
    758  1.95       kre 		}
    759  1.95       kre 		job = jp;
    760  1.95       kre 	}
    761  1.95       kre 
    762  1.95       kre 	VTRACE(DBG_WAIT, ("wait %s%s%sfound %d candidates (last %s)\n",
    763  1.95       kre 	    any ? "-n " : "", *argptr ? *argptr : "",
    764  1.95       kre 	    argptr[0] && argptr[1] ? "... " : " ", found,
    765  1.95       kre 	    job ? (job->ref ? job->ref : "<no-arg>") : "none"));
    766  1.95       kre 
    767  1.95       kre 	/*
    768  1.95       kre 	 * If we were given a list of jobnums:
    769  1.95       kre 	 * and none of those exist, then we're done.
    770  1.95       kre 	 */
    771  1.95       kre 	if (*argptr && found == 0)
    772  1.95       kre 		return 127;
    773  1.95       kre 
    774  1.95       kre 	/*
    775  1.95       kre 	 * Otherwise we need to wait for something to complete
    776  1.95       kre 	 * When it does, we check and see if it is one of the
    777  1.95       kre 	 * jobs we're waiting on, and if so, we clean it up.
    778  1.95       kre 	 * If we had -n, then we're done, otherwise we do it all again
    779  1.95       kre 	 * until all we had listed are done, of if there were no
    780  1.95       kre 	 * jobnum args, all are done.
    781  1.95       kre 	 */
    782  1.95       kre 
    783  1.95       kre 	retval = any || *argptr ? 127 : 0;
    784  1.95       kre 	fpid = NULL;
    785  1.95       kre 	for (;;) {
    786  1.95       kre 		VTRACE(DBG_WAIT, ("wait waiting (%d remain): ", found));
    787  1.95       kre 		for (jp = jobtab, i = njobs; --i >= 0; jp++) {
    788  1.95       kre 			if (jp->used && jp->flags & JOBWANTED &&
    789  1.95       kre 			    jp->state == JOBDONE)
    790  1.95       kre 				break;
    791  1.95       kre 			if (jp->used && jp->state == JOBRUNNING)
    792  1.95       kre 				break;
    793  1.95       kre 		}
    794  1.95       kre 		if (i < 0) {
    795  1.95       kre 			CTRACE(DBG_WAIT, ("nothing running (ret: %d) fpid %s\n",
    796  1.95       kre 			    retval, fpid ? fpid : "unset"));
    797  1.95       kre 			if (pid && fpid)
    798  1.95       kre 				setvar(pid, fpid, 0);
    799  1.95       kre 			return retval;
    800  1.95       kre 		}
    801  1.95       kre 		VTRACE(DBG_WAIT, ("found @%d/%d state: %d\n", njobs-i, njobs,
    802  1.95       kre 		    jp->state));
    803  1.95       kre 
    804  1.95       kre 		/*
    805  1.95       kre 		 * There is at least 1 job running, so we can
    806  1.95       kre 		 * safely wait() for something to exit.
    807  1.95       kre 		 */
    808  1.95       kre 		if (jp->state == JOBRUNNING) {
    809  1.95       kre 			job = NULL;
    810  1.95       kre 			if ((i = dowait(WBLOCK|WNOFREE, NULL, &job)) == -1)
    811  1.75  christos 			       return 128 + lastsig();
    812  1.95       kre 
    813  1.95       kre 			/*
    814  1.95       kre 			 * one of the job's processes exited,
    815  1.95       kre 			 * but there are more
    816  1.95       kre 			 */
    817  1.95       kre 			if (job->state == JOBRUNNING)
    818  1.95       kre 				continue;
    819  1.95       kre 		} else
    820  1.95       kre 			job = jp;	/* we want this, and it is done */
    821  1.95       kre 
    822  1.95       kre 		if (job->flags & JOBWANTED || (*argptr == 0 && any)) {
    823  1.95       kre 			int rv;
    824  1.95       kre 
    825  1.95       kre 			job->flags &= ~JOBWANTED;	/* got it */
    826  1.95       kre 			rv = jobstatus(job, 0);
    827  1.95       kre 			VTRACE(DBG_WAIT, (
    828  1.95       kre 			    "wanted %d (%s) done: st=%d", i,
    829  1.95       kre 			    job->ref ? job->ref : "", rv));
    830  1.95       kre 			if (any || job == last) {
    831  1.95       kre 				retval = rv;
    832  1.95       kre 				fpid = job->ref;
    833  1.95       kre 
    834  1.95       kre 				VTRACE(DBG_WAIT, (" save"));
    835  1.95       kre 				if (pid) {
    836  1.95       kre 				   /*
    837  1.95       kre 				    * don't need fpid unless we are going
    838  1.95       kre 				    * to return it.
    839  1.95       kre 				    */
    840  1.95       kre 				   if (fpid == NULL) {
    841  1.95       kre 					/*
    842  1.95       kre 					 * this only happens with "wait -n"
    843  1.95       kre 					 * (that is, no pid args)
    844  1.95       kre 					 */
    845  1.95       kre 					snprintf(idstring, sizeof idstring,
    846  1.95       kre 					    "%d", job->ps[ job->nprocs ?
    847  1.95       kre 						    job->nprocs-1 :
    848  1.95       kre 						    0 ].pid);
    849  1.95       kre 					fpid = idstring;
    850  1.95       kre 				    }
    851  1.95       kre 				    VTRACE(DBG_WAIT, (" (for %s)", fpid));
    852  1.95       kre 				}
    853  1.95       kre 			}
    854  1.95       kre 
    855  1.95       kre 			if (job->state == JOBDONE) {
    856  1.95       kre 				VTRACE(DBG_WAIT, (" free"));
    857  1.95       kre 				freejob(job);
    858  1.95       kre 			}
    859  1.95       kre 
    860  1.95       kre 			if (any || (found > 0 && --found == 0)) {
    861  1.95       kre 				if (pid && fpid)
    862  1.95       kre 					setvar(pid, fpid, 0);
    863  1.95       kre 				VTRACE(DBG_WAIT, (" return %d\n", retval));
    864  1.95       kre 				return retval;
    865  1.95       kre 			}
    866  1.95       kre 			VTRACE(DBG_WAIT, ("\n"));
    867  1.95       kre 			continue;
    868  1.55  christos 		}
    869  1.95       kre 
    870  1.95       kre 		/* this is to handle "wait" (no args) */
    871  1.95       kre 		if (found == 0 && job->state == JOBDONE) {
    872  1.95       kre 			VTRACE(DBG_JOBS|DBG_WAIT, ("Cleanup: %d\n", i));
    873  1.55  christos 			freejob(job);
    874  1.95       kre 		}
    875   1.1       cgd 	}
    876   1.1       cgd }
    877   1.1       cgd 
    878   1.1       cgd 
    879  1.13       cgd int
    880  1.55  christos jobidcmd(int argc, char **argv)
    881  1.13       cgd {
    882   1.1       cgd 	struct job *jp;
    883   1.1       cgd 	int i;
    884  1.92       kre 	int pg = 0, onep = 0, job = 0;
    885  1.92       kre 
    886  1.92       kre 	while ((i = nextopt("gjp"))) {
    887  1.92       kre 		switch (i) {
    888  1.92       kre 		case 'g':	pg = 1;		break;
    889  1.92       kre 		case 'j':	job = 1;	break;
    890  1.92       kre 		case 'p':	onep = 1;	break;
    891  1.92       kre 		}
    892  1.92       kre 	}
    893  1.92       kre 	CTRACE(DBG_JOBS, ("jobidcmd%s%s%s%s %s\n", pg ? " -g" : "",
    894  1.92       kre 	    onep ? " -p" : "", job ? " -j" : "", jobs_invalid ? " [inv]" : "",
    895  1.92       kre 	    *argptr ? *argptr : "<implicit %%>"));
    896  1.92       kre 	if (pg + onep + job > 1)
    897  1.92       kre 		error("-g -j and -p options cannot be combined");
    898  1.92       kre 
    899  1.92       kre 	if (argptr[0] && argptr[1])
    900  1.92       kre 		error("usage: jobid [-g|-p|-r] jobid");
    901   1.1       cgd 
    902  1.55  christos 	jp = getjob(*argptr, 0);
    903  1.92       kre 	if (job) {
    904  1.93    martin 		out1fmt("%%%zu\n", (size_t)(jp - jobtab + 1));
    905  1.92       kre 		return 0;
    906  1.92       kre 	}
    907  1.92       kre 	if (pg) {
    908  1.92       kre 		if (jp->pgrp != 0) {
    909  1.92       kre 			out1fmt("%ld\n", (long)jp->pgrp);
    910  1.92       kre 			return 0;
    911  1.92       kre 		}
    912  1.92       kre 		return 1;
    913  1.92       kre 	}
    914  1.92       kre 	if (onep) {
    915  1.92       kre 		i = jp->nprocs - 1;
    916  1.92       kre 		if (i < 0)
    917  1.92       kre 			return 1;
    918  1.92       kre 		out1fmt("%ld\n", (long)jp->ps[i].pid);
    919  1.92       kre 		return 0;
    920  1.92       kre 	}
    921   1.1       cgd 	for (i = 0 ; i < jp->nprocs ; ) {
    922  1.27  christos 		out1fmt("%ld", (long)jp->ps[i].pid);
    923  1.55  christos 		out1c(++i < jp->nprocs ? ' ' : '\n');
    924   1.1       cgd 	}
    925   1.1       cgd 	return 0;
    926   1.1       cgd }
    927   1.1       cgd 
    928  1.55  christos int
    929  1.55  christos getjobpgrp(const char *name)
    930  1.55  christos {
    931  1.55  christos 	struct job *jp;
    932   1.1       cgd 
    933  1.91       kre 	if (jobs_invalid)
    934  1.91       kre 		error("No such job: %s", name);
    935  1.55  christos 	jp = getjob(name, 1);
    936  1.55  christos 	if (jp == 0)
    937  1.55  christos 		return 0;
    938  1.55  christos 	return -jp->ps[0].pid;
    939  1.55  christos }
    940   1.1       cgd 
    941   1.1       cgd /*
    942   1.1       cgd  * Convert a job name to a job structure.
    943   1.1       cgd  */
    944   1.1       cgd 
    945   1.1       cgd STATIC struct job *
    946  1.55  christos getjob(const char *name, int noerror)
    947  1.55  christos {
    948  1.55  christos 	int jobno = -1;
    949  1.21       tls 	struct job *jp;
    950   1.1       cgd 	int pid;
    951   1.1       cgd 	int i;
    952  1.55  christos 	const char *err_msg = "No such job: %s";
    953  1.91       kre 
    954   1.1       cgd 	if (name == NULL) {
    955   1.1       cgd #if JOBS
    956  1.55  christos 		jobno = curjob;
    957   1.1       cgd #endif
    958  1.55  christos 		err_msg = "No current job";
    959   1.1       cgd 	} else if (name[0] == '%') {
    960  1.55  christos 		if (is_number(name + 1)) {
    961  1.55  christos 			jobno = number(name + 1) - 1;
    962  1.95       kre 		} else if (!name[1] || !name[2]) {
    963  1.55  christos 			switch (name[1]) {
    964   1.1       cgd #if JOBS
    965  1.55  christos 			case 0:
    966  1.55  christos 			case '+':
    967  1.55  christos 			case '%':
    968  1.55  christos 				jobno = curjob;
    969  1.55  christos 				err_msg = "No current job";
    970  1.55  christos 				break;
    971  1.55  christos 			case '-':
    972  1.55  christos 				jobno = curjob;
    973  1.55  christos 				if (jobno != -1)
    974  1.55  christos 					jobno = jobtab[jobno].prev_job;
    975  1.55  christos 				err_msg = "No previous job";
    976  1.55  christos 				break;
    977   1.1       cgd #endif
    978  1.55  christos 			default:
    979  1.55  christos 				goto check_pattern;
    980  1.55  christos 			}
    981   1.1       cgd 		} else {
    982  1.55  christos 			struct job *found;
    983  1.55  christos     check_pattern:
    984  1.55  christos 			found = NULL;
    985   1.1       cgd 			for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
    986  1.55  christos 				if (!jp->used || jp->nprocs <= 0)
    987  1.55  christos 					continue;
    988  1.55  christos 				if ((name[1] == '?'
    989  1.55  christos 					&& strstr(jp->ps[0].cmd, name + 2))
    990  1.55  christos 				    || prefix(name + 1, jp->ps[0].cmd)) {
    991  1.55  christos 					if (found) {
    992  1.55  christos 						err_msg = "%s: ambiguous";
    993  1.55  christos 						found = 0;
    994  1.55  christos 						break;
    995  1.55  christos 					}
    996   1.1       cgd 					found = jp;
    997   1.1       cgd 				}
    998   1.1       cgd 			}
    999   1.1       cgd 			if (found)
   1000   1.1       cgd 				return found;
   1001   1.1       cgd 		}
   1002  1.55  christos 
   1003   1.1       cgd 	} else if (is_number(name)) {
   1004   1.1       cgd 		pid = number(name);
   1005   1.1       cgd 		for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
   1006   1.1       cgd 			if (jp->used && jp->nprocs > 0
   1007   1.1       cgd 			 && jp->ps[jp->nprocs - 1].pid == pid)
   1008   1.1       cgd 				return jp;
   1009   1.1       cgd 		}
   1010   1.1       cgd 	}
   1011  1.55  christos 
   1012  1.91       kre 	if (jobno >= 0 && jobno < njobs) {
   1013  1.55  christos 		jp = jobtab + jobno;
   1014  1.55  christos 		if (jp->used)
   1015  1.55  christos 			return jp;
   1016  1.55  christos 	}
   1017  1.55  christos 	if (!noerror)
   1018  1.55  christos 		error(err_msg, name);
   1019  1.55  christos 	return 0;
   1020   1.1       cgd }
   1021   1.1       cgd 
   1022   1.1       cgd 
   1023   1.1       cgd 
   1024   1.1       cgd /*
   1025   1.1       cgd  * Return a new job structure,
   1026   1.1       cgd  */
   1027   1.1       cgd 
   1028   1.1       cgd struct job *
   1029  1.55  christos makejob(union node *node, int nprocs)
   1030  1.13       cgd {
   1031   1.1       cgd 	int i;
   1032   1.1       cgd 	struct job *jp;
   1033   1.1       cgd 
   1034  1.55  christos 	if (jobs_invalid) {
   1035  1.55  christos 		for (i = njobs, jp = jobtab ; --i >= 0 ; jp++) {
   1036  1.55  christos 			if (jp->used)
   1037  1.55  christos 				freejob(jp);
   1038  1.55  christos 		}
   1039  1.55  christos 		jobs_invalid = 0;
   1040  1.55  christos 	}
   1041  1.55  christos 
   1042   1.1       cgd 	for (i = njobs, jp = jobtab ; ; jp++) {
   1043   1.1       cgd 		if (--i < 0) {
   1044   1.1       cgd 			INTOFF;
   1045   1.1       cgd 			if (njobs == 0) {
   1046   1.1       cgd 				jobtab = ckmalloc(4 * sizeof jobtab[0]);
   1047   1.1       cgd 			} else {
   1048   1.1       cgd 				jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
   1049  1.12   mycroft 				memcpy(jp, jobtab, njobs * sizeof jp[0]);
   1050  1.17        pk 				/* Relocate `ps' pointers */
   1051  1.17        pk 				for (i = 0; i < njobs; i++)
   1052  1.17        pk 					if (jp[i].ps == &jobtab[i].ps0)
   1053  1.17        pk 						jp[i].ps = &jp[i].ps0;
   1054   1.1       cgd 				ckfree(jobtab);
   1055   1.1       cgd 				jobtab = jp;
   1056   1.1       cgd 			}
   1057   1.1       cgd 			jp = jobtab + njobs;
   1058  1.97  christos 			for (i = 4 ; --i >= 0 ; njobs++) {
   1059  1.97  christos 				jobtab[njobs].used = 0;
   1060  1.97  christos 				jobtab[njobs].prev_job = -1;
   1061  1.97  christos 			}
   1062   1.1       cgd 			INTON;
   1063   1.1       cgd 			break;
   1064   1.1       cgd 		}
   1065   1.1       cgd 		if (jp->used == 0)
   1066   1.1       cgd 			break;
   1067   1.1       cgd 	}
   1068   1.1       cgd 	INTOFF;
   1069  1.55  christos 	jp->state = JOBRUNNING;
   1070   1.1       cgd 	jp->used = 1;
   1071  1.95       kre 	jp->flags = 0;
   1072   1.1       cgd 	jp->nprocs = 0;
   1073  1.92       kre 	jp->pgrp = 0;
   1074   1.1       cgd #if JOBS
   1075   1.1       cgd 	jp->jobctl = jobctl;
   1076  1.55  christos 	set_curjob(jp, 1);
   1077   1.1       cgd #endif
   1078   1.1       cgd 	if (nprocs > 1) {
   1079   1.1       cgd 		jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
   1080   1.1       cgd 	} else {
   1081   1.1       cgd 		jp->ps = &jp->ps0;
   1082   1.1       cgd 	}
   1083   1.1       cgd 	INTON;
   1084  1.87       kre 	VTRACE(DBG_JOBS, ("makejob(0x%lx, %d) returns %%%d\n",
   1085  1.87       kre 	    (long)node, nprocs, jp - jobtab + 1));
   1086   1.1       cgd 	return jp;
   1087  1.19  christos }
   1088   1.1       cgd 
   1089   1.1       cgd 
   1090   1.1       cgd /*
   1091  1.37     lukem  * Fork off a subshell.  If we are doing job control, give the subshell its
   1092   1.1       cgd  * own process group.  Jp is a job structure that the job is to be added to.
   1093   1.1       cgd  * N is the command that will be evaluated by the child.  Both jp and n may
   1094   1.1       cgd  * be NULL.  The mode parameter can be one of the following:
   1095   1.1       cgd  *	FORK_FG - Fork off a foreground process.
   1096   1.1       cgd  *	FORK_BG - Fork off a background process.
   1097   1.1       cgd  *	FORK_NOJOB - Like FORK_FG, but don't give the process its own
   1098   1.1       cgd  *		     process group even if job control is on.
   1099   1.1       cgd  *
   1100   1.1       cgd  * When job control is turned off, background processes have their standard
   1101   1.1       cgd  * input redirected to /dev/null (except for the second and later processes
   1102   1.1       cgd  * in a pipeline).
   1103   1.1       cgd  */
   1104   1.1       cgd 
   1105   1.1       cgd int
   1106  1.55  christos forkshell(struct job *jp, union node *n, int mode)
   1107  1.13       cgd {
   1108  1.72  christos 	pid_t pid;
   1109  1.72  christos 	int serrno;
   1110   1.1       cgd 
   1111  1.87       kre 	CTRACE(DBG_JOBS, ("forkshell(%%%d, %p, %d) called\n",
   1112  1.87       kre 	    jp - jobtab, n, mode));
   1113  1.87       kre 
   1114  1.47  christos 	switch ((pid = fork())) {
   1115  1.47  christos 	case -1:
   1116  1.72  christos 		serrno = errno;
   1117  1.87       kre 		VTRACE(DBG_JOBS, ("Fork failed, errno=%d\n", serrno));
   1118   1.1       cgd 		INTON;
   1119  1.72  christos 		error("Cannot fork (%s)", strerror(serrno));
   1120  1.47  christos 		break;
   1121  1.47  christos 	case 0:
   1122  1.85       kre 		SHELL_FORKED();
   1123  1.51  christos 		forkchild(jp, n, mode, 0);
   1124  1.47  christos 		return 0;
   1125  1.47  christos 	default:
   1126  1.51  christos 		return forkparent(jp, n, mode, pid);
   1127   1.1       cgd 	}
   1128  1.47  christos }
   1129  1.47  christos 
   1130  1.47  christos int
   1131  1.55  christos forkparent(struct job *jp, union node *n, int mode, pid_t pid)
   1132  1.47  christos {
   1133  1.53   mycroft 	int pgrp;
   1134   1.1       cgd 
   1135  1.53   mycroft 	if (rootshell && mode != FORK_NOJOB && mflag) {
   1136  1.53   mycroft 		if (jp == NULL || jp->nprocs == 0)
   1137  1.53   mycroft 			pgrp = pid;
   1138  1.53   mycroft 		else
   1139  1.53   mycroft 			pgrp = jp->ps[0].pid;
   1140  1.92       kre 		jp->pgrp = pgrp;
   1141  1.53   mycroft 		/* This can fail because we are doing it in the child also */
   1142  1.53   mycroft 		(void)setpgid(pid, pgrp);
   1143  1.53   mycroft 	}
   1144   1.1       cgd 	if (mode == FORK_BG)
   1145   1.1       cgd 		backgndpid = pid;		/* set $! */
   1146   1.1       cgd 	if (jp) {
   1147   1.1       cgd 		struct procstat *ps = &jp->ps[jp->nprocs++];
   1148   1.1       cgd 		ps->pid = pid;
   1149   1.1       cgd 		ps->status = -1;
   1150  1.55  christos 		ps->cmd[0] = 0;
   1151  1.55  christos 		if (/* iflag && rootshell && */ n)
   1152  1.55  christos 			commandtext(ps, n);
   1153   1.1       cgd 	}
   1154  1.89       kre 	CTRACE(DBG_JOBS, ("In parent shell: child = %d (mode %d)\n",pid,mode));
   1155   1.1       cgd 	return pid;
   1156   1.1       cgd }
   1157   1.1       cgd 
   1158  1.47  christos void
   1159  1.55  christos forkchild(struct job *jp, union node *n, int mode, int vforked)
   1160  1.47  christos {
   1161  1.47  christos 	int wasroot;
   1162  1.47  christos 	int pgrp;
   1163  1.47  christos 	const char *devnull = _PATH_DEVNULL;
   1164  1.47  christos 	const char *nullerr = "Can't open %s";
   1165  1.47  christos 
   1166  1.51  christos 	wasroot = rootshell;
   1167  1.91       kre 	CTRACE(DBG_JOBS, ("Child shell %d %sforked from %d (mode %d)\n",
   1168  1.91       kre 	    getpid(), vforked?"v":"", getppid(), mode));
   1169  1.55  christos 	if (!vforked)
   1170  1.51  christos 		rootshell = 0;
   1171  1.55  christos 
   1172  1.47  christos 	closescript(vforked);
   1173  1.47  christos 	clear_traps(vforked);
   1174  1.47  christos #if JOBS
   1175  1.47  christos 	if (!vforked)
   1176  1.47  christos 		jobctl = 0;		/* do job control only in root shell */
   1177  1.47  christos 	if (wasroot && mode != FORK_NOJOB && mflag) {
   1178  1.47  christos 		if (jp == NULL || jp->nprocs == 0)
   1179  1.47  christos 			pgrp = getpid();
   1180  1.47  christos 		else
   1181  1.47  christos 			pgrp = jp->ps[0].pid;
   1182  1.53   mycroft 		/* This can fail because we are doing it in the parent also */
   1183  1.53   mycroft 		(void)setpgid(0, pgrp);
   1184  1.47  christos 		if (mode == FORK_FG) {
   1185  1.47  christos 			if (tcsetpgrp(ttyfd, pgrp) == -1)
   1186  1.47  christos 				error("Cannot set tty process group (%s) at %d",
   1187  1.47  christos 				    strerror(errno), __LINE__);
   1188  1.47  christos 		}
   1189  1.47  christos 		setsignal(SIGTSTP, vforked);
   1190  1.47  christos 		setsignal(SIGTTOU, vforked);
   1191  1.47  christos 	} else if (mode == FORK_BG) {
   1192  1.47  christos 		ignoresig(SIGINT, vforked);
   1193  1.47  christos 		ignoresig(SIGQUIT, vforked);
   1194  1.47  christos 		if ((jp == NULL || jp->nprocs == 0) &&
   1195  1.47  christos 		    ! fd0_redirected_p ()) {
   1196  1.47  christos 			close(0);
   1197  1.47  christos 			if (open(devnull, O_RDONLY) != 0)
   1198  1.47  christos 				error(nullerr, devnull);
   1199  1.47  christos 		}
   1200  1.47  christos 	}
   1201  1.47  christos #else
   1202  1.47  christos 	if (mode == FORK_BG) {
   1203  1.47  christos 		ignoresig(SIGINT, vforked);
   1204  1.47  christos 		ignoresig(SIGQUIT, vforked);
   1205  1.47  christos 		if ((jp == NULL || jp->nprocs == 0) &&
   1206  1.47  christos 		    ! fd0_redirected_p ()) {
   1207  1.47  christos 			close(0);
   1208  1.47  christos 			if (open(devnull, O_RDONLY) != 0)
   1209  1.47  christos 				error(nullerr, devnull);
   1210  1.47  christos 		}
   1211  1.47  christos 	}
   1212  1.47  christos #endif
   1213  1.47  christos 	if (wasroot && iflag) {
   1214  1.47  christos 		setsignal(SIGINT, vforked);
   1215  1.47  christos 		setsignal(SIGQUIT, vforked);
   1216  1.47  christos 		setsignal(SIGTERM, vforked);
   1217  1.47  christos 	}
   1218  1.55  christos 
   1219  1.55  christos 	if (!vforked)
   1220  1.55  christos 		jobs_invalid = 1;
   1221  1.47  christos }
   1222  1.47  christos 
   1223   1.1       cgd /*
   1224   1.1       cgd  * Wait for job to finish.
   1225   1.1       cgd  *
   1226   1.1       cgd  * Under job control we have the problem that while a child process is
   1227   1.1       cgd  * running interrupts generated by the user are sent to the child but not
   1228   1.1       cgd  * to the shell.  This means that an infinite loop started by an inter-
   1229   1.1       cgd  * active user may be hard to kill.  With job control turned off, an
   1230   1.1       cgd  * interactive user may place an interactive program inside a loop.  If
   1231   1.1       cgd  * the interactive program catches interrupts, the user doesn't want
   1232   1.1       cgd  * these interrupts to also abort the loop.  The approach we take here
   1233   1.1       cgd  * is to have the shell ignore interrupt signals while waiting for a
   1234   1.1       cgd  * forground process to terminate, and then send itself an interrupt
   1235   1.1       cgd  * signal if the child process was terminated by an interrupt signal.
   1236   1.1       cgd  * Unfortunately, some programs want to do a bit of cleanup and then
   1237   1.1       cgd  * exit on interrupt; unless these processes terminate themselves by
   1238   1.1       cgd  * sending a signal to themselves (instead of calling exit) they will
   1239   1.1       cgd  * confuse this approach.
   1240   1.1       cgd  */
   1241   1.1       cgd 
   1242   1.1       cgd int
   1243  1.55  christos waitforjob(struct job *jp)
   1244  1.55  christos {
   1245   1.1       cgd #if JOBS
   1246  1.10       jtc 	int mypgrp = getpgrp();
   1247   1.1       cgd #endif
   1248   1.1       cgd 	int status;
   1249   1.1       cgd 	int st;
   1250   1.1       cgd 
   1251   1.1       cgd 	INTOFF;
   1252  1.87       kre 	VTRACE(DBG_JOBS, ("waitforjob(%%%d) called\n", jp - jobtab + 1));
   1253  1.55  christos 	while (jp->state == JOBRUNNING) {
   1254  1.95       kre 		dowait(WBLOCK, jp, NULL);
   1255   1.1       cgd 	}
   1256   1.1       cgd #if JOBS
   1257   1.1       cgd 	if (jp->jobctl) {
   1258  1.47  christos 		if (tcsetpgrp(ttyfd, mypgrp) == -1)
   1259  1.47  christos 			error("Cannot set tty process group (%s) at %d",
   1260  1.47  christos 			    strerror(errno), __LINE__);
   1261   1.1       cgd 	}
   1262  1.55  christos 	if (jp->state == JOBSTOPPED && curjob != jp - jobtab)
   1263  1.55  christos 		set_curjob(jp, 2);
   1264   1.1       cgd #endif
   1265  1.90       kre 	status = jobstatus(jp, 1);
   1266  1.90       kre 
   1267   1.1       cgd 	/* convert to 8 bits */
   1268  1.23  christos 	if (WIFEXITED(status))
   1269  1.23  christos 		st = WEXITSTATUS(status);
   1270   1.1       cgd #if JOBS
   1271  1.23  christos 	else if (WIFSTOPPED(status))
   1272  1.23  christos 		st = WSTOPSIG(status) + 128;
   1273   1.1       cgd #endif
   1274   1.1       cgd 	else
   1275  1.23  christos 		st = WTERMSIG(status) + 128;
   1276  1.87       kre 
   1277  1.87       kre 	VTRACE(DBG_JOBS, ("waitforjob: job %d, nproc %d, status %d, st %x\n",
   1278  1.87       kre 		jp - jobtab + 1, jp->nprocs, status, st));
   1279  1.32   mycroft #if JOBS
   1280  1.32   mycroft 	if (jp->jobctl) {
   1281  1.32   mycroft 		/*
   1282  1.32   mycroft 		 * This is truly gross.
   1283  1.32   mycroft 		 * If we're doing job control, then we did a TIOCSPGRP which
   1284  1.32   mycroft 		 * caused us (the shell) to no longer be in the controlling
   1285  1.32   mycroft 		 * session -- so we wouldn't have seen any ^C/SIGINT.  So, we
   1286  1.32   mycroft 		 * intuit from the subprocess exit status whether a SIGINT
   1287  1.40       wiz 		 * occurred, and if so interrupt ourselves.  Yuck.  - mycroft
   1288  1.32   mycroft 		 */
   1289  1.32   mycroft 		if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
   1290  1.32   mycroft 			raise(SIGINT);
   1291  1.32   mycroft 	}
   1292  1.32   mycroft #endif
   1293   1.1       cgd 	if (! JOBS || jp->state == JOBDONE)
   1294   1.1       cgd 		freejob(jp);
   1295   1.1       cgd 	INTON;
   1296   1.1       cgd 	return st;
   1297   1.1       cgd }
   1298   1.1       cgd 
   1299   1.1       cgd 
   1300   1.1       cgd 
   1301   1.1       cgd /*
   1302   1.1       cgd  * Wait for a process to terminate.
   1303   1.1       cgd  */
   1304   1.1       cgd 
   1305   1.1       cgd STATIC int
   1306  1.95       kre dowait(int flags, struct job *job, struct job **changed)
   1307  1.13       cgd {
   1308   1.1       cgd 	int pid;
   1309   1.1       cgd 	int status;
   1310   1.1       cgd 	struct procstat *sp;
   1311   1.1       cgd 	struct job *jp;
   1312   1.1       cgd 	struct job *thisjob;
   1313   1.1       cgd 	int done;
   1314   1.1       cgd 	int stopped;
   1315   1.1       cgd 
   1316  1.87       kre 	VTRACE(DBG_JOBS|DBG_PROCS, ("dowait(%x) called\n", flags));
   1317  1.95       kre 
   1318  1.95       kre 	if (changed != NULL)
   1319  1.95       kre 		*changed = NULL;
   1320  1.95       kre 
   1321   1.1       cgd 	do {
   1322  1.68  christos 		pid = waitproc(flags & WBLOCK, job, &status);
   1323  1.87       kre 		VTRACE(DBG_JOBS|DBG_PROCS, ("wait returns pid %d, status %#x\n",
   1324  1.87       kre 		    pid, status));
   1325  1.74  christos 	} while (pid == -1 && errno == EINTR && pendingsigs == 0);
   1326   1.1       cgd 	if (pid <= 0)
   1327   1.1       cgd 		return pid;
   1328   1.1       cgd 	INTOFF;
   1329   1.1       cgd 	thisjob = NULL;
   1330   1.1       cgd 	for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
   1331   1.1       cgd 		if (jp->used) {
   1332   1.1       cgd 			done = 1;
   1333   1.1       cgd 			stopped = 1;
   1334   1.1       cgd 			for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
   1335   1.1       cgd 				if (sp->pid == -1)
   1336   1.1       cgd 					continue;
   1337  1.91       kre 				if (sp->pid == pid &&
   1338  1.91       kre 				  (sp->status==-1 || WIFSTOPPED(sp->status))) {
   1339  1.87       kre 					VTRACE(DBG_JOBS | DBG_PROCS,
   1340  1.87       kre 			("Job %d: changing status of proc %d from %#x to %#x\n",
   1341  1.87       kre 						jp - jobtab + 1, pid,
   1342  1.87       kre 						sp->status, status));
   1343  1.91       kre 					if (WIFCONTINUED(status)) {
   1344  1.91       kre 						if (sp->status != -1)
   1345  1.95       kre 							jp->flags |= JOBCHANGED;
   1346  1.91       kre 						sp->status = -1;
   1347  1.91       kre 						jp->state = 0;
   1348  1.91       kre 					} else
   1349  1.91       kre 						sp->status = status;
   1350   1.1       cgd 					thisjob = jp;
   1351  1.95       kre 					if (changed != NULL)
   1352  1.95       kre 						*changed = jp;
   1353   1.1       cgd 				}
   1354   1.1       cgd 				if (sp->status == -1)
   1355   1.1       cgd 					stopped = 0;
   1356  1.23  christos 				else if (WIFSTOPPED(sp->status))
   1357   1.1       cgd 					done = 0;
   1358   1.1       cgd 			}
   1359   1.1       cgd 			if (stopped) {		/* stopped or done */
   1360  1.55  christos 				int state = done ? JOBDONE : JOBSTOPPED;
   1361  1.91       kre 
   1362   1.1       cgd 				if (jp->state != state) {
   1363  1.87       kre 					VTRACE(DBG_JOBS,
   1364  1.87       kre 				("Job %d: changing state from %d to %d\n",
   1365  1.87       kre 					    jp - jobtab + 1, jp->state, state));
   1366   1.1       cgd 					jp->state = state;
   1367   1.1       cgd #if JOBS
   1368  1.55  christos 					if (done)
   1369  1.55  christos 						set_curjob(jp, 0);
   1370   1.1       cgd #endif
   1371   1.1       cgd 				}
   1372   1.1       cgd 			}
   1373   1.1       cgd 		}
   1374   1.1       cgd 	}
   1375  1.23  christos 
   1376  1.95       kre 	if (thisjob &&
   1377  1.95       kre 	    (thisjob->state != JOBRUNNING || thisjob->flags & JOBCHANGED)) {
   1378  1.55  christos 		int mode = 0;
   1379  1.91       kre 
   1380  1.55  christos 		if (!rootshell || !iflag)
   1381  1.55  christos 			mode = SHOW_SIGNALLED;
   1382  1.68  christos 		if ((job == thisjob && (flags & WNOFREE) == 0) ||
   1383  1.91       kre 		    job != thisjob)
   1384  1.55  christos 			mode = SHOW_SIGNALLED | SHOW_NO_FREE;
   1385  1.91       kre 		if (mode && (flags & WSILENT) == 0)
   1386  1.55  christos 			showjob(out2, thisjob, mode);
   1387  1.55  christos 		else {
   1388  1.87       kre 			VTRACE(DBG_JOBS,
   1389  1.87       kre 			    ("Not printing status, rootshell=%d, job=%p\n",
   1390  1.87       kre 			    rootshell, job));
   1391  1.95       kre 			thisjob->flags |= JOBCHANGED;
   1392   1.1       cgd 		}
   1393   1.1       cgd 	}
   1394  1.55  christos 
   1395  1.47  christos 	INTON;
   1396   1.1       cgd 	return pid;
   1397   1.1       cgd }
   1398   1.1       cgd 
   1399   1.1       cgd 
   1400   1.1       cgd 
   1401   1.1       cgd /*
   1402   1.1       cgd  * Do a wait system call.  If job control is compiled in, we accept
   1403   1.1       cgd  * stopped processes.  If block is zero, we return a value of zero
   1404   1.1       cgd  * rather than blocking.
   1405   1.1       cgd  *
   1406   1.1       cgd  * System V doesn't have a non-blocking wait system call.  It does
   1407  1.65       snj  * have a SIGCLD signal that is sent to a process when one of its
   1408   1.1       cgd  * children dies.  The obvious way to use SIGCLD would be to install
   1409   1.1       cgd  * a handler for SIGCLD which simply bumped a counter when a SIGCLD
   1410   1.1       cgd  * was received, and have waitproc bump another counter when it got
   1411   1.1       cgd  * the status of a process.  Waitproc would then know that a wait
   1412   1.1       cgd  * system call would not block if the two counters were different.
   1413   1.1       cgd  * This approach doesn't work because if a process has children that
   1414   1.1       cgd  * have not been waited for, System V will send it a SIGCLD when it
   1415   1.1       cgd  * installs a signal handler for SIGCLD.  What this means is that when
   1416   1.1       cgd  * a child exits, the shell will be sent SIGCLD signals continuously
   1417   1.1       cgd  * until is runs out of stack space, unless it does a wait call before
   1418   1.1       cgd  * restoring the signal handler.  The code below takes advantage of
   1419   1.1       cgd  * this (mis)feature by installing a signal handler for SIGCLD and
   1420   1.1       cgd  * then checking to see whether it was called.  If there are any
   1421   1.1       cgd  * children to be waited for, it will be.
   1422   1.1       cgd  *
   1423   1.1       cgd  * If neither SYSV nor BSD is defined, we don't implement nonblocking
   1424   1.1       cgd  * waits at all.  In this case, the user will not be informed when
   1425   1.1       cgd  * a background process until the next time she runs a real program
   1426   1.1       cgd  * (as opposed to running a builtin command or just typing return),
   1427   1.1       cgd  * and the jobs command may give out of date information.
   1428   1.1       cgd  */
   1429   1.1       cgd 
   1430   1.1       cgd #ifdef SYSV
   1431   1.1       cgd STATIC int gotsigchild;
   1432   1.1       cgd 
   1433   1.1       cgd STATIC int onsigchild() {
   1434   1.1       cgd 	gotsigchild = 1;
   1435   1.1       cgd }
   1436   1.1       cgd #endif
   1437   1.1       cgd 
   1438   1.1       cgd 
   1439   1.1       cgd STATIC int
   1440  1.55  christos waitproc(int block, struct job *jp, int *status)
   1441  1.13       cgd {
   1442   1.1       cgd #ifdef BSD
   1443  1.38  christos 	int flags = 0;
   1444   1.1       cgd 
   1445   1.1       cgd #if JOBS
   1446  1.91       kre 	if (mflag || (jp != NULL && jp->jobctl))
   1447  1.91       kre 		flags |= WUNTRACED | WCONTINUED;
   1448   1.1       cgd #endif
   1449   1.1       cgd 	if (block == 0)
   1450   1.1       cgd 		flags |= WNOHANG;
   1451  1.91       kre 	VTRACE(DBG_WAIT, ("waitproc: doing waitpid(flags=%#x)\n", flags));
   1452  1.64        tv 	return waitpid(-1, status, flags);
   1453   1.1       cgd #else
   1454   1.1       cgd #ifdef SYSV
   1455   1.1       cgd 	int (*save)();
   1456   1.1       cgd 
   1457   1.1       cgd 	if (block == 0) {
   1458   1.1       cgd 		gotsigchild = 0;
   1459   1.1       cgd 		save = signal(SIGCLD, onsigchild);
   1460   1.1       cgd 		signal(SIGCLD, save);
   1461   1.1       cgd 		if (gotsigchild == 0)
   1462   1.1       cgd 			return 0;
   1463   1.1       cgd 	}
   1464   1.1       cgd 	return wait(status);
   1465   1.1       cgd #else
   1466   1.1       cgd 	if (block == 0)
   1467   1.1       cgd 		return 0;
   1468   1.1       cgd 	return wait(status);
   1469   1.1       cgd #endif
   1470   1.1       cgd #endif
   1471   1.1       cgd }
   1472   1.1       cgd 
   1473   1.8       jtc /*
   1474   1.8       jtc  * return 1 if there are stopped jobs, otherwise 0
   1475   1.8       jtc  */
   1476   1.8       jtc int job_warning = 0;
   1477   1.8       jtc int
   1478  1.55  christos stoppedjobs(void)
   1479   1.8       jtc {
   1480  1.21       tls 	int jobno;
   1481  1.21       tls 	struct job *jp;
   1482   1.8       jtc 
   1483  1.55  christos 	if (job_warning || jobs_invalid)
   1484   1.8       jtc 		return (0);
   1485   1.8       jtc 	for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
   1486   1.8       jtc 		if (jp->used == 0)
   1487   1.8       jtc 			continue;
   1488   1.8       jtc 		if (jp->state == JOBSTOPPED) {
   1489   1.8       jtc 			out2str("You have stopped jobs.\n");
   1490   1.8       jtc 			job_warning = 2;
   1491   1.8       jtc 			return (1);
   1492   1.8       jtc 		}
   1493   1.8       jtc 	}
   1494   1.1       cgd 
   1495   1.8       jtc 	return (0);
   1496   1.8       jtc }
   1497   1.1       cgd 
   1498   1.1       cgd /*
   1499   1.1       cgd  * Return a string identifying a command (to be printed by the
   1500  1.55  christos  * jobs command).
   1501   1.1       cgd  */
   1502   1.1       cgd 
   1503   1.1       cgd STATIC char *cmdnextc;
   1504   1.1       cgd STATIC int cmdnleft;
   1505   1.1       cgd 
   1506  1.55  christos void
   1507  1.55  christos commandtext(struct procstat *ps, union node *n)
   1508  1.55  christos {
   1509  1.55  christos 	int len;
   1510   1.1       cgd 
   1511  1.55  christos 	cmdnextc = ps->cmd;
   1512  1.99       kre 	if (iflag || mflag || sizeof(ps->cmd) <= 60)
   1513  1.55  christos 		len = sizeof(ps->cmd);
   1514  1.99       kre 	else if (sizeof ps->cmd <= 400)
   1515  1.99       kre 		len = 50;
   1516  1.99       kre 	else if (sizeof ps->cmd <= 800)
   1517  1.99       kre 		len = 80;
   1518  1.55  christos 	else
   1519  1.55  christos 		len = sizeof(ps->cmd) / 10;
   1520  1.55  christos 	cmdnleft = len;
   1521   1.1       cgd 	cmdtxt(n);
   1522  1.55  christos 	if (cmdnleft <= 0) {
   1523  1.55  christos 		char *p = ps->cmd + len - 4;
   1524  1.55  christos 		p[0] = '.';
   1525  1.55  christos 		p[1] = '.';
   1526  1.55  christos 		p[2] = '.';
   1527  1.55  christos 		p[3] = 0;
   1528  1.55  christos 	} else
   1529  1.55  christos 		*cmdnextc = '\0';
   1530  1.87       kre 
   1531  1.87       kre 	VTRACE(DBG_JOBS,
   1532  1.99       kre 	    ("commandtext: ps->cmd %p, end %p, left %d\n\t\"%s\"\n",
   1533  1.87       kre 	    ps->cmd, cmdnextc, cmdnleft, ps->cmd));
   1534   1.1       cgd }
   1535   1.1       cgd 
   1536   1.1       cgd 
   1537   1.1       cgd STATIC void
   1538  1.55  christos cmdtxt(union node *n)
   1539  1.55  christos {
   1540   1.1       cgd 	union node *np;
   1541   1.1       cgd 	struct nodelist *lp;
   1542  1.31  christos 	const char *p;
   1543   1.1       cgd 	int i;
   1544   1.1       cgd 
   1545  1.55  christos 	if (n == NULL || cmdnleft <= 0)
   1546   1.8       jtc 		return;
   1547   1.1       cgd 	switch (n->type) {
   1548   1.1       cgd 	case NSEMI:
   1549   1.1       cgd 		cmdtxt(n->nbinary.ch1);
   1550   1.1       cgd 		cmdputs("; ");
   1551   1.1       cgd 		cmdtxt(n->nbinary.ch2);
   1552   1.1       cgd 		break;
   1553   1.1       cgd 	case NAND:
   1554   1.1       cgd 		cmdtxt(n->nbinary.ch1);
   1555   1.1       cgd 		cmdputs(" && ");
   1556   1.1       cgd 		cmdtxt(n->nbinary.ch2);
   1557   1.1       cgd 		break;
   1558   1.1       cgd 	case NOR:
   1559   1.1       cgd 		cmdtxt(n->nbinary.ch1);
   1560   1.1       cgd 		cmdputs(" || ");
   1561   1.1       cgd 		cmdtxt(n->nbinary.ch2);
   1562   1.1       cgd 		break;
   1563  1.83       kre 	case NDNOT:
   1564  1.83       kre 		cmdputs("! ");
   1565  1.83       kre 		/* FALLTHROUGH */
   1566  1.81       kre 	case NNOT:
   1567  1.81       kre 		cmdputs("! ");
   1568  1.81       kre 		cmdtxt(n->nnot.com);
   1569  1.81       kre 		break;
   1570   1.1       cgd 	case NPIPE:
   1571   1.1       cgd 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
   1572   1.1       cgd 			cmdtxt(lp->n);
   1573   1.1       cgd 			if (lp->next)
   1574   1.1       cgd 				cmdputs(" | ");
   1575   1.1       cgd 		}
   1576  1.79       kre 		if (n->npipe.backgnd)
   1577  1.79       kre 			cmdputs(" &");
   1578   1.1       cgd 		break;
   1579   1.1       cgd 	case NSUBSHELL:
   1580   1.1       cgd 		cmdputs("(");
   1581   1.1       cgd 		cmdtxt(n->nredir.n);
   1582   1.1       cgd 		cmdputs(")");
   1583   1.1       cgd 		break;
   1584   1.1       cgd 	case NREDIR:
   1585   1.1       cgd 	case NBACKGND:
   1586   1.1       cgd 		cmdtxt(n->nredir.n);
   1587   1.1       cgd 		break;
   1588   1.1       cgd 	case NIF:
   1589   1.1       cgd 		cmdputs("if ");
   1590   1.1       cgd 		cmdtxt(n->nif.test);
   1591   1.1       cgd 		cmdputs("; then ");
   1592   1.1       cgd 		cmdtxt(n->nif.ifpart);
   1593  1.55  christos 		if (n->nif.elsepart) {
   1594  1.55  christos 			cmdputs("; else ");
   1595  1.55  christos 			cmdtxt(n->nif.elsepart);
   1596  1.55  christos 		}
   1597  1.55  christos 		cmdputs("; fi");
   1598   1.1       cgd 		break;
   1599   1.1       cgd 	case NWHILE:
   1600   1.1       cgd 		cmdputs("while ");
   1601   1.1       cgd 		goto until;
   1602   1.1       cgd 	case NUNTIL:
   1603   1.1       cgd 		cmdputs("until ");
   1604  1.80       kre  until:
   1605   1.1       cgd 		cmdtxt(n->nbinary.ch1);
   1606   1.1       cgd 		cmdputs("; do ");
   1607   1.1       cgd 		cmdtxt(n->nbinary.ch2);
   1608   1.1       cgd 		cmdputs("; done");
   1609   1.1       cgd 		break;
   1610   1.1       cgd 	case NFOR:
   1611   1.1       cgd 		cmdputs("for ");
   1612   1.1       cgd 		cmdputs(n->nfor.var);
   1613  1.55  christos 		cmdputs(" in ");
   1614  1.55  christos 		cmdlist(n->nfor.args, 1);
   1615  1.55  christos 		cmdputs("; do ");
   1616  1.55  christos 		cmdtxt(n->nfor.body);
   1617  1.55  christos 		cmdputs("; done");
   1618   1.1       cgd 		break;
   1619   1.1       cgd 	case NCASE:
   1620   1.1       cgd 		cmdputs("case ");
   1621   1.1       cgd 		cmdputs(n->ncase.expr->narg.text);
   1622  1.55  christos 		cmdputs(" in ");
   1623  1.55  christos 		for (np = n->ncase.cases; np; np = np->nclist.next) {
   1624  1.55  christos 			cmdtxt(np->nclist.pattern);
   1625  1.55  christos 			cmdputs(") ");
   1626  1.55  christos 			cmdtxt(np->nclist.body);
   1627  1.82       kre 			switch (n->type) {	/* switch (not if) for later */
   1628  1.82       kre 			case NCLISTCONT:
   1629  1.82       kre 				cmdputs(";& ");
   1630  1.82       kre 				break;
   1631  1.82       kre 			default:
   1632  1.82       kre 				cmdputs(";; ");
   1633  1.82       kre 				break;
   1634  1.82       kre 			}
   1635  1.55  christos 		}
   1636  1.55  christos 		cmdputs("esac");
   1637   1.1       cgd 		break;
   1638   1.1       cgd 	case NDEFUN:
   1639   1.1       cgd 		cmdputs(n->narg.text);
   1640  1.55  christos 		cmdputs("() { ... }");
   1641   1.1       cgd 		break;
   1642   1.1       cgd 	case NCMD:
   1643  1.55  christos 		cmdlist(n->ncmd.args, 1);
   1644  1.55  christos 		cmdlist(n->ncmd.redirect, 0);
   1645  1.79       kre 		if (n->ncmd.backgnd)
   1646  1.79       kre 			cmdputs(" &");
   1647   1.1       cgd 		break;
   1648   1.1       cgd 	case NARG:
   1649   1.1       cgd 		cmdputs(n->narg.text);
   1650   1.1       cgd 		break;
   1651   1.1       cgd 	case NTO:
   1652   1.1       cgd 		p = ">";  i = 1;  goto redir;
   1653  1.46  christos 	case NCLOBBER:
   1654  1.46  christos 		p = ">|";  i = 1;  goto redir;
   1655   1.1       cgd 	case NAPPEND:
   1656   1.1       cgd 		p = ">>";  i = 1;  goto redir;
   1657   1.1       cgd 	case NTOFD:
   1658   1.1       cgd 		p = ">&";  i = 1;  goto redir;
   1659   1.1       cgd 	case NFROM:
   1660   1.1       cgd 		p = "<";  i = 0;  goto redir;
   1661   1.1       cgd 	case NFROMFD:
   1662   1.1       cgd 		p = "<&";  i = 0;  goto redir;
   1663  1.29  christos 	case NFROMTO:
   1664  1.29  christos 		p = "<>";  i = 0;  goto redir;
   1665  1.80       kre  redir:
   1666  1.77       kre 		if (n->nfile.fd != i)
   1667  1.77       kre 			cmdputi(n->nfile.fd);
   1668   1.1       cgd 		cmdputs(p);
   1669   1.1       cgd 		if (n->type == NTOFD || n->type == NFROMFD) {
   1670  1.77       kre 			if (n->ndup.dupfd < 0)
   1671  1.77       kre 				cmdputs("-");
   1672  1.77       kre 			else
   1673  1.77       kre 				cmdputi(n->ndup.dupfd);
   1674   1.1       cgd 		} else {
   1675   1.1       cgd 			cmdtxt(n->nfile.fname);
   1676   1.1       cgd 		}
   1677   1.1       cgd 		break;
   1678   1.1       cgd 	case NHERE:
   1679   1.1       cgd 	case NXHERE:
   1680   1.1       cgd 		cmdputs("<<...");
   1681   1.1       cgd 		break;
   1682   1.1       cgd 	default:
   1683   1.1       cgd 		cmdputs("???");
   1684   1.1       cgd 		break;
   1685   1.1       cgd 	}
   1686   1.1       cgd }
   1687   1.1       cgd 
   1688  1.55  christos STATIC void
   1689  1.55  christos cmdlist(union node *np, int sep)
   1690  1.55  christos {
   1691  1.55  christos 	for (; np; np = np->narg.next) {
   1692  1.55  christos 		if (!sep)
   1693  1.55  christos 			cmdputs(" ");
   1694  1.55  christos 		cmdtxt(np);
   1695  1.55  christos 		if (sep && np->narg.next)
   1696  1.55  christos 			cmdputs(" ");
   1697  1.55  christos 	}
   1698  1.55  christos }
   1699   1.1       cgd 
   1700   1.1       cgd 
   1701   1.1       cgd STATIC void
   1702  1.55  christos cmdputs(const char *s)
   1703  1.55  christos {
   1704  1.55  christos 	const char *p, *str = 0;
   1705  1.55  christos 	char c, cc[2] = " ";
   1706  1.55  christos 	char *nextc;
   1707  1.55  christos 	int nleft;
   1708   1.1       cgd 	int subtype = 0;
   1709  1.55  christos 	int quoted = 0;
   1710  1.55  christos 	static char vstype[16][4] = { "", "}", "-", "+", "?", "=",
   1711  1.84       kre 					"#", "##", "%", "%%", "}" };
   1712   1.1       cgd 
   1713   1.1       cgd 	p = s;
   1714  1.55  christos 	nextc = cmdnextc;
   1715  1.55  christos 	nleft = cmdnleft;
   1716  1.55  christos 	while (nleft > 0 && (c = *p++) != 0) {
   1717  1.55  christos 		switch (c) {
   1718  1.86       kre 		case CTLNONL:
   1719  1.86       kre 			c = '\0';
   1720  1.86       kre 			break;
   1721  1.55  christos 		case CTLESC:
   1722  1.55  christos 			c = *p++;
   1723  1.55  christos 			break;
   1724  1.55  christos 		case CTLVAR:
   1725   1.1       cgd 			subtype = *p++;
   1726  1.86       kre 			if (subtype & VSLINENO) {	/* undo LINENO hack */
   1727  1.84       kre 				if ((subtype & VSTYPE) == VSLENGTH)
   1728  1.86       kre 					str = "${#LINENO";	/*}*/
   1729  1.84       kre 				else
   1730  1.86       kre 					str = "${LINENO";	/*}*/
   1731  1.84       kre 				while (is_digit(*p))
   1732  1.84       kre 					p++;
   1733  1.84       kre 			} else if ((subtype & VSTYPE) == VSLENGTH)
   1734  1.86       kre 				str = "${#"; /*}*/
   1735  1.55  christos 			else
   1736  1.86       kre 				str = "${"; /*}*/
   1737  1.55  christos 			if (!(subtype & VSQUOTE) != !(quoted & 1)) {
   1738  1.55  christos 				quoted ^= 1;
   1739  1.55  christos 				c = '"';
   1740  1.84       kre 			} else {
   1741  1.55  christos 				c = *str++;
   1742  1.84       kre 			}
   1743  1.55  christos 			break;
   1744  1.86       kre 		case CTLENDVAR:		/*{*/
   1745  1.84       kre 			c = '}';
   1746  1.84       kre 			if (quoted & 1)
   1747  1.84       kre 				str = "\"";
   1748  1.55  christos 			quoted >>= 1;
   1749   1.1       cgd 			subtype = 0;
   1750  1.55  christos 			break;
   1751  1.55  christos 		case CTLBACKQ:
   1752  1.55  christos 			c = '$';
   1753  1.55  christos 			str = "(...)";
   1754  1.55  christos 			break;
   1755  1.55  christos 		case CTLBACKQ+CTLQUOTE:
   1756  1.55  christos 			c = '"';
   1757  1.55  christos 			str = "$(...)\"";
   1758  1.55  christos 			break;
   1759  1.55  christos 		case CTLARI:
   1760  1.55  christos 			c = '$';
   1761  1.86       kre 			if (*p == ' ')
   1762  1.86       kre 				p++;
   1763  1.86       kre 			str = "((";	/*))*/
   1764  1.55  christos 			break;
   1765  1.86       kre 		case CTLENDARI:		/*((*/
   1766  1.55  christos 			c = ')';
   1767  1.55  christos 			str = ")";
   1768  1.55  christos 			break;
   1769  1.55  christos 		case CTLQUOTEMARK:
   1770  1.55  christos 			quoted ^= 1;
   1771  1.55  christos 			c = '"';
   1772  1.55  christos 			break;
   1773  1.84       kre 		case CTLQUOTEEND:
   1774  1.84       kre 			quoted >>= 1;
   1775  1.84       kre 			c = '"';
   1776  1.84       kre 			break;
   1777  1.55  christos 		case '=':
   1778  1.55  christos 			if (subtype == 0)
   1779  1.55  christos 				break;
   1780  1.55  christos 			str = vstype[subtype & VSTYPE];
   1781  1.55  christos 			if (subtype & VSNUL)
   1782  1.55  christos 				c = ':';
   1783  1.55  christos 			else
   1784  1.86       kre 				c = *str++;		/*{*/
   1785  1.55  christos 			if (c != '}')
   1786  1.55  christos 				quoted <<= 1;
   1787  1.84       kre 			else if (*p == CTLENDVAR)
   1788  1.84       kre 				c = *str++;
   1789  1.84       kre 			subtype = 0;
   1790  1.55  christos 			break;
   1791  1.55  christos 		case '\'':
   1792  1.55  christos 		case '\\':
   1793  1.55  christos 		case '"':
   1794  1.55  christos 		case '$':
   1795  1.55  christos 			/* These can only happen inside quotes */
   1796  1.55  christos 			cc[0] = c;
   1797  1.55  christos 			str = cc;
   1798  1.55  christos 			c = '\\';
   1799  1.55  christos 			break;
   1800  1.55  christos 		default:
   1801   1.1       cgd 			break;
   1802   1.1       cgd 		}
   1803  1.84       kre 		if (c != '\0') do {	/* c == 0 implies nothing in str */
   1804  1.55  christos 			*nextc++ = c;
   1805  1.55  christos 		} while (--nleft > 0 && str && (c = *str++));
   1806  1.55  christos 		str = 0;
   1807  1.55  christos 	}
   1808  1.55  christos 	if ((quoted & 1) && nleft) {
   1809  1.55  christos 		*nextc++ = '"';
   1810  1.55  christos 		nleft--;
   1811   1.1       cgd 	}
   1812  1.55  christos 	cmdnleft = nleft;
   1813  1.55  christos 	cmdnextc = nextc;
   1814   1.1       cgd }
   1815