proX
proX

Reputation: 73

how to daemonize without parent exit?

I am writing a program in C, a server-client transmission (by socket, send, recv...)

Accord to website http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html,
and other resources, they all exits their parent and close all file descriptors(FD) after using fork() to produce a new child process (maybe such as writing a log file).

I am wondering if it is necessary to do like that since I hope to do something in the coming of code for parent process (server). Moreover, this parent process will listen to new connection or request from socket, I guess it will be invalid if closing all of FDs.

Thanks.

Upvotes: 3

Views: 149

Answers (1)

Ctx
Ctx

Reputation: 18420

You seem to mix this up a bit. The "daemonizing" is only relevant to start the server in background. When this server forks a worker process for each client, the server usually closes the client socket (since only the worker process needs it in the future), but of course leaves the listen-socket open and does not exit.

So:

  • Daemonizing is for having the main server process in background (usually fork(), exit the parent process, child closes stdin/stdout/stderr and calls setsid())

  • Server forks children for each connection to process the client requests and closes client socket after fork, but maintains listen socket to serve future clients.

If you need to daemonize another process from this parent, double-fork():

  • Server forks a process
  • This process forks again and exits
  • The child process closes all irrelevant filedescriptors and calls setsid()

Upvotes: 1

Related Questions