~emersion/mrsh

ref: 4b0435e60a86d710080ab7aac5b7ba8b23b29928 mrsh/builtin/bg.c -rw-r--r-- 878 bytes
4b0435e6emersion wip: job control 2 years 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
#include <mrsh/array.h>
#include <mrsh/getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "builtin.h"
#include "shell/job.h"

// TODO: bg [job_id]
static const char bg_usage[] = "usage: bg\n";

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

	struct job *bg = NULL;
	for (ssize_t i = jobs.len - 1; i >= 0; --i) {
		struct job *j = jobs.data[i];
		if (j != job_foreground()) {
			bg = j;
			break;
		}
	}
	if (bg == NULL) {
		fprintf(stderr, "bg: no current job");
		return EXIT_FAILURE;
	}

	job_continue(bg);

	return EXIT_SUCCESS;
}