[uClinux-dev] Daemonize a process

Georges Menie g.menie at wanadoo.fr
Fri Mar 14 17:29:05 EST 2003


On Thu, 2003-03-13 at 16:38, Stuart MacDonald wrote:
> From: "Roope Anttinen" <roope.anttinen at indagon.com>
> > Try something like this. Fairly standard stuff but I haven't tried this
> > is uClinux so it might need some modifications.
> 
> As I mentioned in my original post, this does not work properly.
> 
> > int daemonize()
> > {
> >     int fd;
> >     pid_t pid;
> >
> >     pid = fork();
> >
> >     switch (pid) {
> >     case -1:
> >         return -1;
> >     case 0:
> 
> The child runs, gets to this line and continues with the setsid below.
> 
> >         break;
> >     default:
> 
> The parent is blocked waiting for the child to _exit() or execve(),
> and does not reach the line below until that happens. This leaves the
> parent process in the D state, and AFAICanTell, also does not detach
> the daemon from the controlling tty, meaning that when one logs out,
> the process is killed.

what about this the following code ?
I tried it on my board, and it seems to work ok,
I don't know if the signal() are needed or not...

I used a trick with the execve name and the commandline
name of the process to avoid vfork loop, the program
name is messmgr but the forked process gets a name
with a 'd' happened at the end...

the controlling terminal is reset, so one can exit the shell which was
used to start the daemon.

#define EXEC_FULLPATHNAME "/usr/local/bin/messmgr"

int main(int argc, char *argv[])
{
	int fd, pid;
	char *av[] = { "messmgrd", NULL }; /* real basename + 'd' */
	extern char **environ;
	
	chdir("/");
	umask(0);
	setpgrp();
	for (fd = 0; fd < getdtablesize(); ++fd)
		close(fd);
	if ((fd=open("/dev/tty", O_RDWR)) >= 0) {
		(void) ioctl(fd, TIOCNOTTY, (char *)0);
		(void) close(fd);
	}
	signal(SIGHUP, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTSTP, SIG_IGN);

	openlog(argv[0],LOG_CONS|LOG_PID,LOG_DAEMON);

	if (strcmp(argv[0], av[0])) {
		if ((pid = vfork()) == 0) {
			execve(EXEC_FULLPATHNAME, av, environ);
			syslog(LOG_DEBUG,"exec failed\n");
		} else if(pid < 0) {
			syslog(LOG_DEBUG,"fork failed\n");
		}
		_exit(0);
	}

	return do_something();
}





More information about the uClinux-dev mailing list