mirror of
https://github.com/RGBCube/serenity
synced 2025-05-14 09:24:57 +00:00
LibC: Add daemon(3) implementation to match behavior of Linux and BSDs
This helper that originally appeared in 4.4BSD helps to daemonize a process by forking, setting itself as session leader, chdir to "/" and closing stdin/stdout.
This commit is contained in:
parent
6fdd9cddb7
commit
b13846e688
2 changed files with 34 additions and 0 deletions
|
@ -102,6 +102,39 @@ pid_t vfork()
|
|||
return fork();
|
||||
}
|
||||
|
||||
// Non-POSIX, but present in BSDs and Linux
|
||||
// https://man.openbsd.org/daemon.3
|
||||
int daemon(int nochdir, int noclose)
|
||||
{
|
||||
pid_t pid = fork();
|
||||
if (pid < 0)
|
||||
return -1;
|
||||
|
||||
// exit parent, continue execution in child
|
||||
if (pid > 0)
|
||||
_exit(0);
|
||||
|
||||
pid = setsid();
|
||||
if (pid < 0)
|
||||
return -1;
|
||||
|
||||
if (nochdir == 0)
|
||||
(void)chdir("/");
|
||||
|
||||
if (noclose == 0) {
|
||||
// redirect stdout and stderr to /dev/null
|
||||
int fd = open("/dev/null", O_WRONLY);
|
||||
if (fd < 0)
|
||||
return -1;
|
||||
(void)close(STDOUT_FILENO);
|
||||
(void)close(STDERR_FILENO);
|
||||
(void)dup2(fd, STDOUT_FILENO);
|
||||
(void)dup2(fd, STDERR_FILENO);
|
||||
(void)close(fd);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/execv.html
|
||||
int execv(const char* path, char* const argv[])
|
||||
{
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue