1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
|
/**
* @file jobs.c
* @brief Child processes, the job table and job control.
*
* There are two ways the shell looks after its children.
*
* **Without job control** (every script, and `set +m`): a foreground
* child is simply waited for with wait_fg(). Nothing is allocated and no
* process groups are touched, so the common path costs one `waitpid()`.
* Background children are recorded in the job table only so that `wait`,
* `jobs`, `kill %n` and `$!` work.
*
* **With job control** (`set -m`, the default for an interactive shell on
* a terminal): every command line that creates processes is a *job* with
* its own process group. The job in the foreground owns the terminal, so
* `^C` and `^Z` reach it and not the shell. A job that stops is kept in
* the table and can be resumed with `fg` or `bg`.
*
* The evaluator does not pass a job around. It brackets process creation
* with job_begin() and job_wait_fg()/job_end_bg(). While a job is being
* launched, fork_shell() and spawn_command() ask this file (through
* #job_launching) which process group the new process belongs to.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include "exec.h"
#include "shell.h"
#include "sys.h"
/** @brief One process of a job. */
typedef struct proc {
pid_t pid;
int status; /**< Shell exit status once done; 128+signal if stopped. */
int sig; /**< Signal that killed or stopped it, or 0. */
bool done; /**< Has been reaped. */
bool stopped; /**< Currently stopped. */
} proc;
/** @brief A job: the processes created for one command. */
typedef struct job {
struct job *next; /**< Next older job. */
int id; /**< The N of `%N`. */
pid_t pgid; /**< Its process group, or 0 if it has none of its own. */
proc *procs;
int nprocs;
char *text; /**< Command text for listings; may be nullptr. */
bool announce; /**< Changed state; tell the user before the next prompt. */
} job;
/** @brief What a job as a whole is doing. */
typedef enum job_state { JOB_RUNNING, JOB_STOPPED, JOB_DONE } job_state;
/** @brief All jobs, most recently created or resumed first. */
job *job_list;
/**
* @brief The job that processes created right now belong to.
*
* Set between job_begin() and the end of launching. nullptr otherwise,
* including whenever job control is off.
*/
job *job_launching;
/** @brief `$!`: process ID of the most recent background command. */
pid_t last_bg_pid;
/** @brief A background process reaped before anything waited for it. */
typedef struct reaped {
pid_t pid;
int status;
} reaped;
/**
* @brief Statuses `wait` has not collected yet, oldest first.
*
* A non-interactive shell frees a finished job as soon as it is reaped, but
* POSIX lets `wait $pid` ask for it afterwards. The list is bounded by
* _SC_CHILD_MAX; past that the oldest entry is forgotten.
*/
static reaped *reaped_list;
static int reaped_n;
static int reaped_cap;
static bool launching_fg; /**< The job being launched gets the terminal. */
static bool jc_on; /**< Job control is active in this process. */
static int tty_fd = -1; /**< The controlling terminal, when jc_on. */
static pid_t shell_pgid; /**< The shell's own process group. */
static pid_t initial_pgid; /**< The group the shell started in. */
static struct termios shell_tmodes; /**< Terminal modes to return to. */
/**
* @brief shell_tmodes holds valid terminal modes.
*/
static bool have_tmodes;
/**
* @brief Convert a `waitpid()` status to a shell exit status.
* @param wstatus Status from `waitpid()`.
* @return The exit code, or 128 plus the signal number.
*/
static int status_of(int wstatus) {
if (WIFEXITED(wstatus))
return WEXITSTATUS(wstatus);
if (WIFSIGNALED(wstatus))
return 128 + WTERMSIG(wstatus);
if (WIFSTOPPED(wstatus))
return 128 + WSTOPSIG(wstatus);
return 1;
}
/**
* @brief Say on stderr that a foreground child was killed by a signal.
*
* Nothing is said for SIGINT (the user did that) or SIGPIPE (normal for
* `producer | head`).
*
* @param sig The signal.
*/
static void report_signal(int sig) {
if (sig == SIGINT || sig == SIGPIPE)
return;
out_printf(&out2, "%s\n", sys_strsignal(sig));
out_flush(&out2);
}
/**
* @brief Wait for one foreground child that is not part of a job.
*
* This is the fast path used whenever job control is off.
*
* @param pid The child.
* @return Its exit status (127 if it could not be waited for).
*/
int wait_fg(pid_t pid) {
int wstatus;
while (waitpid(pid, &wstatus, 0) < 0) {
if (errno != EINTR)
return 127;
}
if (WIFSIGNALED(wstatus))
report_signal(WTERMSIG(wstatus));
return status_of(wstatus);
}
/* ---- the job table --------------------------------------------------- */
/**
* @brief Create an empty job and put it at the head of the table.
* @param text Command text (ownership passes to the job), or nullptr.
* @return The new job.
*/
static job *job_new(char *text) {
job *j = xmalloc(sizeof *j);
int id = 0;
for (const job *o = job_list; o; o = o->next) {
if (o->id > id)
id = o->id;
}
*j = (job){.next = job_list, .id = id + 1, .text = text};
job_list = j;
return j;
}
/**
* @brief Remove a job from the table and free it.
* @param j The job.
*/
static void job_free(job *j) {
for (job **pj = &job_list; *pj; pj = &(*pj)->next) {
if (*pj == j) {
*pj = j->next;
break;
}
}
if (job_launching == j)
job_launching = nullptr;
free(j->procs);
free(j->text);
free(j);
}
/**
* @brief Work out what a job is doing from its processes.
* @param j The job.
* @return JOB_DONE when every process has been reaped, JOB_STOPPED when
* everything still alive is stopped, else JOB_RUNNING.
*/
static job_state job_get_state(const job *j) {
bool stopped = false;
for (int i = 0; i < j->nprocs; i++) {
if (j->procs[i].done)
continue;
if (!j->procs[i].stopped)
return JOB_RUNNING;
stopped = true;
}
return stopped ? JOB_STOPPED : JOB_DONE;
}
/**
* @brief Record a new process as part of a job.
*
* Under job control the process is also moved into the job's process
* group from this side. The child does the same for itself (or spawn()
* does it for it). Doing it in both places closes the window in which
* the parent might signal a group the child has not joined yet.
*
* @param j The job.
* @param pid The new child.
*/
void job_add_proc(job *j, pid_t pid) {
j->procs = xrealloc(j->procs, ((size_t)j->nprocs + 1) * sizeof *j->procs);
j->procs[j->nprocs++] = (proc){.pid = pid};
if (jc_on && j == job_launching) {
if (!j->pgid)
j->pgid = pid;
setpgid(pid, j->pgid); /* fails harmlessly once the child has exec'd */
}
}
/**
* @brief Fold a `waitpid()` result into a process record.
* @param p The process.
* @param wstatus Its new status.
*/
static void proc_update(proc *p, int wstatus) {
#ifdef WIFCONTINUED
if (WIFCONTINUED(wstatus)) {
p->stopped = false;
return;
}
#endif
p->status = status_of(wstatus);
if (WIFSTOPPED(wstatus)) {
p->stopped = true;
p->sig = WSTOPSIG(wstatus);
} else {
p->done = true;
p->stopped = false;
p->sig = WIFSIGNALED(wstatus) ? WTERMSIG(wstatus) : 0;
}
}
/** @brief The `waitpid()` flags that also report stops and continues. */
static int poll_flags(void) {
int flags = WNOHANG;
if (jc_on) {
flags |= WUNTRACED;
#ifdef WCONTINUED
flags |= WCONTINUED;
#endif
}
return flags;
}
/**
* @brief Describe the state of a job for a listing.
* @param j The job.
* @param buf Scratch space for the "Done(N)" form.
* @param n Size of `buf`.
* @return "Running", "Stopped", "Done", "Done(N)" or the signal's name.
*/
static const char *job_state_text(const job *j, char *buf, size_t n) {
switch (job_get_state(j)) {
case JOB_RUNNING:
return "Running";
case JOB_STOPPED:
return "Stopped";
case JOB_DONE:
break;
}
const proc *last = &j->procs[j->nprocs - 1];
if (last->sig)
return sys_strsignal(last->sig);
if (!last->status)
return "Done";
char num[INT_BUFSZ];
size_t len = 0;
for (const char *s = "Done("; *s && len + 1 < n; s++)
buf[len++] = *s;
for (const char *s = fmt_int(last->status, num); *s && len + 1 < n; s++)
buf[len++] = *s;
if (len + 1 < n)
buf[len++] = ')';
buf[len] = '\0';
return buf;
}
/** @brief How a job is printed. */
enum {
JP_LONG = 1u << 0, /**< Include the process ID (`jobs -l`). */
JP_PIDS = 1u << 1, /**< Print only the process group ID (`jobs -p`). */
};
/**
* @brief Print one line describing a job.
*
* The layout is the POSIX one: `[N] C state command`, where C is `+` for
* the current job, `-` for the previous one and a space otherwise.
*
* @param o Where to print.
* @param j The job.
* @param flags JP_LONG or JP_PIDS.
*/
static void job_print(output *o, const job *j, unsigned flags) {
pid_t lead = j->pgid ? j->pgid : j->procs[0].pid;
if (flags & JP_PIDS) {
out_printf(o, "%ld\n", (long)lead);
return;
}
char buf[32];
char mark = j == job_list ? '+' : j == job_list->next ? '-' : ' ';
out_printf(o, "[%d] %c ", j->id, mark);
if (flags & JP_LONG)
out_printf(o, "%ld ", (long)lead);
out_printf(o, "%-22s %s\n", job_state_text(j, buf, sizeof buf),
j->text ? j->text : "");
}
/**
* @brief Collect state changes of background jobs without blocking.
*
* In an interactive shell a job that finishes or stops is flagged so
* that jobs_notify() reports it. In a script, finished jobs are dropped
* at once, except the one `$!` names: its status must stay available to
* `wait $!`.
*/
/**
* @brief Remember the status of a reaped background process.
*/
static void reaped_add(pid_t pid, int status) {
if (reaped_n == reaped_cap) {
long max = sysconf(_SC_CHILD_MAX);
int cap = reaped_cap ? reaped_cap * 2 : 16;
if (max > 0 && cap > max)
cap = (int)max;
if (cap > reaped_n) {
reaped_list =
xrealloc(reaped_list, (size_t)cap * sizeof *reaped_list);
reaped_cap = cap;
} else {
memmove(reaped_list, reaped_list + 1,
(size_t)(reaped_n - 1) * sizeof *reaped_list);
reaped_n--;
}
}
reaped_list[reaped_n++] = (reaped){pid, status};
}
/**
* @brief Status of a finished background process.
*
* The entry stays, because `wait` on a pid it has already collected answers
* with the same status, as dash and bash do.
*
* @return true if that process was one of the remembered ones.
*/
static bool reaped_find(long pid, int *status) {
for (int i = 0; i < reaped_n; i++) {
if ((long)reaped_list[i].pid != pid)
continue;
*status = reaped_list[i].status;
return true;
}
return false;
}
void jobs_reap(void) {
int flags = poll_flags();
for (job *j = job_list, *next; j; j = next) {
next = j->next;
if (j == job_launching)
continue;
job_state before = job_get_state(j);
for (int i = 0; i < j->nprocs; i++) {
proc *p = &j->procs[i];
int wstatus;
if (!p->done && waitpid(p->pid, &wstatus, flags) == p->pid)
proc_update(p, wstatus);
}
job_state after = job_get_state(j);
if (after == before)
continue;
if (opt.interactive) {
j->announce = after != JOB_RUNNING;
} else if (after == JOB_DONE &&
j->procs[j->nprocs - 1].pid != last_bg_pid) {
for (int i = 0; i < j->nprocs; i++)
reaped_add(j->procs[i].pid, j->procs[i].status);
job_free(j);
}
}
}
/**
* @brief Report finished and stopped background jobs, then forget the
* finished ones. Called just before the prompt is printed.
*/
void jobs_notify(void) {
if (!job_list)
return;
jobs_reap();
for (job *j = job_list, *next; j; j = next) {
next = j->next;
if (!j->announce)
continue;
j->announce = false;
job_print(&out2, j, 0);
if (job_get_state(j) == JOB_DONE)
job_free(j);
}
out_flush(&out2);
}
/**
* @brief Record a background process created without job control.
*
* In an interactive shell the job number and process ID are printed, as
* POSIX asks.
*
* @param pid The child.
* @param n The command, for the listing text. May be nullptr.
*/
void jobs_add(pid_t pid, const node *n) {
job *j = job_new(node_text(n));
job_add_proc(j, pid);
last_bg_pid = pid;
if (opt.interactive) {
out_printf(&out2, "[%d] %ld\n", j->id, (long)pid);
out_flush(&out2);
}
}
/**
* @brief Forget every job. A forked child calls this: the parent's
* children are not the child's.
*/
void jobs_forget(void) {
while (job_list)
job_free(job_list);
job_launching = nullptr;
jc_on = false;
opt.monitor = false;
}
/**
* @brief Count the jobs that are stopped.
* @return The number of stopped jobs (after collecting pending changes).
*/
int jobs_stopped(void) {
int n = 0;
jobs_reap();
for (const job *j = job_list; j; j = j->next)
n += job_get_state(j) == JOB_STOPPED;
return n;
}
/* ---- job control ----------------------------------------------------- */
/**
* @brief Is job control active in this process?
* @return true when commands get their own process groups.
*/
bool jc_active(void) {
return jc_on;
}
/**
* @brief The terminal a foreground job should be handed, or -1.
*
* Used by spawn_command() to have the platform layer give the child's
* process group the terminal as part of creating it.
*/
int job_tty(void) {
return jc_on && launching_fg ? tty_fd : -1;
}
/**
* @brief Bring job control in line with the `monitor` option.
*
* Called at startup and after `set -m` / `set +m`. Turning it on means:
* find the terminal, wait until the shell is in the foreground, ignore the
* job-control stop signals, and put the shell in a process group of its
* own that owns the terminal. If there is no terminal, job control stays
* off and the option is cleared.
*/
void jc_sync(void) {
bool want = opt.monitor && !in_subshell;
if (want == jc_on)
return;
if (!want) {
tcsetpgrp(tty_fd, initial_pgid);
setpgid(0, initial_pgid);
trap_jobctl(false);
close(tty_fd);
tty_fd = -1;
jc_on = false;
return;
}
int fd = open("/dev/tty", O_RDWR);
if (fd < 0)
fd = isatty(2) ? dup(2) : isatty(0) ? dup(0) : -1;
if (fd >= 0) {
int high = sys_dupfd(fd, SYS_NFD);
close(fd);
fd = high;
}
pid_t fg;
if (fd < 0 || (fg = tcgetpgrp(fd)) < 0) {
if (fd >= 0)
close(fd);
if (opt.interactive)
sh_warn("cannot access the terminal: job control turned off");
opt.monitor = false;
return;
}
tty_fd = fd;
initial_pgid = getpgrp();
/* Started in the background: stop until the user brings us forward. */
while (fg != initial_pgid) {
kill(0, SIGTTIN);
fg = tcgetpgrp(tty_fd);
if (fg < 0)
break;
}
trap_jobctl(true);
shell_pgid = getpid();
if (setpgid(0, shell_pgid) < 0)
shell_pgid = getpgrp(); /* a session leader already has its own */
tcsetpgrp(tty_fd, shell_pgid);
have_tmodes = tcgetattr(tty_fd, &shell_tmodes) == 0;
jc_on = true;
}
/**
* @brief Give the terminal back to whoever had it when the shell started.
* Called on the way out of the shell.
*/
void jc_exit(void) {
if (jc_on && initial_pgid != shell_pgid) {
tcsetpgrp(tty_fd, initial_pgid);
setpgid(0, initial_pgid);
}
}
/**
* @brief Start a job-controlled job. Processes created from now on join it.
*
* Only meaningful when jc_active(). End the launch with job_wait_fg() or
* job_end_bg().
*
* @param n The command, used for the listing text.
* @param fg Whether the job is to own the terminal.
* @return The job.
*/
job *job_begin(const node *n, bool fg) {
job *j = job_new(node_text(n));
job_launching = j;
launching_fg = fg;
return j;
}
/**
* @brief The process group a process being created now should join.
* @return The group ID. 0 means "start a new group". -1 means "leave it
* alone" (no job is being launched).
*/
pid_t job_launch_pgid(void) {
return job_launching ? job_launching->pgid : -1;
}
/**
* @brief Set up a freshly forked child as a member of the job being
* launched.
*
* The child joins (or founds) the job's process group and, for a
* foreground job, takes the terminal. This must run while SIGTTOU is
* still ignored, that is before trap_reset_child().
*/
void job_child_setup(void) {
pid_t pgid = job_launching->pgid ? job_launching->pgid : getpid();
setpgid(0, pgid);
if (launching_fg)
tcsetpgrp(tty_fd, pgid);
}
/**
* @brief Finish launching a foreground job and wait for it.
*
* The job is given the terminal and waited for until every process has
* exited or the job has stopped. The shell then takes the terminal back.
* A stopped job is announced and stays in the table. Otherwise call
* job_release() once the per-process statuses have been read.
*
* @param j The job.
* @return The exit status of the job's last process. 128 plus the signal
* number if the job stopped or was killed.
*/
int job_wait_fg(job *j) {
job_launching = nullptr;
if (!j->nprocs)
return 0;
if (jc_on && j->pgid) {
tcsetpgrp(tty_fd, j->pgid);
/* The child may have touched the terminal before it owned it. */
if (!sys_spawn_gives_tty())
kill(-j->pgid, SIGCONT);
}
for (;;) {
proc *p = nullptr;
for (int i = 0; i < j->nprocs && !p; i++) {
if (!j->procs[i].done && !j->procs[i].stopped)
p = &j->procs[i];
}
if (!p)
break;
int wstatus;
if (waitpid(p->pid, &wstatus, jc_on ? WUNTRACED : 0) < 0) {
if (errno == EINTR)
continue;
p->done = true;
p->status = 127;
continue;
}
proc_update(p, wstatus);
}
if (jc_on && j->pgid)
tcsetpgrp(tty_fd, shell_pgid);
const proc *last = &j->procs[j->nprocs - 1];
if (job_get_state(j) == JOB_STOPPED) {
if (have_tmodes)
tcsetattr(tty_fd, TCSADRAIN, &shell_tmodes);
j->announce = false;
out_putc(&out2, '\n');
job_print(&out2, j, 0);
out_flush(&out2);
return last->status;
}
int sig = 0;
bool interrupted = false;
for (int i = 0; i < j->nprocs; i++) {
if (j->procs[i].sig == SIGINT)
interrupted = true;
else if (j->procs[i].sig)
sig = j->procs[i].sig;
}
if (jc_on) {
if (sig || interrupted) {
if (have_tmodes)
tcsetattr(tty_fd, TCSADRAIN, &shell_tmodes);
} else {
have_tmodes = tcgetattr(tty_fd, &shell_tmodes) == 0;
}
}
if (sig)
report_signal(sig);
/*
* ^C went to the job, not to the shell. Tell the shell about it so
* that the rest of the command line is abandoned, as it would be
* without job control.
*/
if (interrupted && jc_on)
trap_note(SIGINT);
return last->status;
}
/**
* @brief Exit status of one process of a job that has been waited for.
* @param j The job.
* @param pid The process.
* @return Its status, or 127 if it is not part of the job.
*/
int job_status_of(const job *j, pid_t pid) {
for (int i = 0; i < j->nprocs; i++) {
if (j->procs[i].pid == pid)
return j->procs[i].status;
}
return 127;
}
/**
* @brief Let go of a foreground job: free it unless it is stopped.
* @param j The job.
*/
void job_release(job *j) {
if (job_launching == j)
job_launching = nullptr;
if (!j->nprocs || job_get_state(j) == JOB_DONE)
job_free(j);
}
/**
* @brief Finish launching a background job under job control.
*
* Sets `$!` and prints `[N] pid` in an interactive shell.
*
* @param j The job.
*/
void job_end_bg(job *j) {
job_launching = nullptr;
if (!j->nprocs) {
job_free(j);
return;
}
last_bg_pid = j->procs[j->nprocs - 1].pid;
if (opt.interactive) {
out_printf(&out2, "[%d] %ld\n", j->id, (long)last_bg_pid);
out_flush(&out2);
}
}
/* ---- job specifications ---------------------------------------------- */
/**
* @brief Find the job a `%` specification names.
*
* `%N` is job number N. `%%`, `%+` and `%` the current job. `%-` the
* previous job. `%text` a job whose command starts with `text`. `%?text`
* a job whose command contains `text`. nullptr selects the current job.
*
* @param spec The specification, or nullptr.
* @return The job, or nullptr if there is no such job.
*/
static job *job_find(const char *spec) {
if (!spec || !strcmp(spec, "%") || !strcmp(spec, "%%") ||
!strcmp(spec, "%+"))
return job_list;
if (!strcmp(spec, "%-"))
return job_list ? job_list->next : nullptr;
if (spec[0] != '%')
return nullptr;
spec++;
long id;
if (parse_long(spec, &id)) {
for (job *j = job_list; j; j = j->next) {
if (j->id == id)
return j;
}
return nullptr;
}
bool anywhere = spec[0] == '?';
if (anywhere)
spec++;
size_t len = strlen(spec);
for (job *j = job_list; j; j = j->next) {
if (!j->text)
continue;
if (anywhere ? strstr(j->text, spec) != nullptr
: !strncmp(j->text, spec, len))
return j;
}
return nullptr;
}
/**
* @brief Send a signal to every process of a job (for `kill %N`).
* @param spec Job specification.
* @param sig Signal number.
* @return 0 on success, -1 with errno set (ESRCH for an unknown job).
*/
int job_signal(const char *spec, int sig) {
job *j = job_find(spec);
if (!j) {
errno = ESRCH;
return -1;
}
if (j->pgid) {
int rc = kill(-j->pgid, sig);
/* A stopped job cannot act on the signal until it is continued. */
if (rc == 0 && (sig == SIGTERM || sig == SIGHUP || sig == SIGCONT)) {
for (int i = 0; i < j->nprocs; i++)
j->procs[i].stopped = false;
if (sig != SIGCONT)
kill(-j->pgid, SIGCONT);
}
return rc;
}
int rc = 0;
for (int i = 0; i < j->nprocs; i++) {
if (!j->procs[i].done && kill(j->procs[i].pid, sig) < 0)
rc = -1;
}
return rc;
}
/**
* @brief Block until a job has finished (or stopped).
* @param j The job.
* @return Status of its last process, or 128 plus a signal number if a
* trapped signal interrupted the wait.
*/
static int job_wait(job *j) {
for (int i = 0; i < j->nprocs; i++) {
proc *p = &j->procs[i];
int wstatus;
while (!p->done && !p->stopped) {
if (waitpid(p->pid, &wstatus, jc_on ? WUNTRACED : 0) < 0) {
if (errno != EINTR) {
p->done = true;
p->status = 127;
} else if (trap_pending) {
return 128 + (int)trap_pending;
}
continue;
}
proc_update(p, wstatus);
}
}
return j->procs[j->nprocs - 1].status;
}
/* ---- builtins -------------------------------------------------------- */
/**
* @brief The `wait` builtin: `wait [pid | %job] ...`.
*
* With no operands, waits for every background job and returns 0. With
* operands, returns the status of the last one named. 127 for a process
* that is not a child of this shell.
*/
int builtin_wait(int argc, char **argv) {
int i = 1;
if (i < argc && !strcmp(argv[i], "--"))
i++;
if (i >= argc) {
for (job *j = job_list, *next; j; j = next) {
next = j->next;
if (job_get_state(j) == JOB_STOPPED)
continue;
int status = job_wait(j);
if (job_get_state(j) == JOB_RUNNING)
return status; /* interrupted by a trapped signal */
if (job_get_state(j) == JOB_DONE)
job_free(j);
}
reaped_n = 0;
return 0;
}
int status = 0;
for (; i < argc; i++) {
job *j = nullptr;
long pid = 0;
if (argv[i][0] == '%') {
j = job_find(argv[i]);
} else {
if (!parse_long(argv[i], &pid)) {
sh_warn("wait: %s: bad process id", argv[i]);
return 2;
}
for (job *o = job_list; o && !j; o = o->next) {
for (int k = 0; k < o->nprocs && !j; k++) {
if (o->procs[k].pid == pid)
j = o;
}
}
}
if (!j) {
if (!reaped_find(pid, &status))
status = 127;
continue;
}
status = job_wait(j);
if (job_get_state(j) == JOB_RUNNING)
return status; /* interrupted by a trapped signal */
if (job_get_state(j) == JOB_DONE) {
reaped_add(j->procs[j->nprocs - 1].pid, status);
job_free(j);
}
}
return status;
}
/**
* @brief The `jobs` builtin: `jobs [-l | -p] [%job ...]`.
* @return 0, or 1 if a named job does not exist.
*/
int builtin_jobs(int argc, char **argv) {
unsigned flags = 0;
int i = 1;
for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
if (!strcmp(argv[i], "-l"))
flags = JP_LONG;
else if (!strcmp(argv[i], "-p"))
flags = JP_PIDS;
else if (!strcmp(argv[i], "--")) {
i++;
break;
} else {
sh_warn("jobs: %s: bad option", argv[i]);
return 2;
}
}
jobs_reap();
int status = 0;
if (i < argc) {
for (; i < argc; i++) {
const job *j = job_find(argv[i]);
if (j) {
job_print(&out1, j, flags);
} else {
sh_warn("jobs: %s: no such job", argv[i]);
status = 1;
}
}
return status;
}
/* Oldest first, which is the reverse of the table. */
int n = 0;
for (const job *j = job_list; j; j = j->next)
n++;
job **order = arena_alloc(&scratch, ((size_t)n + 1) * sizeof *order);
int k = n;
for (job *j = job_list; j; j = j->next)
order[--k] = j;
for (k = 0; k < n; k++) {
job *j = order[k];
job_print(&out1, j, flags);
}
return 0;
}
/**
* @brief Move a job to the head of the table, making it the current job.
* @param j The job.
*/
static void job_make_current(job *j) {
if (job_list == j)
return;
for (job **pj = &job_list; *pj; pj = &(*pj)->next) {
if (*pj == j) {
*pj = j->next;
break;
}
}
j->next = job_list;
job_list = j;
}
/**
* @brief Send SIGCONT to a job and mark its processes as running.
* @param j The job.
*/
static void job_continue(job *j) {
for (int i = 0; i < j->nprocs; i++)
j->procs[i].stopped = false;
if (j->pgid)
kill(-j->pgid, SIGCONT);
}
/**
* @brief The `fg` builtin: `fg [%job]`.
*
* Moves a job to the foreground, continuing it if it was stopped, and
* waits for it.
*
* @return The job's exit status. 1 if there is no such job. 2 if job
* control is off.
*/
int builtin_fg(int argc, char **argv) {
if (!jc_on) {
sh_warn("fg: no job control");
return 2;
}
int i = 1;
if (i < argc && !strcmp(argv[i], "--"))
i++;
jobs_reap();
job *j = job_find(i < argc ? argv[i] : nullptr);
if (!j || job_get_state(j) == JOB_DONE) {
sh_warn("fg: %s: no such job", i < argc ? argv[i] : "current");
return 1;
}
job_make_current(j);
out_printf(&out1, "%s\n", j->text ? j->text : "");
out_flush(&out1);
launching_fg = true;
if (j->pgid)
tcsetpgrp(tty_fd, j->pgid);
job_continue(j);
int status = job_wait_fg(j);
job_release(j);
return status;
}
/**
* @brief The `bg` builtin: `bg [%job ...]`.
*
* Continues stopped jobs in the background.
*
* @return 0, 1 if a job does not exist, 2 if job control is off.
*/
int builtin_bg(int argc, char **argv) {
if (!jc_on) {
sh_warn("bg: no job control");
return 2;
}
int status = 0;
int i = 1;
if (i < argc && !strcmp(argv[i], "--"))
i++;
jobs_reap();
do {
job *j = job_find(i < argc ? argv[i] : nullptr);
if (!j || job_get_state(j) == JOB_DONE) {
sh_warn("bg: %s: no such job", i < argc ? argv[i] : "current");
status = 1;
continue;
}
job_continue(j);
out_printf(&out1, "[%d] %s &\n", j->id, j->text ? j->text : "");
} while (++i < argc);
return status;
}
|