summaryrefslogtreecommitdiffstats
path: root/osdep/subprocess.c
diff options
context:
space:
mode:
authorwm4 <wm4@nowhere>2020-02-16 21:57:17 +0100
committerwm4 <wm4@nowhere>2020-02-16 22:08:48 +0100
commitf2c7c641b38d060a7eea52a92bc0239f1603bffb (patch)
treed6f6df3c7a8325edf6c22d45c846d022f50e57a7 /osdep/subprocess.c
parent92fee4ebc4852f023527dc64b28e5b10e4507053 (diff)
downloadmpv-f2c7c641b38d060a7eea52a92bc0239f1603bffb.tar.bz2
mpv-f2c7c641b38d060a7eea52a92bc0239f1603bffb.tar.xz
subprocess: implement proper detached processes on POSIX
The previous method for this sucked: for every launched detached process, it started a thread, which then would leak if the launched process didn't end before the player uninitialized. This was very racy (although I bet the race condition wouldn't trigger in a 100 years), and wasteful (threads aren't a cheap resource). Implement it for POSIX directly. posix_spawn() has no direct support for this, so we need to do it ourselves with fork(). We could probably do it without fork(), and attempt to collect the PID in another thread. But then we'd either have a waiting thread again, or we'd need to do an unsafe waitpid(-1, ...) call. (POSIX process management sucks so badly, how did they even manage this. Hopefully I'm just missing something, but I'm not.) So now we depend on both posix_spawn() _and_ fork(), isn't it fun? Also call setsid(), to essentially detach the child process from the terminal. (Otherwise it can receive various signals from the terminal, which is probably not what you want.) posix_spawn() adds POSIX_SPAWN_SETSID in newer POSIX releases, but we don't want to rely on this yet. The posix_spawnp() call is duplicated, but this is better than somehow trying to unify the code paths. Only somewhat tested, so enjoy the bugs.
Diffstat (limited to 'osdep/subprocess.c')
-rw-r--r--osdep/subprocess.c27
1 files changed, 26 insertions, 1 deletions
diff --git a/osdep/subprocess.c b/osdep/subprocess.c
index 9da5c10c1c..8bb2acd0b7 100644
--- a/osdep/subprocess.c
+++ b/osdep/subprocess.c
@@ -65,7 +65,30 @@ int mp_subprocess(char **args, struct mp_cancel *cancel, void *ctx,
return res.exit_status;
}
-#endif
+void mp_subprocess_detached(struct mp_log *log, char **args)
+{
+ mp_msg_flush_status_line(log);
+
+ struct mp_subprocess_opts opts = {
+ .exe = args[0],
+ .args = args,
+ .fds = {
+ {.fd = 0, .src_fd = 0,},
+ {.fd = 1, .src_fd = 1,},
+ {.fd = 2, .src_fd = 2,},
+ },
+ .num_fds = 3,
+ .detach = true,
+ };
+ struct mp_subprocess_result res;
+ mp_subprocess2(&opts, &res);
+ if (res.error < 0) {
+ mp_err(log, "Starting subprocess failed: %s\n",
+ mp_subprocess_err_str(res.error));
+ }
+}
+
+#else
struct subprocess_args {
struct mp_log *log;
@@ -100,6 +123,8 @@ void mp_subprocess_detached(struct mp_log *log, char **args)
talloc_free(p);
}
+#endif
+
const char *mp_subprocess_err_str(int num)
{
// Note: these are visible to the public client API