[<prev] [next>] [day] [month] [year] [list]
Message-ID: <4D162DB6.1000808@aknet.ru>
Date: Sat, 25 Dec 2010 20:45:26 +0300
From: Stas Sergeev <stsp@...et.ru>
To: linux-kernel@...r.kernel.org
Subject: [RFC][patch] PR_DETACH: detach from parent
Hi.
I was trying to use daemon() library call to daemonize the process, and
found out that it is not suitable
for the process that have threads: all the threads are simply being killed.
The reason is that the daemon() function does fork(), then exit() in
parent and setsid() in child, which is
a bit ugly, and doesn't work with threads (fork() doesn't fork threads).
I've found no solution to that, and just hacked up one instead.
The attached patch adds the PR_DETACH prctl command, which detaches the
process from its parent.
With that, the daemon() function can be implemented without the
fork/exit/setsid hacks, and here is an
example of it:
---
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#ifndef PR_DETACH
#define PR_DETACH 35
#endif
int daemon2(int nochdir, int noclose)
{
int err, fd;
err = prctl(PR_DETACH);
if (err == -1) {
if (errno == EINVAL)
errno = ENOTSUP;
return -1;
}
fd = open("/dev/tty", O_RDWR);
if (fd != -1) {
ioctl(fd, TIOCNOTTY, NULL);
close(fd);
}
if (!nochdir && chdir("/") == -1)
return -1;
if (!noclose) {
fd = open("/dev/null", O_RDWR, 0);
if (fd == -1)
return -1;
if (dup2(fd, STDIN_FILENO) == -1)
return -1;
if (dup2(fd, STDOUT_FILENO) == -1)
return -1;
if (dup2(fd, STDERR_FILENO) == -1)
return -1;
if (fd > 2)
close(fd);
}
return 0;
}
---
With this implementation, all threads survive the daemonization.
Thoughts?
View attachment "pr_detach.diff" of type "text/plain" (1587 bytes)
Powered by blists - more mailing lists