~emersion/mrsh

ref: ee80db4d9ac87dbb0eedc3a50ab7e5bafac6633d mrsh/shell/task/subshell.c -rw-r--r-- 1.5 KiB View raw
ee80db4dSimon Ser Introduce job_poll 1 year, 2 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
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "shell/process.h"
#include "shell/task.h"

struct task_subshell {
	struct task task;
	struct task *subtask;
	bool started;
	struct process *process;
};

static void task_subshell_destroy(struct task *task) {
	struct task_subshell *ts = (struct task_subshell *)task;
	task_destroy(ts->subtask);
	free(ts);
}

static bool task_subshell_start(struct task_subshell *ts, struct context *ctx) {
	pid_t pid = fork();
	if (pid < 0) {
		fprintf(stderr, "failed to fork(): %s\n", strerror(errno));
		return false;
	} else if (pid == 0) {
		// TODO: set process group ID

		errno = 0;
		int ret = task_run(ts->subtask, ctx);
		if (ret < 0) {
			fprintf(stderr, "failed to run task: %s\n", strerror(errno));
			exit(127);
		}

		if (ctx->state->exit >= 0) {
			exit(ctx->state->exit);
		}
		exit(ret);
	}

	ts->process = process_create(ctx->state, pid);
	return true;
}

static int task_subshell_poll(struct task *task, struct context *ctx) {
	struct task_subshell *ts = (struct task_subshell *)task;

	if (!ts->started) {
		if (!task_subshell_start(ts, ctx)) {
			return TASK_STATUS_ERROR;
		}
		ts->started = true;
	}

	return process_poll(ts->process);
}

static const struct task_interface task_subshell_impl = {
	.destroy = task_subshell_destroy,
	.poll = task_subshell_poll,
};

struct task *task_subshell_create(struct task *subtask) {
	struct task_subshell *ts = calloc(1, sizeof(struct task_subshell));
	task_init(&ts->task, &task_subshell_impl);
	ts->subtask = subtask;
	return &ts->task;
}