Unix/Linux如何创建一个后台进程

https://blog.csdn.net/ACb0y/article/details/6629774
1、调用fork函数,创建一个子进程。
2、先让父进程自然结束。
3、在子进程中调用setpgrp(),把子进程的进程组ID设为子进程的进程ID。
4、在子进程中调用setsid(),创建一个新的Session(会话),这样子进程就与当前的控制终端脱离,也接受不到当前终端的(ctrl + c)消息。

macOS

Ref: man daemon –> posix_spawn
https://github.com/apple-oss-distributions/Libc/blob/main/gen/FreeBSD/daemon.c
https://github.com/aria2/aria2/blob/master/src/daemon.cc
https://github.com/apache/apr/blob/trunk/threadproc/unix/procsup.c
https://github.com/nghttp2/nghttp2/blob/master/src/util.cc#L1651
daemonize

1
2
3
4
5
6
#ifdef __APPLE__
/* Don't daemonize when run by launchd */
if (getppid() != 1 && daemon(1, 0) == -1) {
#else
if (daemon(1, 0) == -1) {
#endif

posix_spawn

https://github.com/libuv/libuv/blob/v1.x/src/unix/process.c#L845
https://github.com/ninja-build/ninja/blob/master/src/subprocess-posix.cc#L51
https://github.com/qt/qtbase/blob/dev/src/3rdparty/forkfd/forkfd.c