1

I wrote a TCP daemon, that accepts clients connections on given port and after that it executes a command using execv(3). In every tutorial on writting daemons it is mentioned to close stdin, stdout, stderr to sucessfully daemonize the process.

However I found out that accept(2) reuses file descriptor numbers of already closed stdout/stderr so after calling fork(2) and execv(3), child process writes output to socket simply because stdout/stderr maps to file descriptor now associated with client socket.

Any ideas how can I avoid this without resorting to shell output redirection?

antagon
  • 119
  • 8

2 Answers2

1

Everyone!

If you don't want file descriptors for standard input/output to be reused by accept(2) and presumably any other function which returns a new file descriptor, avoid calling close(2)/fclose(3) on them, but redirect them to /dev/null (if available) instead. This idea comes from manual page for daemon(3).

freopen ("/dev/null", "r", stdin);
freopen ("/dev/null", "w", stdout);
freopen ("/dev/null", "w", stderr);
antagon
  • 119
  • 8
0

First thing, to daemon process, its parent has to be exited, so it will be redirected to INIT process and it will become a daemon.

I think your use-case is, you get the command from other clients and executes it in your daemon and then redirect output to requesting client. If you are planning to use closing of STD_ERR and STD_OUT concept then you have to be careful to receive request in serial manner only.

Now come to your issue, To redirect STD_ERR and STD_OUT to accepted client FD, you have to keep STD_ERR and STD_OUT open till client is accepted, after accepting client only, close the STD_OUT and then use DUP with accepted client FD.

refer below link to get more idea from this kind of issue. practical examples use dup or dup2

Community
  • 1
  • 1
Pratrick
  • 7
  • 3