-
Notifications
You must be signed in to change notification settings - Fork 30
/
job.c
1460 lines (1317 loc) · 46.5 KB
/
job.c
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
/* Yash: yet another shell */
/* job.c: job control */
/* (C) 2007-2024 magicant */
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "common.h"
#include "job.h"
#include <assert.h>
#include <errno.h>
#if HAVE_GETTEXT
# include <libintl.h>
#endif
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>
#include "builtin.h"
#include "exec.h"
#include "option.h"
#include "plist.h"
#include "redir.h"
#include "sig.h"
#include "strbuf.h"
#include "util.h"
#include "yash.h"
#if YASH_ENABLE_LINEEDIT
# include "xfnmatch.h"
# include "lineedit/complete.h"
# ifndef FG_DONT_SAVE_TERMINAL
# include "lineedit/terminfo.h"
# endif
#endif
static inline job_T *get_job(size_t jobnumber)
__attribute__((pure));
static inline void free_job(job_T *job);
static void trim_joblist(void);
static void set_current_jobnumber(size_t jobnumber);
static size_t find_next_job(size_t numlimit);
static void apply_curstop(void);
static int calc_status(int status)
__attribute__((const));
static inline int calc_status_of_process(const process_T *p)
__attribute__((nonnull,pure));
static wchar_t *get_job_name(const job_T *job)
__attribute__((nonnull,warn_unused_result));
static char *get_process_status_string(const process_T *p, bool *needfree)
__attribute__((nonnull,malloc,warn_unused_result));
static char *get_job_status_string(const job_T *job, bool *needfree)
__attribute__((nonnull,malloc,warn_unused_result));
static int print_job_status(size_t jobnumber,
bool changedonly, bool verbose, bool remove_done, FILE *f)
__attribute__((nonnull));
static size_t get_jobnumber_from_name(const wchar_t *name)
__attribute__((nonnull,pure));
static size_t get_jobnumber_from_pid(long pid)
__attribute__((pure));
static bool jobs_builtin_print_job(size_t jobnumber,
bool verbose, bool changedonly, bool pgidonly,
bool runningonly, bool stoppedonly);
static int continue_job(size_t jobnumber, job_T *job, bool fg)
__attribute__((nonnull));
static int wait_for_job_by_jobspec(const wchar_t *jobspec)
__attribute__((nonnull));
static bool wait_builtin_has_job(bool jobcontrol);
/* The list of jobs.
* `joblist.contents[ACTIVE_JOBNO]' is a special job that is called "active
* job", the job that is currently being executed.
* The list length is always non-zero. */
static plist_T joblist;
/* number of the current/previous jobs. 0 if none. */
static size_t current_jobnumber, previous_jobnumber;
/* Initializes the job list. */
void init_job(void)
{
assert(joblist.contents == NULL);
pl_init(&joblist);
pl_add(&joblist, NULL);
}
/* Sets the active job. */
void set_active_job(job_T *job)
{
assert(ACTIVE_JOBNO < joblist.length);
assert(joblist.contents[ACTIVE_JOBNO] == NULL);
joblist.contents[ACTIVE_JOBNO] = job;
}
/* Moves the active job into the job list.
* If the newly added job is stopped, it becomes the current job.
* If `current' is true or there is no current job, the newly added job becomes
* the current job if there is no stopped job. */
void add_job(bool current)
{
job_T *job = joblist.contents[ACTIVE_JOBNO];
size_t jobnumber;
assert(job != NULL);
joblist.contents[ACTIVE_JOBNO] = NULL;
/* if there is an empty element in the list, use it */
for (jobnumber = 1; jobnumber < joblist.length; jobnumber++) {
if (joblist.contents[jobnumber] == NULL) {
joblist.contents[jobnumber] = job;
goto set_current;
}
}
/* if there is no empty, append at the end of the list */
pl_add(&joblist, job);
set_current:
assert(joblist.contents[jobnumber] == job);
if (job->j_status == JS_STOPPED || current)
set_current_jobnumber(jobnumber);
else
set_current_jobnumber(current_jobnumber);
}
/* Returns the job of the specified number or NULL if not found. */
job_T *get_job(size_t jobnumber)
{
return (jobnumber < joblist.length) ? joblist.contents[jobnumber] : NULL;
}
/* Removes the job of the specified number.
* If the job is the current/previous job, the current/previous job is reset
* (another job is assigned to it). */
void remove_job(size_t jobnumber)
{
free_job(get_job(jobnumber));
joblist.contents[jobnumber] = NULL;
trim_joblist();
set_current_jobnumber(current_jobnumber);
}
/* Removes all jobs unconditionally. */
void remove_all_jobs(void)
{
for (size_t i = 0; i < joblist.length; i++) {
free_job(joblist.contents[i]);
joblist.contents[i] = NULL;
}
trim_joblist();
current_jobnumber = previous_jobnumber = 0;
}
/* Frees the specified job. */
void free_job(job_T *job)
{
if (job != NULL) {
for (size_t i = 0; i < job->j_pcount; i++)
free(job->j_procs[i].pr_name);
free(job);
}
}
/* Shrink the job list, removing unused elements. */
void trim_joblist(void)
{
if (joblist.maxlength > 20 && joblist.maxlength / 2 > joblist.length) {
pl_setmax(&joblist, joblist.length * 2);
} else {
size_t tail = joblist.length;
while (tail > 1 && joblist.contents[tail - 1] == NULL)
tail--;
assert(tail > 0);
pl_truncate(&joblist, tail);
}
}
/* Sets the `j_legacy' flags of all jobs.
* All the jobs will be no longer job-controlled. */
void neglect_all_jobs(void)
{
for (size_t i = 0; i < joblist.length; i++) {
job_T *job = joblist.contents[i];
if (job != NULL)
job->j_legacy = true;
}
current_jobnumber = previous_jobnumber = 0;
}
/* Current/previous job selection discipline:
*
* - When there is one or more stopped jobs, the current job must be one of
* them.
* - When there are more than one stopped job, the previous job must be one of
* them but the current one.
* - The current job becomes the previous job when another job becomes the
* current.
*
* - When a foreground job is stopped, it becomes the current job.
* - When an asynchronous command is executed and the "curasync" option is set,
* it becomes the current job.
* - When a job is continued by the "bg" command and the "curbg" option is set,
* it becomes the current job.
* - When a job is stopped and the "curstop" option is set, it becomes the
* current job.
*
* - The "wait" command doesn't change the current and previous jobs. */
/* Sets the current job number to the specified one and resets the previous job
* number. If the specified job number is not used, a job is arbitrarily chosen
* for the current. If there is one or more stopped jobs and the one specified
* by the argument is not stopped, the current job is not changed. */
/* This function must be called whenever a job is added to or removed from the
* job list or any job's status has been changed. */
void set_current_jobnumber(size_t jobnumber)
{
size_t stopcount = stopped_job_count();
const job_T *newcurrent = get_job(jobnumber);
if (newcurrent == NULL
|| (stopcount > 0 && newcurrent->j_status != JS_STOPPED)) {
jobnumber = current_jobnumber;
newcurrent = get_job(jobnumber);
if (newcurrent == NULL
|| (stopcount > 0 && newcurrent->j_status != JS_STOPPED)) {
jobnumber = previous_jobnumber;
newcurrent = get_job(jobnumber);
if (newcurrent == NULL
|| (stopcount > 0 && newcurrent->j_status != JS_STOPPED))
jobnumber = find_next_job(ACTIVE_JOBNO);
}
}
if (jobnumber != current_jobnumber) {
size_t oldcurrentnum = current_jobnumber;
current_jobnumber = jobnumber;
jobnumber = oldcurrentnum;
} else {
jobnumber = previous_jobnumber;
}
const job_T *newprevious = get_job(jobnumber);
if (newprevious == NULL || jobnumber == current_jobnumber
|| (stopcount > 1 && newprevious->j_status != JS_STOPPED)) {
jobnumber = previous_jobnumber;
newprevious = get_job(jobnumber);
if (newprevious == NULL || jobnumber == current_jobnumber
|| (stopcount > 1 && newprevious->j_status != JS_STOPPED))
jobnumber = find_next_job(current_jobnumber);
}
previous_jobnumber = jobnumber;
}
/* Returns an arbitrary job number except the specified.
* The returned number is suitable for the current/previous jobs.
* If there is no job to pick out, 0 is returned.
* Stopped jobs are preferred to running/finished jobs.
* If there are more than one stopped jobs, the previous job is preferred. */
size_t find_next_job(size_t excl)
{
if (previous_jobnumber != excl) {
job_T *job = get_job(previous_jobnumber);
if (job != NULL && job->j_status == JS_STOPPED)
return previous_jobnumber;
}
size_t jobnumber = joblist.length;
while (--jobnumber > 0) {
if (jobnumber != excl) {
job_T *job = get_job(jobnumber);
if (job != NULL && job->j_status == JS_STOPPED)
return jobnumber;
}
}
jobnumber = joblist.length;
while (--jobnumber > 0) {
if (jobnumber != excl) {
job_T *job = get_job(jobnumber);
if (job != NULL)
return jobnumber;
}
}
return 0;
}
/* If the "curstop" option is set and there is a job which has been stopped and
* whose `j_statuschanged' flag is set, make it the current job. */
void apply_curstop(void)
{
if (shopt_curstop) {
for (size_t i = 0; i < joblist.length; i++) {
job_T *job = joblist.contents[i];
if (job != NULL)
if (job->j_status == JS_STOPPED && job->j_statuschanged)
set_current_jobnumber(i);
}
}
set_current_jobnumber(current_jobnumber);
}
/* Counts the number of jobs in the job list. */
size_t job_count(void)
{
size_t count = 0;
for (size_t i = 0; i < joblist.length; i++) {
const job_T *job = joblist.contents[i];
if (job == NULL)
continue;
if (job->j_status == JS_DONE && !job->j_statuschanged)
continue; // Ignore finished jobs that have already been reported.
count++;
}
return count;
}
/* Counts the number of stopped jobs in the job list. */
size_t stopped_job_count(void)
{
size_t count = 0;
for (size_t i = 0; i < joblist.length; i++) {
job_T *job = joblist.contents[i];
if (job != NULL && job->j_status == JS_STOPPED)
count++;
}
return count;
}
/* Updates the info about the jobs in the job list.
* This function doesn't block. */
void do_wait(void)
{
pid_t pid;
int status;
#if HAVE_WCONTINUED
static int waitpidoption = WUNTRACED | WCONTINUED | WNOHANG;
#else
const int waitpidoption = WUNTRACED | WNOHANG;
#endif
start:
pid = waitpid(-1, &status, waitpidoption);
if (pid < 0) {
switch (errno) {
case EINTR:
goto start; /* try again */
case ECHILD:
return; /* there are no child processes */
#if HAVE_WCONTINUED
/* Even when the WCONTINUED flag is defined in the <sys/wait.h>
* header, the OS kernel may not support it. We try again without
* the flag if it is rejected. */
case EINVAL:
if (waitpidoption & WCONTINUED) {
waitpidoption &= ~WCONTINUED;
goto start;
}
#endif
; /* falls thru! */
default:
xerror(errno, "waitpid");
return;
}
} else if (pid == 0) {
/* no more jobs to be updated */
return;
}
size_t jobnumber, pnumber;
job_T *job;
process_T *pr;
/* determine `jobnumber', `job' and `pr' from `pid' */
for (jobnumber = 0; jobnumber < joblist.length; jobnumber++)
if ((job = joblist.contents[jobnumber]) != NULL)
for (pnumber = 0; pnumber < job->j_pcount; pnumber++)
if ((pr = &job->j_procs[pnumber])->pr_pid == pid &&
pr->pr_status != JS_DONE)
goto found;
/* If `pid' was not found in the job list, we simply ignore it. This may
* happen on some occasions: e.g. the job has been "disown"ed. */
goto start;
found:
pr->pr_statuscode = status;
if (WIFEXITED(status) || WIFSIGNALED(status))
pr->pr_status = JS_DONE;
if (WIFSTOPPED(status))
pr->pr_status = JS_STOPPED;
#ifdef HAVE_WCONTINUED
if (WIFCONTINUED(status))
pr->pr_status = JS_RUNNING;
/* On FreeBSD, when WIFCONTINUED is true, WIFSIGNALED is also true. We must
* be careful about the order of these checks. */
#endif
/* decide the job status from the process status:
* - JS_RUNNING if any of the processes is running.
* - JS_STOPPED if no processes are running but some are stopped.
* - JS_DONE if all the processes are finished. */
jobstatus_T oldstatus = job->j_status;
bool anyrunning = false, anystopped = false;
/* check if there are running/stopped processes */
for (size_t i = 0; i < job->j_pcount; i++) {
switch (job->j_procs[i].pr_status) {
case JS_RUNNING: anyrunning = true; goto out_of_loop;
case JS_STOPPED: anystopped = true; break;
default: break;
}
}
out_of_loop:
job->j_status = anyrunning ? JS_RUNNING : anystopped ? JS_STOPPED : JS_DONE;
if (job->j_status != oldstatus)
job->j_statuschanged = true;
goto start;
}
/* Waits for the specified job to finish (or stop).
* `jobnumber' must be a valid job number.
* If `return_on_stop' is false, waits for the job to finish.
* Otherwise, waits for the job to finish or stop.
* If `interruptible' is true, this function can be canceled by SIGINT.
* If `return_on_trap' is true, this function returns false immediately after
* trap actions are performed. Otherwise, traps are not handled.
* This function returns immediately if the job is already finished/stopped or
* is not a child of this shell process.
* Returns the signal number if interrupted, or zero if successful. */
/* In most cases, you should call `put_foreground' to bring the shell back to
* foreground after calling `wait_for_job' if `doing_job_control_now' is true.
*/
int wait_for_job(size_t jobnumber, bool return_on_stop,
bool interruptible, bool return_on_trap)
{
int signum = 0;
job_T *job = joblist.contents[jobnumber];
if (!job->j_legacy) {
bool savenonotify = job->j_nonotify;
job->j_nonotify = true;
for (;;) {
if (job->j_status == JS_DONE)
break;
if (return_on_stop && job->j_status == JS_STOPPED)
break;
signum = wait_for_sigchld(interruptible, return_on_trap);
if (signum != 0)
break;
}
job->j_nonotify = savenonotify;
}
return signum;
}
/* Waits for the specified child process to finish (or stop).
* `cpid' is the process ID of the child process to wait for. This must not be
* in the job list.
* `cpgid' is the process group ID of the child. If the child's PGID is the same
* as that of the parent, `cpgid' must be 0.
* If `return_on_stop' is false, waits for the job to finish.
* Otherwise, waits for the job to finish or stop.
* Traps are not handled in this function.
* There must be no active job when this function is called.
* If `return_on_stop' is true and the child is stopped, this function returns
* a pointer to a pointer to a wide string. The caller must assign a pointer to
* a newly malloced wide string to the variable the return value points to.
* This string is used as the name of the new stopped job.
* If the child exited, this function returns NULL.
* The exit status is assigned to `laststatus' in any case. */
wchar_t **wait_for_child(pid_t cpid, pid_t cpgid, bool return_on_stop)
{
job_T *job = xmalloc(add(sizeof *job, sizeof *job->j_procs));
job->j_pgid = cpgid;
job->j_status = JS_RUNNING;
job->j_statuschanged = false;
job->j_legacy = false;
job->j_nonotify = false;
job->j_pcount = 1;
job->j_procs[0].pr_pid = cpid;
job->j_procs[0].pr_status = JS_RUNNING;
job->j_procs[0].pr_statuscode = 0;
job->j_procs[0].pr_name = NULL;
set_active_job(job);
wait_for_job(ACTIVE_JOBNO, return_on_stop, false, false);
if (doing_job_control_now)
put_foreground(shell_pgid);
laststatus = calc_status_of_job(job);
if (job->j_status == JS_DONE) {
notify_signaled_job(ACTIVE_JOBNO);
remove_job(ACTIVE_JOBNO);
return NULL;
} else {
add_job(true);
return &job->j_procs[0].pr_name;
}
}
/* Returns the process group ID of the specified job.
* If no valid job is found, an error message is printed and -1 is returned.
* `jobname' may have a preceding '%' sign. */
pid_t get_job_pgid(const wchar_t *jobname)
{
size_t jobnumber = get_jobnumber_from_name(
(jobname[0] == L'%') ? &jobname[1] : jobname);
const job_T *job;
if (jobnumber >= joblist.length) {
xerror(0, Ngt("job specification `%ls' is ambiguous"), jobname);
return -1;
} else if (jobnumber == 0
|| (job = joblist.contents[jobnumber]) == NULL
|| job->j_legacy) {
xerror(0, Ngt("no such job `%ls'"), jobname);
return -1;
} else if (job->j_pgid == 0) {
xerror(0, Ngt("`%ls' is not a job-controlled job"), jobname);
return -1;
} else {
return job->j_pgid;
}
}
/* Puts the specified process group in the foreground.
* `pgrp' must be a valid process group ID and `doing_job_control_now' must be
* true. */
void put_foreground(pid_t pgrp)
{
sigset_t blockss, savess;
assert(doing_job_control_now);
assert(pgrp > 0);
sigemptyset(&blockss);
sigaddset(&blockss, SIGTTOU);
sigemptyset(&savess);
sigprocmask(SIG_BLOCK, &blockss, &savess);
tcsetpgrp(ttyfd, pgrp);
sigprocmask(SIG_SETMASK, &savess, NULL);
}
/* Ensures the current shell process is in the foreground.
* The shell process is stopped by SIGTTOU until it is put in the foreground.
* This function requires `doing_job_control_now' to be true. */
/* This function prevents the job-control shell from mangling the terminal while
* another shell is using it. */
void ensure_foreground(void)
{
/* This function calls `tcsetpgrp' with the default SIGTTOU handler. If the
* shell is in the background, it will receive SIGTTOU and get stopped until
* it is continued in the foreground. */
struct sigaction dflsa, savesa;
sigset_t blockss, savess;
assert(doing_job_control_now);
assert(shell_pgid > 0);
dflsa.sa_handler = SIG_DFL;
dflsa.sa_flags = 0;
sigemptyset(&dflsa.sa_mask);
sigemptyset(&savesa.sa_mask);
sigaction(SIGTTOU, &dflsa, &savesa);
sigemptyset(&blockss);
sigaddset(&blockss, SIGTTOU);
sigemptyset(&savess);
sigprocmask(SIG_UNBLOCK, &blockss, &savess);
tcsetpgrp(ttyfd, shell_pgid);
sigprocmask(SIG_SETMASK, &savess, NULL);
sigaction(SIGTTOU, &savesa, NULL);
}
/* Computes the exit status from the status code returned by `waitpid'. */
int calc_status(int status)
{
if (WIFEXITED(status))
return WEXITSTATUS(status);
#ifdef WIFCONTINUED
if (WIFCONTINUED(status))
return Exit_SUCCESS;
/* On FreeBSD, when WIFCONTINUED is true, WIFSIGNALED is also true. We must
* be careful about the order of these checks. */
#endif
if (WIFSIGNALED(status))
return WTERMSIG(status) + TERMSIGOFFSET;
if (WIFSTOPPED(status))
return WSTOPSIG(status) + TERMSIGOFFSET;
assert(false);
}
/* Computes the exit status of the specified process.
* The process state must be JS_DONE or JS_STOPPED. */
int calc_status_of_process(const process_T *p)
{
int s = p->pr_statuscode;
return (p->pr_pid == 0) ? s : calc_status(s);
}
/* Computes the exit status of the specified job.
* The job state must be JS_DONE or JS_STOPPED. */
int calc_status_of_job(const job_T *job)
{
switch (job->j_status) {
case JS_DONE:
if (!shopt_pipefail)
return calc_status_of_process(&job->j_procs[job->j_pcount - 1]);
for (size_t i = job->j_pcount; i-- > 0; ) {
int status = calc_status_of_process(&job->j_procs[i]);
if (status != Exit_SUCCESS)
return status;
}
return Exit_SUCCESS;
case JS_STOPPED:
for (size_t i = job->j_pcount; i-- > 0; ) {
if (job->j_procs[i].pr_status == JS_STOPPED)
return calc_status(job->j_procs[i].pr_statuscode);
}
/* falls thru! */
default:
assert(false);
}
}
/* Returns the name of the specified job.
* If the job has only one process, `job->j_procs[0].pr_name' is returned.
* Otherwise, the names of all the process are concatenated and returned, which
* must be freed by the caller. */
wchar_t *get_job_name(const job_T *job)
{
if (job->j_pcount == 1)
return job->j_procs[0].pr_name;
xwcsbuf_T buf;
wb_init(&buf);
for (size_t i = 0; i < job->j_pcount; i++) {
if (i > 0)
wb_cat(&buf, L" | ");
wb_cat(&buf, job->j_procs[i].pr_name);
}
return wb_towcs(&buf);
}
/* Returns a string that describes the status of the specified process
* such as "Running" and "Stopped(SIGTSTP)".
* The returned string must be freed by the caller iff `*needfree' is assigned
* true, otherwise it must not be modified or freed. */
char *get_process_status_string(const process_T *p, bool *needfree)
{
int status, sig;
switch (p->pr_status) {
case JS_RUNNING:
*needfree = false;
return (char *) gt("Running");
case JS_STOPPED:
*needfree = true;
return malloc_printf(gt("Stopped(SIG%ls)"),
get_signal_name(WSTOPSIG(p->pr_statuscode)));
case JS_DONE:
status = p->pr_statuscode;
if (p->pr_pid == 0)
goto exitstatus;
if (WIFEXITED(status)) {
status = WEXITSTATUS(status);
exitstatus:
if (status == Exit_SUCCESS) {
*needfree = false;
return (char *) gt("Done");
} else {
*needfree = true;
return malloc_printf(gt("Done(%d)"), status);
}
} else {
assert(WIFSIGNALED(status));
*needfree = true;
sig = WTERMSIG(status);
#ifdef WCOREDUMP
if (WCOREDUMP(sig))
return malloc_printf(gt("Killed (SIG%ls: core dumped)"),
get_signal_name(sig));
#endif
return malloc_printf(gt("Killed (SIG%ls)"), get_signal_name(sig));
}
}
assert(false);
}
/* Returns a string that describes the status of the specified job
* such as "Running" and "Stopped(SIGTSTP)".
* The returned string must be freed by the caller iff `*needfree' is assigned
* true, otherwise it must not be modified or freed. */
char *get_job_status_string(const job_T *job, bool *needfree)
{
switch (job->j_status) {
case JS_RUNNING:
*needfree = false;
return (char *) gt("Running");
case JS_STOPPED:
/* find a stopped process */
for (size_t i = job->j_pcount; ; )
if (job->j_procs[--i].pr_status == JS_STOPPED)
return get_process_status_string(&job->j_procs[i], needfree);
assert(false);
case JS_DONE:
return get_process_status_string(
&job->j_procs[job->j_pcount - 1], needfree);
}
assert(false);
}
/* Returns true iff there is any job whose status has been changed but not yet
* reported. If this function returns false, `print_job_status_all' is nop. */
bool any_job_status_has_changed(void)
{
for (size_t i = 1; i < joblist.length; i++) {
const job_T *job = get_job(i);
if (job != NULL && !job->j_nonotify && job->j_statuschanged)
return true;
}
return false;
}
/* Prints the status of the specified job.
* If `remove_done' is true, finished jobs are removed from the job list after
* the status is printed.
* If the specified job doesn't exist, nothing is printed (it isn't an error).
* If `changedonly' is true, the job is printed only if the `j_statuschanged'
* flag is true.
* If `verbose' is true, the status is printed in the process-wise format rather
* than the usual job-wise format.
* Returns zero if successful. Returns errno if `fprintf' failed. */
int print_job_status(size_t jobnumber,
bool changedonly, bool verbose, bool remove_done, FILE *f)
{
int result = 0;
job_T *job = get_job(jobnumber);
if (job == NULL || job->j_nonotify)
return result;
if (changedonly && !job->j_statuschanged)
return result;
char current;
if (jobnumber == current_jobnumber) current = '+';
else if (jobnumber == previous_jobnumber) current = '-';
else current = ' ';
if (!verbose) {
bool needfree;
char *status = get_job_status_string(job, &needfree);
wchar_t *jobname = get_job_name(job);
/* TRANSLATORS: the translated format string can be different
* from the original only in the number of spaces. This is required
* for POSIX compliance. */
result = fprintf(f, gt("[%zu] %c %-20s %ls\n"),
jobnumber, current, status, jobname);
result = (result >= 0) ? 0 : errno;
if (needfree)
free(status);
if (jobname != job->j_procs[0].pr_name)
free(jobname);
} else {
bool needfree;
pid_t pid = job->j_procs[0].pr_pid;
char *status = get_process_status_string(
&job->j_procs[posixly_correct ? job->j_pcount - 1 : 0],
&needfree);
wchar_t *jobname = job->j_procs[0].pr_name;
/* TRANSLATORS: the translated format string can be different
* from the original only in the number of spaces. This is required
* for POSIX compliance. */
result = fprintf(f, gt("[%zu] %c %5jd %-20s %ls\n"),
jobnumber, current, (intmax_t) pid, status, jobname);
result = (result >= 0) ? 0 : errno;
if (needfree)
free(status);
for (size_t i = 1; result == 0 && i < job->j_pcount; i++) {
pid = job->j_procs[i].pr_pid;
status = get_process_status_string(&job->j_procs[i], &needfree);
jobname = job->j_procs[i].pr_name;
/* TRANSLATORS: the translated format string can be different
* from the original only in the number of spaces. This is required
* for POSIX compliance. */
result = fprintf(f, gt(" %5jd %-20s | %ls\n"),
(intmax_t) pid, (posixly_correct ? "" : status), jobname);
result = (result >= 0) ? 0 : errno;
if (needfree)
free(status);
}
}
job->j_statuschanged = false;
if (remove_done && job->j_status == JS_DONE)
remove_job(jobnumber);
return result;
}
/* Prints the status of jobs which have been changed but not reported. */
void print_job_status_all(void)
{
apply_curstop();
for (size_t i = 1; i < joblist.length; i++)
print_job_status(i, true, false, false, stderr);
}
/* If the shell is interactive and the specified job has been killed by a
* signal other than SIGPIPE, prints a notification to the standard error.
* If the signal is SIGINT, only a single newline is printed to the standard
* error and the shell is flagged as interrupted. */
void notify_signaled_job(size_t jobnumber)
{
if (!is_interactive_now)
return;
job_T *job = get_job(jobnumber);
if (job == NULL || job->j_status != JS_DONE)
return;
process_T *p = &job->j_procs[job->j_pcount - 1];
assert(p->pr_status == JS_DONE);
if (p->pr_pid == 0 || !WIFSIGNALED(p->pr_statuscode))
return;
int sig = WTERMSIG(p->pr_statuscode);
switch (sig) {
case SIGINT:
fputc('\n', stderr);
set_interrupted();
break;
case SIGPIPE:
break;
default:
#if HAVE_STRSIGNAL
fprintf(stderr, gt("The process was killed by SIG%ls: %s\n"),
get_signal_name(sig), strsignal(sig));
#else
fprintf(stderr, gt("The process was killed by SIG%ls\n"),
get_signal_name(sig));
#endif
break;
}
}
/* Returns the job number from the specified job ID string.
* If no applicable job is found, zero is returned.
* If more than one jobs are found, `joblist.length' is returned.
* When `name' is a number, the number is returned if it is a valid job number.
* The string must not have the preceding '%'. */
/* "", "%", "+" -> the current job
* "-" -> the previous job
* "n" (integer) -> the job #n
* "xxx" -> the job whose name starts with "xxx"
* "?xxx" -> the job whose name contains "xxx" */
size_t get_jobnumber_from_name(const wchar_t *name)
{
if (name[0] == L'\0' || wcscmp(name, L"%") == 0 || wcscmp(name, L"+") == 0)
return current_jobnumber;
if (wcscmp(name, L"-") == 0)
return previous_jobnumber;
if (iswdigit(name[0])) {
unsigned long num;
if (xwcstoul(name, 10, &num))
return (num <= SIZE_MAX && get_job(num) != NULL) ? num : 0;
}
bool contain;
size_t n = 0;
if (name[0] == L'?') {
contain = true;
name++;
} else {
contain = false;
}
for (size_t i = 1; i < joblist.length; i++) {
job_T *job = joblist.contents[i];
if (job != NULL) {
wchar_t *jobname = get_job_name(job);
bool match = contain
? wcsstr(jobname, name) != NULL
: matchwcsprefix(jobname, name) != NULL;
if (jobname != job->j_procs[0].pr_name)
free(jobname);
if (match) {
if (n != 0)
return joblist.length; /* more than one found */
else
n = i;
}
}
}
return n;
}
/* Returns the number of job that contains a process whose process ID is `pid'.
* If not found, 0 is returned. */
size_t get_jobnumber_from_pid(long pid)
{
size_t jobnumber;
if (pid == 0)
return 0;
for (jobnumber = joblist.length; --jobnumber > 0; ) {
job_T *job = joblist.contents[jobnumber];
if (job != NULL) {
for (size_t i = 0; i < job->j_pcount; i++)
if (job->j_procs[i].pr_pid == pid)
goto found;
}
}
found:
return jobnumber;
}
#if YASH_ENABLE_LINEEDIT
/* Generates completion candidates for job names matching the pattern. */
/* The prototype of this function is declared in "lineedit/complete.h". */
void generate_job_candidates(const le_compopt_T *compopt)
{
if (!(compopt->type & CGT_JOB))
return;
le_compdebug("adding job candidates");
if (!le_compile_cpatterns(compopt))
return;
for (size_t i = 1; i < joblist.length; i++) {
const job_T *job = joblist.contents[i];
if (job == NULL)
continue;
switch (job->j_status) {
case JS_RUNNING:
if (!(compopt->type & CGT_RUNNING))
continue;
break;
case JS_STOPPED:
if (!(compopt->type & CGT_STOPPED))
continue;
break;
case JS_DONE:
if (!(compopt->type & CGT_DONE))
continue;
break;
}
wchar_t *jobname = get_job_name(job);
if (le_wmatch_comppatterns(compopt, jobname))
le_new_candidate(CT_JOB, xwcsdup(jobname),
malloc_wprintf(L"%%%zu", i), compopt);
if (jobname != job->j_procs[0].pr_name)
free(jobname);
}
}
#endif /* YASH_ENABLE_LINEEDIT */
/********** Built-ins **********/
/* Options for the "jobs" built-in. */
const struct xgetopt_T jobs_options[] = {
{ L'l', L"verbose", OPTARG_NONE, true, NULL, },
{ L'n', L"new", OPTARG_NONE, false, NULL, },
{ L'p', L"pgid-only", OPTARG_NONE, true, NULL, },
{ L'r', L"running-only", OPTARG_NONE, false, NULL, },
{ L's', L"stopped-only", OPTARG_NONE, false, NULL, },
#if YASH_ENABLE_HELP
{ L'-', L"help", OPTARG_NONE, false, NULL, },
#endif