1

I'm writing an init.d script to start a program that I've written in C. The program follows a pretty standard template where it calls fork() to create a child process, and then the parent process terminates almost immediately. The trouble I'm running into is that the PID file gets the parent process ID written to it, so later when I call "stop" it fails because the parent has long since ended and only the child is running.

Currently I have this command in my startup script:

start-stop-daemon --start --background -m --oknodo --pidfile "$PIDFILE" --exec "$SCRIPT" || return 2

I confess that I'm very new to all of this so I'm not even entirely sure what all those flags do. This was mostly a copy/paste from various articles I stumbled across. In any case, this would seem like a fairly common thing. How can I make it write the correct (i.e. child) process ID in the pid file?

soapergem
  • 7,597
  • 16
  • 79
  • 124
  • Either: you pass the path of the `PIDFILE` to your C program and the parent will write the PID of his child into it, or 2.) the parent prints the PID of the child to stdout/stderr, so the underlaying shell could capture it... 3) your C will not fork itself, and the `start-stop-deemon` will send it into the background, so it will know its PID. – jm666 Mar 29 '17 at 20:19
  • Let's say I choose door #2, how would I modify the bash command above to account for that? – soapergem Mar 29 '17 at 20:21
  • Good question. :) Me not using ubuntu (nor even linux), so i don't know exactly how the `start-stop-daemon` works. (Otherwise I was added an answer, not only an comment). So, better to wait for some, more deep answer... – jm666 Mar 29 '17 at 20:23
  • So I see that if I just write `$SCRIPT >$PIDFILE` instead of all that above, it will successfully launch the daemon and write the correct process ID into the pidfile (because I went ahead and modified my program to print it to stdout). However, `$SCRIPT >$PIDFILE` doesn't include any checks to see if the pidfile already exists, if the process is already running, etc. It just plows ahead and starts it no matter what. And I'm not familiar enough with bash to write the proper if statements to handle things better. – soapergem Mar 30 '17 at 21:53

1 Answers1

1

Daemons need to create .pid file by own self. Because of daemonizing procedure by it self, when you change your start pid.

Option --pidfile is for pid file which already created. Also start-stop-daemon has option --make-pidfile, but it's useful only for program which not daemonize own self.

-m, --make-pidfile ... Note: This feature may not work in all cases. Most notably when the program being executed forks from its main process.

Ronald Coarite
  • 3,431
  • 23
  • 25
komar
  • 841
  • 5
  • 8