1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
14 static int close_fds(int except[], unsigned n_except) {
19 /* Modifies the fds array! (sorts it) */
21 if (!(d = opendir("/proc/self/fd")))
24 while ((de = readdir(d))) {
27 if (de->d_name[0] == '.')
30 if ((r = safe_atoi(de->d_name, &fd)) < 0)
44 for (i = 0; i < n_except; i++)
45 if (except[i] == fd) {
54 if ((r = close_nointr(fd)) < 0)
63 static int shift_fds(int fds[], unsigned n_fds) {
64 int start, restart_from;
77 for (i = start; i < (int) n_fds; i++) {
80 /* Already at right index? */
84 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
87 assert_se(close_nointr(fds[i]));
90 /* Hmm, the fd we wanted isn't free? Then
91 * let's remember that and try again from here*/
92 if (nfd != i+3 && restart_from < 0)
105 int exec_spawn(const ExecCommand *command, const ExecContext *context, int *fds, unsigned n_fds, pid_t *ret) {
111 assert(fds || n_fds <= 0);
113 if ((pid = fork()) < 0)
117 char **e, **f = NULL;
122 umask(context->umask);
124 if (chdir(context->directory ? context->directory : "/") < 0) {
129 snprintf(t, sizeof(t), "%i", context->oom_adjust);
132 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
137 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
142 if (close_fds(fds, n_fds) < 0 ||
143 shift_fds(fds, n_fds) < 0) {
148 for (i = 0; i < RLIMIT_NLIMITS; i++) {
149 if (!context->rlimit[i])
152 if (setrlimit(i, context->rlimit[i]) < 0) {
160 char *listen_env[3] = {
166 snprintf(a, sizeof(a), "LISTEN_PID=%llu", (unsigned long long) getpid());
167 snprintf(b, sizeof(b), "LISTEN_FDS=%u", n_fds);
172 if (context->environment) {
173 if (!(f = strv_merge(listen_env, context->environment))) {
182 e = context->environment;
184 execve(command->path, command->argv, e);
196 void exec_context_init(ExecContext *c) {
200 cap_clear(c->capabilities);
205 void exec_context_done(ExecContext *c) {
210 strv_free(c->environment);
211 c->environment = NULL;
213 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
227 strv_free(c->supplementary_groups);
228 c->supplementary_groups = NULL;
231 void exec_command_free_list(ExecCommand *c) {
235 LIST_REMOVE(ExecCommand, command, c, i);
243 void exec_command_free_array(ExecCommand **c, unsigned n) {
246 for (i = 0; i < n; i++) {
247 exec_command_free_list(c[i]);
253 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
266 prefix, c->directory ? c->directory : "/",
268 prefix, c->oom_adjust);
271 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
277 s->timestamp = now(CLOCK_REALTIME);