From 079c69cbfd7cd3c97baae91332251c8388a8bb02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Axel=20D=C3=B6rfler?= Date: Tue, 4 Sep 2007 12:32:20 +0000 Subject: [PATCH] Added daemon() function to libbsd.so. git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@22164 a95241bf-73f2-0310-859d-f6bbb57e9c96 --- headers/compatibility/bsd/stdlib.h | 3 +- src/libs/bsd/Jamfile | 1 + src/libs/bsd/daemon.c | 68 ++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 src/libs/bsd/daemon.c diff --git a/headers/compatibility/bsd/stdlib.h b/headers/compatibility/bsd/stdlib.h index 1e6e888e13..4d2410ba63 100644 --- a/headers/compatibility/bsd/stdlib.h +++ b/headers/compatibility/bsd/stdlib.h @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku, Inc. All Rights Reserved. + * Copyright 2006-2007, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. */ #ifndef _BSD_STDLIB_H_ @@ -13,6 +13,7 @@ extern "C" { #endif +int daemon(int noChangeDir, int noClose); const char *getprogname(void); void setprogname(const char *programName); diff --git a/src/libs/bsd/Jamfile b/src/libs/bsd/Jamfile index 65f9e2c032..b9e3fa1551 100644 --- a/src/libs/bsd/Jamfile +++ b/src/libs/bsd/Jamfile @@ -5,6 +5,7 @@ SetSubDirSupportedPlatforms $(HAIKU_BONE_COMPATIBLE_PLATFORMS) ; UseHeaders [ FDirName $(HAIKU_TOP) headers compatibility bsd ] : true ; SharedLibrary libbsd.so : + daemon.c err.c fgetln.c getpass.c diff --git a/src/libs/bsd/daemon.c b/src/libs/bsd/daemon.c new file mode 100644 index 0000000000..a34825dd3c --- /dev/null +++ b/src/libs/bsd/daemon.c @@ -0,0 +1,68 @@ +/* + * Copyright 2007, Haiku, Inc. All Rights Reserved. + * Distributed under the terms of the MIT License. + * + * Authors: + * Axel Dörfler, axeld@pinc-software.de + */ + +#include +#include +#include +#include + + +static void +restore_old_sighup(int result, struct sigaction *action) +{ + if (result != -1) + sigaction(SIGHUP, action, NULL); +} + + +int +daemon(int noChangeDir, int noClose) +{ + struct sigaction oldAction, action; + int oldActionResult; + pid_t newGroup; + pid_t pid; + + /* Ignore eventually send SIGHUPS on parent exit */ + sigemptyset(&action.sa_mask); + action.sa_handler = SIG_IGN; + action.sa_flags = 0; + oldActionResult = sigaction(SIGHUP, &action, &oldAction); + + pid = fork(); + if (pid == -1) { + restore_old_sighup(oldActionResult, &oldAction); + return -1; + } + if (pid > 0) { + // we're the parent - let's exit + exit(0); + } + + newGroup = setsid(); + restore_old_sighup(oldActionResult, &oldAction); + + if (newGroup == -1) + return -1; + + if (!noChangeDir) + chdir("/"); + + if (!noClose) { + int fd = open("/dev/null", O_RDWR); + if (fd != -1) { + dup2(fd, STDIN_FILENO); + dup2(fd, STDOUT_FILENO); + dup2(fd, STDERR_FILENO); + if (fd > STDERR_FILENO) + close(fd); + } + } + + return 0; +}