0aa34cd033201e13b28edd71c3130d12ffe8ba5d
[musl] / src / process / system.c
1 #include <unistd.h>
2 #include <fcntl.h>
3 #include <signal.h>
4 #include <sys/wait.h>
5 #include <spawn.h>
6 #include <errno.h>
7 #include "pthread_impl.h"
8 #include "libc.h"
9
10 static void dummy_0()
11 {
12 }
13 weak_alias(dummy_0, __acquire_ptc);
14 weak_alias(dummy_0, __release_ptc);
15
16 extern char **environ;
17
18 int system(const char *cmd)
19 {
20         pid_t pid;
21         sigset_t old, reset;
22         struct sigaction sa = { .sa_handler = SIG_IGN }, oldint, oldquit;
23         int status = 0x7f00, ret;
24         posix_spawnattr_t attr;
25
26         pthread_testcancel();
27
28         if (!cmd) return 1;
29
30         sigaction(SIGINT, &sa, &oldint);
31         sigaction(SIGQUIT, &sa, &oldquit);
32         sigaddset(&sa.sa_mask, SIGCHLD);
33         sigprocmask(SIG_BLOCK, &sa.sa_mask, &old);
34
35         sigemptyset(&reset);
36         if (oldint.sa_handler != SIG_IGN) sigaddset(&reset, SIGINT);
37         if (oldquit.sa_handler != SIG_IGN) sigaddset(&reset, SIGQUIT);
38         posix_spawnattr_init(&attr);
39         posix_spawnattr_setsigmask(&attr, &old);
40         posix_spawnattr_setsigdefault(&attr, &reset);
41         posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF|POSIX_SPAWN_SETSIGMASK);
42         ret = posix_spawn(&pid, "/bin/sh", 0, &attr,
43                 (char *[]){"sh", "-c", (char *)cmd, 0}, environ);
44         posix_spawnattr_destroy(&attr);
45
46         if (!ret) while (waitpid(pid, &status, 0)<0 && errno == EINTR);
47         sigaction(SIGINT, &oldint, NULL);
48         sigaction(SIGQUIT, &oldquit, NULL);
49         sigprocmask(SIG_SETMASK, &old, NULL);
50
51         if (ret) errno = ret;
52         return status;
53 }