From Organic Design
Legacy.svg Legacy: This article describes a concept that has been superseded in the course of ongoing development on the Organic Design wiki. Please do not develop this any further or base work on this concept, this is only useful for a historic record of work done. You may find a link to the currently used concept or function in this article, if not you can contact the author to find out what has taken the place of this legacy item.
// [[[[http://www.organicdesign.co.nz/peerd|peerd]]]] - nodal p2p wiki daemon
// This article and all its includes are licenced under LGPL
// GPL: [[[[http://www.gnu.org/copyleft/lesser.html]]]]
// SRC: [[[[http://www.organicdesign.co.nz/daemonise.c]]]]
// included in [[[[http://www.organicdesign.co.nz/category:peerd/files/C|peerd]]]][[[[http://www.organicdesign.co.nz/peerd.c|/peerd.c]]]]

int peerdInit();

// ----------------------------------------------------------------------------------------- //
// daemonise.c

int peerdInit() {

	// Fork so parent can exit and return control to what invoked it
	pid_t pid = fork();
	if (pid > 0) exit(EXIT_SUCCESS);
	if (pid < 0) {
		logAdd("daemonise: First fork() failed!");

	// Become a new session leader with no controlling term
	if (setsid() < 0) {
		logAdd("daemonise: setsid() failed!");

	// Fork again to be a non-session-leader which can't gain a controlling term
	pid = fork();
	if (pid > 0) exit(EXIT_SUCCESS);
	if (pid < 0) {
		logAdd("daemonise: second fork() failed!");

	errno = 0;
	// Should be /home/lc(peer)

	// Don't inherit any file perms mask


	return errno;