ref: ffa7dafff288418aba6e604efee36463bc3cd8ad mrsh/builtin/fg.c -rw-r--r-- 977 bytes View raw
                                                                                
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
#include <mrsh/getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "builtin.h"
#include "shell/job.h"
#include "shell/shell.h"

// TODO: fg [job_id]
static const char fg_usage[] = "usage: fg\n";

int builtin_fg(struct mrsh_state *state, int argc, char *argv[]) {
	mrsh_optind = 0;
	int opt;
	while ((opt = mrsh_getopt(argc, argv, ":")) != -1) {
		switch (opt) {
		default:
			fprintf(stderr, "fg: unknown option -- %c\n", mrsh_optopt);
			fprintf(stderr, fg_usage);
			return EXIT_FAILURE;
		}
	}
	if (mrsh_optind < argc) {
		fprintf(stderr, fg_usage);
		return EXIT_FAILURE;
	}

	struct mrsh_job *stopped = NULL;
	for (ssize_t i = state->jobs.len - 1; i >= 0; --i) {
		struct mrsh_job *job = state->jobs.data[i];
		if (job_stopped(job)) {
			stopped = job;
			break;
		}
	}
	if (stopped == NULL) {
		fprintf(stderr, "fg: no current job");
		return EXIT_FAILURE;
	}

	if (!job_set_foreground(stopped, true, true)) {
		return EXIT_FAILURE;
	}
	return job_wait(stopped);
}