From: Gennady Date: 2003-12-08T17:02:15+09:00 Subject: Re: Trying to create a Ruby daemon On Dec 7, 2003, at 6:37, YANAGAWA Kazuhisa wrote: > In Message-Id: > Samuel Kvarnbrink writes: > >> Does anyone here have an example on how to create a Ruby daemon that >> runs as a session leader (without a controlling terminal)? I've tried >> to accomplish that using fork and Process.setpgrp, but the only >> results so far have been zombie processes or processes that exit when >> I close the terminal. I'm quite new to Ruby so I guess that I've >> missed some little detail somewhere... :) > > Following is a tiny sample. You can get more knowledge from other > daemon codes and man pages. A book like "Advanced Programming in the > UNIX Environment" also helps a lot. > > # See Also: daemon(3), setsid(2), setpgrp(2), wait(2), ps(1) and > # tty(4) if needed (on BSD based system, it may contains info around > # TIOCNOTTY). > > > # parent process exits to pass child to init(1). > fork and exit > > # child becomes session leader and disassociates controlling tty. > # namely do Process.setpgrp + \alpha. > Process.setsid > > # at here already the child process have become daemon. the rest > # is just for behaving well. > > # ensure no extra I/O. > File.open("/dev/null", "r+") do > |devnull| > $stdin.reopen(devnull) > $stdout.reopen(devnull) > $stderr.reopen(devnull) > end > > # ensure daemon process not to prevent shutdown process. > Dir.chdir("/") > > > -- > kjana@dm4lab.to December 7, 2003 > Art is long, and time is fleeting. > > You really need a second fork here, as the previous post suggested, if you do not want to get into trouble with unexpectedly acquiring a controlling terminal. Generally in Unix (with some exceptions), the first tty device opened by a session/group leader (unless opened with O_NOCTTY) becomes the controlling terminal for the whole session/group. Gennady.