sh - Sync to FreeBSD d038ee76 part 2/2 (d)
[dragonfly.git] / bin / sh / jobs.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)jobs.c      8.5 (Berkeley) 5/4/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include <sys/ioctl.h>
42 #include <sys/param.h>
43 #include <sys/resource.h>
44 #include <sys/time.h>
45 #include <sys/wait.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <paths.h>
49 #include <signal.h>
50 #include <stddef.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53
54 #include "shell.h"
55 #if JOBS
56 #include <termios.h>
57 #undef CEOF                     /* syntax.h redefines this */
58 #endif
59 #include "redir.h"
60 #include "exec.h"
61 #include "show.h"
62 #include "main.h"
63 #include "parser.h"
64 #include "nodes.h"
65 #include "jobs.h"
66 #include "options.h"
67 #include "trap.h"
68 #include "syntax.h"
69 #include "input.h"
70 #include "output.h"
71 #include "memalloc.h"
72 #include "error.h"
73 #include "mystring.h"
74 #include "var.h"
75 #include "builtins.h"
76
77
78 static struct job *jobtab;      /* array of jobs */
79 static int njobs;               /* size of array */
80 static pid_t backgndpid = -1;   /* pid of last background process */
81 static struct job *bgjob = NULL; /* last background process */
82 #if JOBS
83 static struct job *jobmru;      /* most recently used job list */
84 static pid_t initialpgrp;       /* pgrp of shell on invocation */
85 #endif
86 static int ttyfd = -1;
87
88 /* mode flags for dowait */
89 #define DOWAIT_BLOCK    0x1 /* wait until a child exits */
90 #define DOWAIT_SIG      0x2 /* if DOWAIT_BLOCK, abort on signal */
91 #define DOWAIT_SIG_TRAP 0x4 /* if DOWAIT_SIG, abort on trapped signal only */
92
93 #if JOBS
94 static void restartjob(struct job *);
95 #endif
96 static void freejob(struct job *);
97 static int waitcmdloop(struct job *);
98 static struct job *getjob_nonotfound(const char *);
99 static struct job *getjob(const char *);
100 pid_t killjob(const char *, int);
101 static pid_t dowait(int, struct job *);
102 static void checkzombies(void);
103 static void cmdtxt(union node *);
104 static void cmdputs(const char *);
105 #if JOBS
106 static void setcurjob(struct job *);
107 static void deljob(struct job *);
108 static struct job *getcurjob(struct job *);
109 #endif
110 static void printjobcmd(struct job *);
111 static void showjob(struct job *, int);
112
113
114 /*
115  * Turn job control on and off.
116  */
117
118 static int jobctl;
119
120 #if JOBS
121 static void
122 jobctl_notty(void)
123 {
124         if (ttyfd >= 0) {
125                 close(ttyfd);
126                 ttyfd = -1;
127         }
128         if (!iflag) {
129                 setsignal(SIGTSTP);
130                 setsignal(SIGTTOU);
131                 setsignal(SIGTTIN);
132                 jobctl = 1;
133                 return;
134         }
135         out2fmt_flush("sh: can't access tty; job control turned off\n");
136         mflag = 0;
137 }
138
139 void
140 setjobctl(int on)
141 {
142         int i;
143
144         if (on == jobctl || rootshell == 0)
145                 return;
146         if (on) {
147                 if (ttyfd != -1)
148                         close(ttyfd);
149                 if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC_MAYBE)) < 0) {
150                         i = 0;
151                         while (i <= 2 && !isatty(i))
152                                 i++;
153                         if (i > 2 ||
154                             (ttyfd = fcntl(i, F_DUPFD_CLOEXEC_MAYBE, 10)) < 0) {
155                                 jobctl_notty();
156                                 return;
157                         }
158                 }
159                 if (ttyfd < 10) {
160                         /*
161                          * Keep our TTY file descriptor out of the way of
162                          * the user's redirections.
163                          */
164                         if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC_MAYBE, 10)) < 0) {
165                                 jobctl_notty();
166                                 return;
167                         }
168                         close(ttyfd);
169                         ttyfd = i;
170                 }
171 #if !defined(O_CLOEXEC) || !defined(F_DUPFD_CLOEXEC)
172                 if (fcntl(ttyfd, F_SETFD, FD_CLOEXEC) < 0) {
173                         close(ttyfd);
174                         ttyfd = -1;
175                         goto out;
176                 }
177 #endif
178                 do { /* while we are in the background */
179                         initialpgrp = tcgetpgrp(ttyfd);
180                         if (initialpgrp < 0) {
181 out:                            jobctl_notty();
182                                 return;
183                         }
184                         if (initialpgrp != getpgrp()) {
185                                 if (!iflag) {
186                                         initialpgrp = -1;
187                                         jobctl_notty();
188                                         return;
189                                 }
190                                 kill(0, SIGTTIN);
191                                 continue;
192                         }
193                 } while (0);
194                 setsignal(SIGTSTP);
195                 setsignal(SIGTTOU);
196                 setsignal(SIGTTIN);
197                 setpgid(0, rootpid);
198                 tcsetpgrp(ttyfd, rootpid);
199         } else { /* turning job control off */
200                 setpgid(0, initialpgrp);
201                 if (ttyfd >= 0) {
202                 tcsetpgrp(ttyfd, initialpgrp);
203                 close(ttyfd);
204                 ttyfd = -1;
205                 }
206                 setsignal(SIGTSTP);
207                 setsignal(SIGTTOU);
208                 setsignal(SIGTTIN);
209         }
210         jobctl = on;
211 }
212 #endif
213
214
215 #if JOBS
216 int
217 fgcmd(int argc __unused, char **argv __unused)
218 {
219         struct job *jp;
220         pid_t pgrp;
221         int status;
222
223         nextopt("");
224         jp = getjob(*argptr);
225         if (jp->jobctl == 0)
226                 error("job not created under job control");
227         printjobcmd(jp);
228         flushout(&output);
229         pgrp = jp->ps[0].pid;
230         if (ttyfd >= 0)
231         tcsetpgrp(ttyfd, pgrp);
232         restartjob(jp);
233         jp->foreground = 1;
234         INTOFF;
235         status = waitforjob(jp, (int *)NULL);
236         INTON;
237         return status;
238 }
239
240
241 int
242 bgcmd(int argc __unused, char **argv __unused)
243 {
244         struct job *jp;
245
246         nextopt("");
247         do {
248                 jp = getjob(*argptr);
249                 if (jp->jobctl == 0)
250                         error("job not created under job control");
251                 if (jp->state == JOBDONE)
252                         continue;
253                 restartjob(jp);
254                 jp->foreground = 0;
255                 out1fmt("[%td] ", jp - jobtab + 1);
256                 printjobcmd(jp);
257         } while (*argptr != NULL && *++argptr != NULL);
258         return 0;
259 }
260
261
262 static void
263 restartjob(struct job *jp)
264 {
265         struct procstat *ps;
266         int i;
267
268         if (jp->state == JOBDONE)
269                 return;
270         setcurjob(jp);
271         INTOFF;
272         kill(-jp->ps[0].pid, SIGCONT);
273         for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
274                 if (WIFSTOPPED(ps->status)) {
275                         ps->status = -1;
276                         jp->state = 0;
277                 }
278         }
279         INTON;
280 }
281 #endif
282
283
284 int
285 jobscmd(int argc __unused, char *argv[] __unused)
286 {
287         char *id;
288         int ch, mode;
289
290         mode = SHOWJOBS_DEFAULT;
291         while ((ch = nextopt("lps")) != '\0') {
292                 switch (ch) {
293                 case 'l':
294                         mode = SHOWJOBS_VERBOSE;
295                         break;
296                 case 'p':
297                         mode = SHOWJOBS_PGIDS;
298                         break;
299                 case 's':
300                         mode = SHOWJOBS_PIDS;
301                         break;
302                 }
303         }
304
305         if (*argptr == NULL)
306                 showjobs(0, mode);
307         else
308                 while ((id = *argptr++) != NULL)
309                         showjob(getjob(id), mode);
310
311         return (0);
312 }
313
314 static void
315 printjobcmd(struct job *jp)
316 {
317         struct procstat *ps;
318         int i;
319
320         for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
321                 out1str(ps->cmd);
322                 if (i > 0)
323                         out1str(" | ");
324         }
325         out1c('\n');
326 }
327
328 static void
329 showjob(struct job *jp, int mode)
330 {
331         char s[64];
332         char statestr[64];
333         const char *sigstr;
334         struct procstat *ps;
335         struct job *j;
336         int col, curr, i, jobno, prev, procno;
337         char c;
338
339         procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
340         jobno = jp - jobtab + 1;
341         curr = prev = 0;
342 #if JOBS
343         if ((j = getcurjob(NULL)) != NULL) {
344                 curr = j - jobtab + 1;
345                 if ((j = getcurjob(j)) != NULL)
346                         prev = j - jobtab + 1;
347         }
348 #endif
349         ps = jp->ps + jp->nprocs - 1;
350         if (jp->state == 0) {
351                 strcpy(statestr, "Running");
352 #if JOBS
353         } else if (jp->state == JOBSTOPPED) {
354                 while (!WIFSTOPPED(ps->status) && ps > jp->ps)
355                         ps--;
356                 if (WIFSTOPPED(ps->status))
357                         i = WSTOPSIG(ps->status);
358                 else
359                         i = -1;
360                 sigstr = strsignal(i);
361                 if (sigstr != NULL)
362                         strcpy(statestr, sigstr);
363                 else
364                         strcpy(statestr, "Suspended");
365 #endif
366         } else if (WIFEXITED(ps->status)) {
367                 if (WEXITSTATUS(ps->status) == 0)
368                         strcpy(statestr, "Done");
369                 else
370                         fmtstr(statestr, 64, "Done(%d)",
371                             WEXITSTATUS(ps->status));
372         } else {
373                 i = WTERMSIG(ps->status);
374                 sigstr = strsignal(i);
375                 if (sigstr != NULL)
376                         strcpy(statestr, sigstr);
377                 else
378                         strcpy(statestr, "Unknown signal");
379                 if (WCOREDUMP(ps->status))
380                         strcat(statestr, " (core dumped)");
381         }
382
383         for (ps = jp->ps ; procno > 0 ; ps++, procno--) { /* for each process */
384                 if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
385                         out1fmt("%d\n", (int)ps->pid);
386                         continue;
387                 }
388                 if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
389                         continue;
390                 if (jobno == curr && ps == jp->ps)
391                         c = '+';
392                 else if (jobno == prev && ps == jp->ps)
393                         c = '-';
394                 else
395                         c = ' ';
396                 if (ps == jp->ps)
397                         fmtstr(s, 64, "[%d] %c ", jobno, c);
398                 else
399                         fmtstr(s, 64, "    %c ", c);
400                 out1str(s);
401                 col = strlen(s);
402                 if (mode == SHOWJOBS_VERBOSE) {
403                         fmtstr(s, 64, "%d ", (int)ps->pid);
404                         out1str(s);
405                         col += strlen(s);
406                 }
407                 if (ps == jp->ps) {
408                         out1str(statestr);
409                         col += strlen(statestr);
410                 }
411                 do {
412                         out1c(' ');
413                         col++;
414                 } while (col < 30);
415                 if (mode == SHOWJOBS_VERBOSE) {
416                         out1str(ps->cmd);
417                         out1c('\n');
418                 } else
419                         printjobcmd(jp);
420         }
421 }
422
423 /*
424  * Print a list of jobs.  If "change" is nonzero, only print jobs whose
425  * statuses have changed since the last call to showjobs.
426  *
427  * If the shell is interrupted in the process of creating a job, the
428  * result may be a job structure containing zero processes.  Such structures
429  * will be freed here.
430  */
431
432 void
433 showjobs(int change, int mode)
434 {
435         int jobno;
436         struct job *jp;
437
438         TRACE(("showjobs(%d) called\n", change));
439         checkzombies();
440         for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
441                 if (! jp->used)
442                         continue;
443                 if (jp->nprocs == 0) {
444                         freejob(jp);
445                         continue;
446                 }
447                 if (change && ! jp->changed)
448                         continue;
449                 showjob(jp, mode);
450                 if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
451                         jp->changed = 0;
452                         /* Hack: discard jobs for which $! has not been
453                          * referenced in interactive mode when they terminate.
454                          */
455                         if (jp->state == JOBDONE && !jp->remembered &&
456                                         (iflag || jp != bgjob)) {
457                                 freejob(jp);
458                         }
459                 }
460         }
461 }
462
463
464 /*
465  * Mark a job structure as unused.
466  */
467
468 static void
469 freejob(struct job *jp)
470 {
471         struct procstat *ps;
472         int i;
473
474         INTOFF;
475         if (bgjob == jp)
476                 bgjob = NULL;
477         for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
478                 if (ps->cmd != nullstr)
479                         ckfree(ps->cmd);
480         }
481         if (jp->ps != &jp->ps0)
482                 ckfree(jp->ps);
483         jp->used = 0;
484 #if JOBS
485         deljob(jp);
486 #endif
487         INTON;
488 }
489
490
491
492 int
493 waitcmd(int argc __unused, char **argv __unused)
494 {
495         struct job *job;
496         int retval;
497
498         nextopt("");
499         if (*argptr == NULL)
500                 return (waitcmdloop(NULL));
501
502         do {
503                 job = getjob_nonotfound(*argptr);
504                 if (job == NULL)
505                         retval = 127;
506                 else
507                         retval = waitcmdloop(job);
508                 argptr++;
509         } while (*argptr != NULL);
510
511         return (retval);
512 }
513
514 static int
515 waitcmdloop(struct job *job)
516 {
517         int status, retval, sig;
518         struct job *jp;
519
520         /*
521          * Loop until a process is terminated or stopped, or a SIGINT is
522          * received.
523          */
524
525         do {
526                 if (job != NULL) {
527                         if (job->state == JOBDONE) {
528                                 status = job->ps[job->nprocs - 1].status;
529                                 if (WIFEXITED(status))
530                                         retval = WEXITSTATUS(status);
531                                 else
532                                         retval = WTERMSIG(status) + 128;
533                                 if (! iflag || ! job->changed)
534                                         freejob(job);
535                                 else {
536                                         job->remembered = 0;
537                                         if (job == bgjob)
538                                                 bgjob = NULL;
539                                 }
540                                 return retval;
541                         }
542                 } else {
543                         for (jp = jobtab ; jp < jobtab + njobs; jp++)
544                                 if (jp->used && jp->state == JOBDONE) {
545                                         if (! iflag || ! jp->changed)
546                                                 freejob(jp);
547                                         else {
548                                                 jp->remembered = 0;
549                                                 if (jp == bgjob)
550                                                         bgjob = NULL;
551                                         }
552                                 }
553                         for (jp = jobtab ; ; jp++) {
554                                 if (jp >= jobtab + njobs) {     /* no running procs */
555                                         return 0;
556                                 }
557                                 if (jp->used && jp->state == 0)
558                                         break;
559                         }
560                 }
561         } while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, (struct job *)NULL) != -1);
562
563         sig = pendingsig_waitcmd;
564         pendingsig_waitcmd = 0;
565         return sig + 128;
566 }
567
568
569
570 int
571 jobidcmd(int argc __unused, char **argv __unused)
572 {
573         struct job *jp;
574         int i;
575
576         nextopt("");
577         jp = getjob(*argptr);
578         for (i = 0 ; i < jp->nprocs ; ) {
579                 out1fmt("%d", (int)jp->ps[i].pid);
580                 out1c(++i < jp->nprocs? ' ' : '\n');
581         }
582         return 0;
583 }
584
585
586
587 /*
588  * Convert a job name to a job structure.
589  */
590
591 static struct job *
592 getjob_nonotfound(const char *name)
593 {
594         int jobno;
595         struct job *found, *jp;
596         size_t namelen;
597         pid_t pid;
598         int i;
599
600         if (name == NULL) {
601 #if JOBS
602                 name = "%+";
603 #else
604                 error("No current job");
605 #endif
606         }
607         if (name[0] == '%') {
608                 if (is_digit(name[1])) {
609                         jobno = number(name + 1);
610                         if (jobno > 0 && jobno <= njobs
611                          && jobtab[jobno - 1].used != 0)
612                                 return &jobtab[jobno - 1];
613 #if JOBS
614                 } else if ((name[1] == '%' || name[1] == '+') &&
615                     name[2] == '\0') {
616                         if ((jp = getcurjob(NULL)) == NULL)
617                                 error("No current job");
618                         return (jp);
619                 } else if (name[1] == '-' && name[2] == '\0') {
620                         if ((jp = getcurjob(NULL)) == NULL ||
621                             (jp = getcurjob(jp)) == NULL)
622                                 error("No previous job");
623                         return (jp);
624 #endif
625                 } else if (name[1] == '?') {
626                         found = NULL;
627                         for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
628                                 if (jp->used && jp->nprocs > 0
629                                  && strstr(jp->ps[0].cmd, name + 2) != NULL) {
630                                         if (found)
631                                                 error("%s: ambiguous", name);
632                                         found = jp;
633                                 }
634                         }
635                         if (found != NULL)
636                                 return (found);
637                 } else {
638                         namelen = strlen(name);
639                         found = NULL;
640                         for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
641                                 if (jp->used && jp->nprocs > 0
642                                  && strncmp(jp->ps[0].cmd, name + 1,
643                                  namelen - 1) == 0) {
644                                         if (found)
645                                                 error("%s: ambiguous", name);
646                                         found = jp;
647                                 }
648                         }
649                         if (found)
650                                 return found;
651                 }
652         } else if (is_number(name)) {
653                 pid = (pid_t)number(name);
654                 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
655                         if (jp->used && jp->nprocs > 0
656                          && jp->ps[jp->nprocs - 1].pid == pid)
657                                 return jp;
658                 }
659         }
660         return NULL;
661 }
662
663
664 static struct job *
665 getjob(const char *name)
666 {
667         struct job *jp;
668
669         jp = getjob_nonotfound(name);
670         if (jp == NULL)
671                 error("No such job: %s", name);
672         return (jp);
673 }
674
675
676 int
677 killjob(const char *name, int sig)
678 {
679         struct job *jp;
680         int i, ret;
681
682         jp = getjob(name);
683         if (jp->state == JOBDONE)
684                 return 0;
685         if (jp->jobctl)
686                 return kill(-jp->ps[0].pid, sig);
687         ret = -1;
688         errno = ESRCH;
689         for (i = 0; i < jp->nprocs; i++)
690                 if (jp->ps[i].status == -1 || WIFSTOPPED(jp->ps[i].status)) {
691                         if (kill(jp->ps[i].pid, sig) == 0)
692                                 ret = 0;
693                 } else
694                         ret = 0;
695         return ret;
696 }
697
698 /*
699  * Return a new job structure,
700  */
701
702 struct job *
703 makejob(union node *node __unused, int nprocs)
704 {
705         int i;
706         struct job *jp;
707
708         for (i = njobs, jp = jobtab ; ; jp++) {
709                 if (--i < 0) {
710                         INTOFF;
711                         if (njobs == 0) {
712                                 jobtab = ckmalloc(4 * sizeof jobtab[0]);
713 #if JOBS
714                                 jobmru = NULL;
715 #endif
716                         } else {
717                                 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
718                                 memcpy(jp, jobtab, njobs * sizeof jp[0]);
719 #if JOBS
720                                 /* Relocate `next' pointers and list head */
721                                 if (jobmru != NULL)
722                                         jobmru = &jp[jobmru - jobtab];
723                                 for (i = 0; i < njobs; i++)
724                                         if (jp[i].next != NULL)
725                                                 jp[i].next = &jp[jp[i].next -
726                                                     jobtab];
727 #endif
728                                 if (bgjob != NULL)
729                                         bgjob = &jp[bgjob - jobtab];
730                                 /* Relocate `ps' pointers */
731                                 for (i = 0; i < njobs; i++)
732                                         if (jp[i].ps == &jobtab[i].ps0)
733                                                 jp[i].ps = &jp[i].ps0;
734                                 ckfree(jobtab);
735                                 jobtab = jp;
736                         }
737                         jp = jobtab + njobs;
738                         for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
739                                 ;
740                         INTON;
741                         break;
742                 }
743                 if (jp->used == 0)
744                         break;
745         }
746         INTOFF;
747         jp->state = 0;
748         jp->used = 1;
749         jp->changed = 0;
750         jp->nprocs = 0;
751         jp->foreground = 0;
752         jp->remembered = 0;
753 #if JOBS
754         jp->jobctl = jobctl;
755         jp->next = NULL;
756 #endif
757         if (nprocs > 1) {
758                 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
759         } else {
760                 jp->ps = &jp->ps0;
761         }
762         INTON;
763         TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
764             jp - jobtab + 1));
765         return jp;
766 }
767
768 #if JOBS
769 static void
770 setcurjob(struct job *cj)
771 {
772         struct job *jp, *prev;
773
774         for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
775                 if (jp == cj) {
776                         if (prev != NULL)
777                                 prev->next = jp->next;
778                         else
779                                 jobmru = jp->next;
780                         jp->next = jobmru;
781                         jobmru = cj;
782                         return;
783                 }
784         }
785         cj->next = jobmru;
786         jobmru = cj;
787 }
788
789 static void
790 deljob(struct job *j)
791 {
792         struct job *jp, *prev;
793
794         for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
795                 if (jp == j) {
796                         if (prev != NULL)
797                                 prev->next = jp->next;
798                         else
799                                 jobmru = jp->next;
800                         return;
801                 }
802         }
803 }
804
805 /*
806  * Return the most recently used job that isn't `nj', and preferably one
807  * that is stopped.
808  */
809 static struct job *
810 getcurjob(struct job *nj)
811 {
812         struct job *jp;
813
814         /* Try to find a stopped one.. */
815         for (jp = jobmru; jp != NULL; jp = jp->next)
816                 if (jp->used && jp != nj && jp->state == JOBSTOPPED)
817                         return (jp);
818         /* Otherwise the most recently used job that isn't `nj' */
819         for (jp = jobmru; jp != NULL; jp = jp->next)
820                 if (jp->used && jp != nj)
821                         return (jp);
822
823         return (NULL);
824 }
825
826 #endif
827
828 /*
829  * Fork of a subshell.  If we are doing job control, give the subshell its
830  * own process group.  Jp is a job structure that the job is to be added to.
831  * N is the command that will be evaluated by the child.  Both jp and n may
832  * be NULL.  The mode parameter can be one of the following:
833  *      FORK_FG - Fork off a foreground process.
834  *      FORK_BG - Fork off a background process.
835  *      FORK_NOJOB - Like FORK_FG, but don't give the process its own
836  *                   process group even if job control is on.
837  *
838  * When job control is turned off, background processes have their standard
839  * input redirected to /dev/null (except for the second and later processes
840  * in a pipeline).
841  */
842
843 pid_t
844 forkshell(struct job *jp, union node *n, int mode)
845 {
846         pid_t pid;
847         pid_t pgrp;
848
849         TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
850             mode));
851         INTOFF;
852         if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
853                 checkzombies();
854         flushall();
855         pid = fork();
856         if (pid == -1) {
857                 TRACE(("Fork failed, errno=%d\n", errno));
858                 INTON;
859                 error("Cannot fork: %s", strerror(errno));
860         }
861         if (pid == 0) {
862                 struct job *p;
863                 int wasroot;
864                 int i;
865
866                 TRACE(("Child shell %d\n", (int)getpid()));
867                 wasroot = rootshell;
868                 rootshell = 0;
869                 handler = &main_handler;
870                 closescript();
871                 INTON;
872                 forcelocal = 0;
873                 clear_traps();
874 #if JOBS
875                 jobctl = 0;             /* do job control only in root shell */
876                 if (wasroot && mode != FORK_NOJOB && mflag) {
877                         if (jp == NULL || jp->nprocs == 0)
878                                 pgrp = getpid();
879                         else
880                                 pgrp = jp->ps[0].pid;
881                         if (setpgid(0, pgrp) == 0 && mode == FORK_FG &&
882                             ttyfd >= 0) {
883                                 /*** this causes superfluous TIOCSPGRPS ***/
884                                 if (tcsetpgrp(ttyfd, pgrp) < 0)
885                                         error("tcsetpgrp failed, errno=%d", errno);
886                         }
887                         setsignal(SIGTSTP);
888                         setsignal(SIGTTOU);
889                 } else if (mode == FORK_BG) {
890                         ignoresig(SIGINT);
891                         ignoresig(SIGQUIT);
892                         if ((jp == NULL || jp->nprocs == 0) &&
893                             ! fd0_redirected_p ()) {
894                                 close(0);
895                                 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
896                                         error("cannot open %s: %s",
897                                             _PATH_DEVNULL, strerror(errno));
898                         }
899                 }
900 #else
901                 if (mode == FORK_BG) {
902                         ignoresig(SIGINT);
903                         ignoresig(SIGQUIT);
904                         if ((jp == NULL || jp->nprocs == 0) &&
905                             ! fd0_redirected_p ()) {
906                                 close(0);
907                                 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
908                                         error("cannot open %s: %s",
909                                             _PATH_DEVNULL, strerror(errno));
910                         }
911                 }
912 #endif
913                 INTOFF;
914                 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
915                         if (p->used)
916                                 freejob(p);
917                 INTON;
918                 if (wasroot && iflag) {
919                         setsignal(SIGINT);
920                         setsignal(SIGQUIT);
921                         setsignal(SIGTERM);
922                 }
923                 return pid;
924         }
925         if (rootshell && mode != FORK_NOJOB && mflag) {
926                 if (jp == NULL || jp->nprocs == 0)
927                         pgrp = pid;
928                 else
929                         pgrp = jp->ps[0].pid;
930                 setpgid(pid, pgrp);
931         }
932         if (mode == FORK_BG) {
933                 if (bgjob != NULL && bgjob->state == JOBDONE &&
934                     !bgjob->remembered && !iflag)
935                         freejob(bgjob);
936                 backgndpid = pid;               /* set $! */
937                 bgjob = jp;
938         }
939         if (jp) {
940                 struct procstat *ps = &jp->ps[jp->nprocs++];
941                 ps->pid = pid;
942                 ps->status = -1;
943                 ps->cmd = nullstr;
944                 if (iflag && rootshell && n)
945                         ps->cmd = commandtext(n);
946                 jp->foreground = mode == FORK_FG;
947 #if JOBS
948                 setcurjob(jp);
949 #endif
950         }
951         INTON;
952         TRACE(("In parent shell:  child = %d\n", (int)pid));
953         return pid;
954 }
955
956
957 pid_t
958 vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
959 {
960         pid_t pid;
961         struct jmploc jmploc;
962         struct jmploc *savehandler;
963
964         TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
965             (void *)pip));
966         INTOFF;
967         flushall();
968         savehandler = handler;
969         pid = vfork();
970         if (pid == -1) {
971                 TRACE(("Vfork failed, errno=%d\n", errno));
972                 INTON;
973                 error("Cannot fork: %s", strerror(errno));
974         }
975         if (pid == 0) {
976                 TRACE(("Child shell %d\n", (int)getpid()));
977                 if (setjmp(jmploc.loc))
978                         _exit(exception == EXEXEC ? exerrno : 2);
979                 if (pip != NULL) {
980                         close(pip[0]);
981                         if (pip[1] != 1) {
982                                 dup2(pip[1], 1);
983                                 close(pip[1]);
984                         }
985                 }
986                 handler = &jmploc;
987                 shellexec(argv, envp, path, idx);
988         }
989         handler = savehandler;
990         if (jp) {
991                 struct procstat *ps = &jp->ps[jp->nprocs++];
992                 ps->pid = pid;
993                 ps->status = -1;
994                 ps->cmd = nullstr;
995                 jp->foreground = 1;
996 #if JOBS
997                 setcurjob(jp);
998 #endif
999         }
1000         INTON;
1001         TRACE(("In parent shell:  child = %d\n", (int)pid));
1002         return pid;
1003 }
1004
1005
1006 /*
1007  * Wait for job to finish.
1008  *
1009  * Under job control we have the problem that while a child process is
1010  * running interrupts generated by the user are sent to the child but not
1011  * to the shell.  This means that an infinite loop started by an inter-
1012  * active user may be hard to kill.  With job control turned off, an
1013  * interactive user may place an interactive program inside a loop.  If
1014  * the interactive program catches interrupts, the user doesn't want
1015  * these interrupts to also abort the loop.  The approach we take here
1016  * is to have the shell ignore interrupt signals while waiting for a
1017  * foreground process to terminate, and then send itself an interrupt
1018  * signal if the child process was terminated by an interrupt signal.
1019  * Unfortunately, some programs want to do a bit of cleanup and then
1020  * exit on interrupt; unless these processes terminate themselves by
1021  * sending a signal to themselves (instead of calling exit) they will
1022  * confuse this approach.
1023  */
1024
1025 int
1026 waitforjob(struct job *jp, int *origstatus)
1027 {
1028 #if JOBS
1029         int propagate_int = jp->jobctl && jp->foreground;
1030 #endif
1031         int status;
1032         int st;
1033
1034         INTOFF;
1035         TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
1036         while (jp->state == 0)
1037                 if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
1038                     DOWAIT_SIG_TRAP : 0), jp) == -1)
1039                         dotrap();
1040 #if JOBS
1041         if (jp->jobctl) {
1042                 if (ttyfd >= 0 && tcsetpgrp(ttyfd, rootpid) < 0)
1043                         error("tcsetpgrp failed, errno=%d\n", errno);
1044         }
1045         if (jp->state == JOBSTOPPED)
1046                 setcurjob(jp);
1047 #endif
1048         status = jp->ps[jp->nprocs - 1].status;
1049         if (origstatus != NULL)
1050                 *origstatus = status;
1051         /* convert to 8 bits */
1052         if (WIFEXITED(status))
1053                 st = WEXITSTATUS(status);
1054 #if JOBS
1055         else if (WIFSTOPPED(status))
1056                 st = WSTOPSIG(status) + 128;
1057 #endif
1058         else
1059                 st = WTERMSIG(status) + 128;
1060         if (! JOBS || jp->state == JOBDONE)
1061                 freejob(jp);
1062         if (int_pending()) {
1063                 if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
1064                         CLEAR_PENDING_INT;
1065         }
1066 #if JOBS
1067         else if (rootshell && propagate_int &&
1068                         WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
1069                 kill(getpid(), SIGINT);
1070 #endif
1071         INTON;
1072         return st;
1073 }
1074
1075
1076 static void
1077 dummy_handler(int sig __unused)
1078 {
1079 }
1080
1081 /*
1082  * Wait for a process to terminate.
1083  */
1084
1085 static pid_t
1086 dowait(int mode, struct job *job)
1087 {
1088         struct sigaction sa, osa;
1089         sigset_t mask, omask;
1090         pid_t pid;
1091         int status;
1092         struct procstat *sp;
1093         struct job *jp;
1094         struct job *thisjob;
1095         const char *sigstr;
1096         int done;
1097         int stopped;
1098         int sig;
1099         int coredump;
1100         int wflags;
1101         int restore_sigchld;
1102
1103         TRACE(("dowait(%d, %p) called\n", mode, job));
1104         restore_sigchld = 0;
1105         if ((mode & DOWAIT_SIG) != 0) {
1106                 sigfillset(&mask);
1107                 sigprocmask(SIG_BLOCK, &mask, &omask);
1108                 INTOFF;
1109                 if (!issigchldtrapped()) {
1110                         restore_sigchld = 1;
1111                         sa.sa_handler = dummy_handler;
1112                         sa.sa_flags = 0;
1113                         sigemptyset(&sa.sa_mask);
1114                         sigaction(SIGCHLD, &sa, &osa);
1115                 }
1116         }
1117         do {
1118 #if JOBS
1119                 if (iflag)
1120                         wflags = WUNTRACED | WCONTINUED;
1121                 else
1122 #endif
1123                         wflags = 0;
1124                 if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
1125                         wflags |= WNOHANG;
1126                 pid = wait3(&status, wflags, (struct rusage *)NULL);
1127                 TRACE(("wait returns %d, status=%d\n", (int)pid, status));
1128                 if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
1129                         pid = -1;
1130                         if (((mode & DOWAIT_SIG_TRAP) != 0 ?
1131                             pendingsig : pendingsig_waitcmd) != 0) {
1132                                 errno = EINTR;
1133                                 break;
1134                         }
1135                         sigsuspend(&omask);
1136                         if (int_pending())
1137                                 break;
1138                 }
1139         } while (pid == -1 && errno == EINTR);
1140         if (pid == -1 && errno == ECHILD && job != NULL)
1141                 job->state = JOBDONE;
1142         if ((mode & DOWAIT_SIG) != 0) {
1143                 if (restore_sigchld)
1144                         sigaction(SIGCHLD, &osa, NULL);
1145                 sigprocmask(SIG_SETMASK, &omask, NULL);
1146                 INTON;
1147         }
1148         if (pid <= 0)
1149                 return pid;
1150         INTOFF;
1151         thisjob = NULL;
1152         for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
1153                 if (jp->used && jp->nprocs > 0) {
1154                         done = 1;
1155                         stopped = 1;
1156                         for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
1157                                 if (sp->pid == -1)
1158                                         continue;
1159                                 if (sp->pid == pid && (sp->status == -1 ||
1160                                     WIFSTOPPED(sp->status))) {
1161                                         TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
1162                                                    (int)pid, sp->status,
1163                                                    status));
1164                                         if (WIFCONTINUED(status)) {
1165                                                 sp->status = -1;
1166                                                 jp->state = 0;
1167                                         } else
1168                                                 sp->status = status;
1169                                         thisjob = jp;
1170                                 }
1171                                 if (sp->status == -1)
1172                                         stopped = 0;
1173                                 else if (WIFSTOPPED(sp->status))
1174                                         done = 0;
1175                         }
1176                         if (stopped) {          /* stopped or done */
1177                                 int state = done? JOBDONE : JOBSTOPPED;
1178                                 if (jp->state != state) {
1179                                         TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
1180                                         jp->state = state;
1181                                         if (jp != job) {
1182                                                 if (done && !jp->remembered &&
1183                                                     !iflag && jp != bgjob)
1184                                                         freejob(jp);
1185 #if JOBS
1186                                                 else if (done)
1187                                                         deljob(jp);
1188 #endif
1189                                         }
1190                                 }
1191                         }
1192                 }
1193         }
1194         INTON;
1195         if (!thisjob || thisjob->state == 0)
1196                 ;
1197         else if ((!rootshell || !iflag || thisjob == job) &&
1198             thisjob->foreground && thisjob->state != JOBSTOPPED) {
1199                 sig = 0;
1200                 coredump = 0;
1201                 for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
1202                         if (WIFSIGNALED(sp->status)) {
1203                                 sig = WTERMSIG(sp->status);
1204                                 coredump = WCOREDUMP(sp->status);
1205                         }
1206                 if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
1207                         sigstr = strsignal(sig);
1208                         if (sigstr != NULL)
1209                                 out2str(sigstr);
1210                         else
1211                                 out2str("Unknown signal");
1212                         if (coredump)
1213                                 out2str(" (core dumped)");
1214                         out2c('\n');
1215                         flushout(out2);
1216                 }
1217         } else {
1218                 TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
1219                 thisjob->changed = 1;
1220         }
1221         return pid;
1222 }
1223
1224
1225
1226 /*
1227  * return 1 if there are stopped jobs, otherwise 0
1228  */
1229 int job_warning = 0;
1230 int
1231 stoppedjobs(void)
1232 {
1233         int jobno;
1234         struct job *jp;
1235
1236         if (job_warning)
1237                 return (0);
1238         for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
1239                 if (jp->used == 0)
1240                         continue;
1241                 if (jp->state == JOBSTOPPED) {
1242                         out2fmt_flush("You have stopped jobs.\n");
1243                         job_warning = 2;
1244                         return (1);
1245                 }
1246         }
1247
1248         return (0);
1249 }
1250
1251
1252 static void
1253 checkzombies(void)
1254 {
1255         while (njobs > 0 && dowait(0, NULL) > 0)
1256                 ;
1257 }
1258
1259
1260 int
1261 backgndpidset(void)
1262 {
1263         return backgndpid != -1;
1264 }
1265
1266
1267 pid_t
1268 backgndpidval(void)
1269 {
1270         if (bgjob != NULL && !forcelocal)
1271                 bgjob->remembered = 1;
1272         return backgndpid;
1273 }
1274
1275 /*
1276  * Return a string identifying a command (to be printed by the
1277  * jobs command.
1278  */
1279
1280 static char *cmdnextc;
1281 static int cmdnleft;
1282 #define MAXCMDTEXT      200
1283
1284 char *
1285 commandtext(union node *n)
1286 {
1287         char *name;
1288
1289         cmdnextc = name = ckmalloc(MAXCMDTEXT);
1290         cmdnleft = MAXCMDTEXT - 4;
1291         cmdtxt(n);
1292         *cmdnextc = '\0';
1293         return name;
1294 }
1295
1296
1297 static void
1298 cmdtxtdogroup(union node *n)
1299 {
1300         cmdputs("; do ");
1301         cmdtxt(n);
1302         cmdputs("; done");
1303 }
1304
1305
1306 static void
1307 cmdtxtredir(union node *n, const char *op, int deffd)
1308 {
1309         char s[2];
1310
1311         if (n->nfile.fd != deffd) {
1312                 s[0] = n->nfile.fd + '0';
1313                 s[1] = '\0';
1314                 cmdputs(s);
1315         }
1316         cmdputs(op);
1317         if (n->type == NTOFD || n->type == NFROMFD) {
1318                 if (n->ndup.dupfd >= 0)
1319                         s[0] = n->ndup.dupfd + '0';
1320                 else
1321                         s[0] = '-';
1322                 s[1] = '\0';
1323                 cmdputs(s);
1324         } else {
1325                 cmdtxt(n->nfile.fname);
1326         }
1327 }
1328
1329
1330 static void
1331 cmdtxt(union node *n)
1332 {
1333         union node *np;
1334         struct nodelist *lp;
1335
1336         if (n == NULL)
1337                 return;
1338         switch (n->type) {
1339         case NSEMI:
1340                 cmdtxt(n->nbinary.ch1);
1341                 cmdputs("; ");
1342                 cmdtxt(n->nbinary.ch2);
1343                 break;
1344         case NAND:
1345                 cmdtxt(n->nbinary.ch1);
1346                 cmdputs(" && ");
1347                 cmdtxt(n->nbinary.ch2);
1348                 break;
1349         case NOR:
1350                 cmdtxt(n->nbinary.ch1);
1351                 cmdputs(" || ");
1352                 cmdtxt(n->nbinary.ch2);
1353                 break;
1354         case NPIPE:
1355                 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
1356                         cmdtxt(lp->n);
1357                         if (lp->next)
1358                                 cmdputs(" | ");
1359                 }
1360                 break;
1361         case NSUBSHELL:
1362                 cmdputs("(");
1363                 cmdtxt(n->nredir.n);
1364                 cmdputs(")");
1365                 break;
1366         case NREDIR:
1367         case NBACKGND:
1368                 cmdtxt(n->nredir.n);
1369                 break;
1370         case NIF:
1371                 cmdputs("if ");
1372                 cmdtxt(n->nif.test);
1373                 cmdputs("; then ");
1374                 cmdtxt(n->nif.ifpart);
1375                 cmdputs("...");
1376                 break;
1377         case NWHILE:
1378                 cmdputs("while ");
1379                 cmdtxt(n->nbinary.ch1);
1380                 cmdtxtdogroup(n->nbinary.ch2);
1381                 break;
1382         case NUNTIL:
1383                 cmdputs("until ");
1384                 cmdtxt(n->nbinary.ch1);
1385                 cmdtxtdogroup(n->nbinary.ch2);
1386                 break;
1387         case NFOR:
1388                 cmdputs("for ");
1389                 cmdputs(n->nfor.var);
1390                 cmdputs(" in ...");
1391                 break;
1392         case NCASE:
1393                 cmdputs("case ");
1394                 cmdputs(n->ncase.expr->narg.text);
1395                 cmdputs(" in ...");
1396                 break;
1397         case NDEFUN:
1398                 cmdputs(n->narg.text);
1399                 cmdputs("() ...");
1400                 break;
1401         case NNOT:
1402                 cmdputs("! ");
1403                 cmdtxt(n->nnot.com);
1404                 break;
1405         case NCMD:
1406                 for (np = n->ncmd.args ; np ; np = np->narg.next) {
1407                         cmdtxt(np);
1408                         if (np->narg.next)
1409                                 cmdputs(" ");
1410                 }
1411                 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
1412                         cmdputs(" ");
1413                         cmdtxt(np);
1414                 }
1415                 break;
1416         case NARG:
1417                 cmdputs(n->narg.text);
1418                 break;
1419         case NTO:
1420                 cmdtxtredir(n, ">", 1);
1421                 break;
1422         case NAPPEND:
1423                 cmdtxtredir(n, ">>", 1);
1424                 break;
1425         case NTOFD:
1426                 cmdtxtredir(n, ">&", 1);
1427                 break;
1428         case NCLOBBER:
1429                 cmdtxtredir(n, ">|", 1);
1430                 break;
1431         case NFROM:
1432                 cmdtxtredir(n, "<", 0);
1433                 break;
1434         case NFROMTO:
1435                 cmdtxtredir(n, "<>", 0);
1436                 break;
1437         case NFROMFD:
1438                 cmdtxtredir(n, "<&", 0);
1439                 break;
1440         case NHERE:
1441         case NXHERE:
1442                 cmdputs("<<...");
1443                 break;
1444         default:
1445                 cmdputs("???");
1446                 break;
1447         }
1448 }
1449
1450
1451
1452 static void
1453 cmdputs(const char *s)
1454 {
1455         const char *p;
1456         char *q;
1457         char c;
1458         int subtype = 0;
1459
1460         if (cmdnleft <= 0)
1461                 return;
1462         p = s;
1463         q = cmdnextc;
1464         while ((c = *p++) != '\0') {
1465                 if (c == CTLESC)
1466                         *q++ = *p++;
1467                 else if (c == CTLVAR) {
1468                         *q++ = '$';
1469                         if (--cmdnleft > 0)
1470                                 *q++ = '{';
1471                         subtype = *p++;
1472                         if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
1473                                 *q++ = '#';
1474                 } else if (c == '=' && subtype != 0) {
1475                         *q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
1476                         if (*q)
1477                                 q++;
1478                         else
1479                                 cmdnleft++;
1480                         if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
1481                             (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
1482                             --cmdnleft > 0)
1483                                 *q = q[-1], q++;
1484                         subtype = 0;
1485                 } else if (c == CTLENDVAR) {
1486                         *q++ = '}';
1487                 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
1488                         cmdnleft -= 5;
1489                         if (cmdnleft > 0) {
1490                                 *q++ = '$';
1491                                 *q++ = '(';
1492                                 *q++ = '.';
1493                                 *q++ = '.';
1494                                 *q++ = '.';
1495                                 *q++ = ')';
1496                         }
1497                 } else if (c == CTLARI) {
1498                         cmdnleft -= 2;
1499                         if (cmdnleft > 0) {
1500                                 *q++ = '$';
1501                                 *q++ = '(';
1502                                 *q++ = '(';
1503                         }
1504                         p++;
1505                 } else if (c == CTLENDARI) {
1506                         if (--cmdnleft > 0) {
1507                                 *q++ = ')';
1508                                 *q++ = ')';
1509                         }
1510                 } else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
1511                         cmdnleft++; /* ignore */
1512                 else
1513                         *q++ = c;
1514                 if (--cmdnleft <= 0) {
1515                         *q++ = '.';
1516                         *q++ = '.';
1517                         *q++ = '.';
1518                         break;
1519                 }
1520         }
1521         cmdnextc = q;
1522 }