~emersion/mrsh

ref: 4974d15d2d362675faf2903f2c7618fb974bdcd2 mrsh/shell/job.c -rw-r--r-- 12.0 KiB
4974d15dSimon Ser Simplify init_job_child_process 10 months ago
                                                                                
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
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <errno.h>
#include <mrsh/array.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "shell/job.h"
#include "shell/process.h"
#include "shell/shell.h"
#include "shell/task.h"

static const int ignored_signals[] = {
	SIGINT,
	SIGQUIT,
	SIGTSTP,
	SIGTTIN,
	SIGTTOU,
};

static const size_t IGNORED_SIGNALS_LEN =
	sizeof(ignored_signals) / sizeof(ignored_signals[0]);

bool mrsh_set_job_control(struct mrsh_state *state, bool enabled) {
	struct mrsh_state_priv *priv = state_get_priv(state);

	assert(priv->term_fd >= 0);

	if (priv->job_control == enabled) {
		return true;
	}

	if (enabled) {
		// Loop until we are in the foreground
		while (true) {
			pid_t pgid = getpgrp();
			if (tcgetpgrp(priv->term_fd) == pgid) {
				break;
			}
			kill(-pgid, SIGTTIN);
		}

		assert(priv->saved_sigactions == NULL);
		priv->saved_sigactions =
			malloc(IGNORED_SIGNALS_LEN * sizeof(struct sigaction));
		if (priv->saved_sigactions == NULL) {
			return false;
		}

		// Ignore interactive and job-control signals
		struct sigaction sa = { .sa_handler = SIG_IGN };
		sigemptyset(&sa.sa_mask);
		for (size_t i = 0; i < IGNORED_SIGNALS_LEN; ++i) {
			if (sigaction(ignored_signals[i], &sa,
					&priv->saved_sigactions[i]) != 0) {
				perror("sigaction");
				return false;
			}
		}

		// Put ourselves in our own process group, if we aren't the session
		// leader
		priv->pgid = getpid();
		if (getsid(0) != priv->pgid) {
			if (setpgid(priv->pgid, priv->pgid) != 0) {
				perror("setpgid");
				return false;
			}
		}

		// Grab control of the terminal
		if (tcsetpgrp(priv->term_fd, priv->pgid) != 0) {
			perror("tcsetpgrp");
			return false;
		}
		// Save default terminal attributes for the shell
		if (tcgetattr(priv->term_fd, &priv->term_modes) != 0) {
			perror("tcgetattr");
			return false;
		}
	} else {
		assert(priv->saved_sigactions != NULL);
		for (size_t i = 0; i < IGNORED_SIGNALS_LEN; ++i) {
			if (sigaction(ignored_signals[i],
					&priv->saved_sigactions[i], NULL) != 0) {
				perror("sigaction");
				return false;
			}
		}

		free(priv->saved_sigactions);
		priv->saved_sigactions = NULL;
	}

	priv->job_control = enabled;
	return true;
}

static void array_remove(struct mrsh_array *array, size_t i) {
	memmove(&array->data[i], &array->data[i + 1],
		(array->len - i - 1) * sizeof(void *));
	--array->len;
}

struct mrsh_job *job_create(struct mrsh_state *state,
		const struct mrsh_node *node) {
	struct mrsh_state_priv *priv = state_get_priv(state);

	int id = 1;
	for (size_t i = 0; i < priv->jobs.len; ++i) {
		struct mrsh_job *job = priv->jobs.data[i];
		if (id < job->job_id + 1) {
			id = job->job_id + 1;
		}
	}

	struct mrsh_job *job = calloc(1, sizeof(struct mrsh_job));
	job->state = state;
	job->node = mrsh_node_copy(node);
	job->pgid = -1;
	job->job_id = id;
	job->last_status = TASK_STATUS_WAIT;
	mrsh_array_add(&priv->jobs, job);
	return job;
}

void job_destroy(struct mrsh_job *job) {
	if (job == NULL) {
		return;
	}

	struct mrsh_state_priv *priv = state_get_priv(job->state);

	if (priv->foreground_job == job) {
		job_set_foreground(job, false, false);
	}

	for (size_t i = 0; i < priv->jobs.len; ++i) {
		if (priv->jobs.data[i] == job) {
			array_remove(&priv->jobs, i);
			break;
		}
	}

	for (size_t j = 0; j < job->processes.len; ++j) {
		process_destroy(job->processes.data[j]);
	}
	mrsh_array_finish(&job->processes);
	mrsh_node_destroy(job->node);
	free(job);
}

void job_add_process(struct mrsh_job *job, struct mrsh_process *proc) {
	if (job->pgid <= 0) {
		job->pgid = proc->pid;
	}
	// This can fail because we do it both in the parent and the child
	if (setpgid(proc->pid, job->pgid) != 0 && errno != EPERM) {
		perror("setpgid");
		return;
	}
	mrsh_array_add(&job->processes, proc);
}

static void queue_job_notifications(struct mrsh_state *state) {
	struct mrsh_state_priv *priv = state_get_priv(state);

	for (size_t i = 0; i < priv->jobs.len; ++i) {
		struct mrsh_job *job = priv->jobs.data[i];
		int status = job_poll(job);
		if (status != job->last_status && job->pgid > 0 &&
				priv->foreground_job != job) {
			job->pending_notification = true;
		}
		job->last_status = status;
	}
}

bool job_set_foreground(struct mrsh_job *job, bool foreground, bool cont) {
	struct mrsh_state *state = job->state;
	struct mrsh_state_priv *priv = state_get_priv(state);

	assert(job->pgid > 0);

	// Don't try to continue the job if it's not stopped
	if (job_poll(job) != TASK_STATUS_STOPPED) {
		cont = false;
	}

	if (foreground && priv->foreground_job != job) {
		assert(priv->foreground_job == NULL);
		// Put the job in the foreground
		tcsetpgrp(priv->term_fd, job->pgid);
		if (cont) {
			// Restore the job's terminal modes
			tcsetattr(priv->term_fd, TCSADRAIN, &job->term_modes);
		}
		priv->foreground_job = job;
	}

	if (!foreground && priv->foreground_job == job) {
		// Put the shell back in the foreground
		tcsetpgrp(priv->term_fd, priv->pgid);
		// Save the job's terminal modes, to restore them if it's put in the
		// foreground again
		tcgetattr(priv->term_fd, &job->term_modes);
		// Restore the shell’s terminal modes
		tcsetattr(priv->term_fd, TCSADRAIN, &priv->term_modes);
		priv->foreground_job = NULL;
	}

	if (cont) {
		if (kill(-job->pgid, SIGCONT) != 0) {
			perror("kill");
			return false;
		}

		for (size_t j = 0; j < job->processes.len; ++j) {
			struct mrsh_process *proc = job->processes.data[j];
			proc->stopped = false;
		}
	}

	queue_job_notifications(state);

	return true;
}

int job_poll(struct mrsh_job *job) {
	int proc_status = 0;
	bool stopped = false;
	for (size_t j = 0; j < job->processes.len; ++j) {
		struct mrsh_process *proc = job->processes.data[j];
		proc_status = process_poll(proc);
		if (proc_status == TASK_STATUS_WAIT) {
			return TASK_STATUS_WAIT;
		}
		if (proc_status == TASK_STATUS_STOPPED) {
			stopped = true;
		}
	}

	if (stopped) {
		return TASK_STATUS_STOPPED;
	}
	// All processes have terminated, return the last one's status
	return proc_status;
}

static void update_job(struct mrsh_state *state, pid_t pid, int stat);

static bool _job_wait(struct mrsh_state *state, pid_t pid, int options) {
	struct mrsh_state_priv *priv = state_get_priv(state);

	assert(pid > 0 && pid != getpid());

	// We only want to be notified about stopped processes in the main
	// shell. Child processes want to block until their own children have
	// terminated.
	if (!priv->child) {
		options |= WUNTRACED;
	}

	while (true) {
		// Here it's important to wait for a specific process: we don't want to
		// steal one of our grandchildren's status for one of our children.
		int stat;
		pid_t ret = waitpid(pid, &stat, options);
		if (ret == 0) { // no status available
			assert(options & WNOHANG);
			return true;
		} else if (ret < 0) {
			if (errno == EINTR) {
				continue;
			}
			perror("waitpid");
			return false;
		}
		assert(ret == pid);

		update_job(state, ret, stat);
		return true;
	}
}

static struct mrsh_process *job_get_running_process(struct mrsh_job *job) {
	for (size_t j = 0; j < job->processes.len; ++j) {
		struct mrsh_process *proc = job->processes.data[j];
		if (process_poll(proc) == TASK_STATUS_WAIT) {
			return proc;
		}
	}
	return NULL;
}

int job_wait(struct mrsh_job *job) {
	while (true) {
		int status = job_poll(job);
		if (status != TASK_STATUS_WAIT) {
			return status;
		}

		struct mrsh_process *wait_proc = job_get_running_process(job);
		assert(wait_proc != NULL);
		if (!_job_wait(job->state, wait_proc->pid, 0)) {
			return TASK_STATUS_ERROR;
		}
	}
}

int job_wait_process(struct mrsh_process *proc) {
	while (true) {
		int status = process_poll(proc);
		if (status != TASK_STATUS_WAIT) {
			return status;
		}

		if (!_job_wait(proc->state, proc->pid, 0)) {
			return TASK_STATUS_ERROR;
		}
	}
}

bool refresh_jobs_status(struct mrsh_state *state) {
	struct mrsh_state_priv *priv = state_get_priv(state);

	for (size_t i = 0; i < priv->jobs.len; ++i) {
		struct mrsh_job *job = priv->jobs.data[i];
		struct mrsh_process *proc = job_get_running_process(job);
		if (proc == NULL) {
			continue;
		}
		if (!_job_wait(job->state, proc->pid, WNOHANG)) {
			return false;
		}
	}

	return true;
}

bool init_job_child_process(struct mrsh_state *state) {
	return mrsh_set_job_control(state, false);
}

static void update_job(struct mrsh_state *state, pid_t pid, int stat) {
	struct mrsh_state_priv *priv = state_get_priv(state);

	update_process(state, pid, stat);

	// Put stopped and terminated jobs in the background. We don't want to do so
	// if we're not the main shell, because we only have a partial view of the
	// jobs (we only know about our own child processes).
	if (!priv->child) {
		for (size_t i = 0; i < priv->jobs.len; ++i) {
			struct mrsh_job *job = priv->jobs.data[i];
			if (job_poll(job) != TASK_STATUS_WAIT && job->pgid > 0) {
				job_set_foreground(job, false, false);
			}
		}
	}

	queue_job_notifications(state);
}

// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_204
struct mrsh_job *job_by_id(struct mrsh_state *state,
		const char *id, bool interactive) {
	struct mrsh_state_priv *priv = state_get_priv(state);

	if (id[0] != '%' || id[1] == '\0') {
		if (interactive) {
			fprintf(stderr, "Invalid job ID specifier\n");
		}
		return NULL;
	}

	if (id[2] == '\0') {
		switch (id[1]) {
		case '%':
		case '+':
			// Current job
			for (ssize_t i = priv->jobs.len - 1; i >= 0; --i) {
				struct mrsh_job *job = priv->jobs.data[i];
				if (job_poll(job) == TASK_STATUS_STOPPED) {
					return job;
				}
			}
			for (ssize_t i = priv->jobs.len - 1; i >= 0; --i) {
				struct mrsh_job *job = priv->jobs.data[i];
				if (job_poll(job) == TASK_STATUS_WAIT) {
					return job;
				}
			}
			if (interactive) {
				fprintf(stderr, "No current job\n");
			}
			return NULL;
		case '-':
			// Previous job
			for (ssize_t i = priv->jobs.len - 1, n = 0; i >= 0; --i) {
				struct mrsh_job *job = priv->jobs.data[i];
				if (job_poll(job) == TASK_STATUS_STOPPED) {
					if (++n == 2) {
						return job;
					}
				}
			}
			bool first = true;
			for (ssize_t i = priv->jobs.len - 1; i >= 0; --i) {
				struct mrsh_job *job = priv->jobs.data[i];
				if (job_poll(job) == TASK_STATUS_WAIT) {
					if (first) {
						first = false;
						continue;
					}
					return job;
				}
			}
			if (interactive) {
				fprintf(stderr, "No previous job\n");
			}
			return NULL;
		}
	}

	if (id[1] >= '0' && id[1] <= '9') {
		char *endptr;
		int n = strtol(&id[1], &endptr, 10);
		if (endptr[0] != '\0') {
			if (interactive) {
				fprintf(stderr, "Invalid job number '%s'\n", id);
			}
			return NULL;
		}
		for (size_t i = 0; i < priv->jobs.len; ++i) {
			struct mrsh_job *job = priv->jobs.data[i];
			if (job->job_id == n) {
				return job;
			}
		}
		if (interactive) {
			fprintf(stderr, "No such job '%s' (%d)\n", id, n);
		}
		return NULL;
	}

	for (size_t i = 0; i < priv->jobs.len; i++) {
		struct mrsh_job *job = priv->jobs.data[i];
		char *cmd = mrsh_node_format(job->node);
		bool match = false;
		switch (id[1]) {
		case '?':
			match = strstr(cmd, &id[2]) != NULL;
			break;
		default:
			match = strstr(cmd, &id[1]) == cmd;
			break;
		}
		free(cmd);
		if (match) {
			return job;
		}
	}

	if (interactive) {
		fprintf(stderr, "No such job '%s'\n", id);
	}
	return NULL;
}

const char *job_state_str(struct mrsh_job *job, bool r) {
	int status = job_poll(job);
	switch (status) {
	case TASK_STATUS_WAIT:
		return "Running";
	case TASK_STATUS_ERROR:
		return "Error";
	case TASK_STATUS_STOPPED:
		if (job->processes.len > 0) {
			struct mrsh_process *proc = job->processes.data[0];
			switch (proc->signal) {
			case SIGSTOP:
				return r ? "Stopped (SIGSTOP)" : "Suspended (SIGSTOP)";
			case SIGTTIN:
				return r ? "Stopped (SIGTTIN)" : "Suspended (SIGTTIN)";
			case SIGTTOU:
				return r ? "Stopped (SIGTTOU)" : "Suspended (SIGTTOU)";
			}
		}
		return r ? "Stopped" : "Suspended";
	default:
		if (job->processes.len > 0) {
			struct mrsh_process *proc = job->processes.data[0];
			if (proc->stat != 0) {
				static char stat[128];
				snprintf(stat, sizeof(stat), "Done(%d)", proc->stat);
				return stat;
			}
		}
		assert(status >= 0);
		return "Done";
	}
}