2

I am trying to create a c++ daemon that runs on a Red Hat 6.3 platform and am having trouble understanding the differences between the libc daemon() call, the daemon shell command, startproc, start-stop-daemon and about half a dozen other methods that google suggests for creating daemons.

I have seen suggestions that two forks are needed, but calling daemon only does one. Why is the second fork needed?

If I write the init.d script to call bash daemon, does the c code still need to call daemon?

I implemented my application to call the c daemon() function since it seems the simplest solution, but I am running into the problem of my environment variables seem to get discarded. How do I prevent this?

I also need to run the daemon as a particular user, not as root.

What is the simplest way to create a C++ daemon that keeps its environment variables, runs as a specific user, and is started on system boot?

mjr
  • 1,963
  • 4
  • 20
  • 21

1 Answers1

1

Why is the second fork needed?

Answered in What is the reason for performing a double fork when creating a daemon?

bash daemon shell command

My bash 4.2 does not have a builtin command named daemon. Are you sure yours is from bash? What version, what distribution?

environment variables seem to get discarded.

I can see no indication to that effect in the documentation. Are you sure it is due to daemon? Have you checked whether they are present before, and missing after that call?

run the daemon as a particular user

Read about setresuid and related functions.

What is the simplest way to create a C++ daemon that keeps its environment variables, runs as a specific user, and is started on system boot?

Depends. If you want to keep your code simple, forget about all of this and let the init script do this via e.g. start-stop-daemon. If you want to handle this in your app, daemon combined with retresuid should be a good approach, although not the only one.

Community
  • 1
  • 1
MvG
  • 57,380
  • 22
  • 148
  • 276
  • daemon is in /etc/init.d/functions. I am certain that my environment variables are set before the call the daemon(), and not after. – mjr Nov 13 '13 at 16:51
  • [This post](http://unix.stackexchange.com/a/9317/20807) clarifies that `/etc/init.d.functions` is distro-dependent. This my question about your distribution. I can't reproduce `daemon` loosing environment; in my test app here it works fine. – MvG Nov 13 '13 at 18:20
  • I am currently running on Red Hat 6.3 and will so be soon setting up on another server running some version of CentOS. – mjr Nov 14 '13 at 19:33