0

I found the answer in Managing Signal Handling for daemons that fork() very helpful for what I'm doing. I'm unsure about how to solve

"You will therefore need to install any signal handling in the execed process when it starts up"

I don't have control over the process that start up. Is there any way for me to force some signal handles on the execed from the parent of the fork?

Edit:{
I'm writing a Perl module that monitors long-running processes. Instead of

system(<long-running cmd>);

you'd use

my_system(<ID>, <long-running cmd>);

I create a lock file for the <ID> and don't let another my_system(<ID>...) call through if there is one currently running with a matching ID.

The parent fork/execs <long-running cmd> and is in change of cleaning up the lock file when it terminates. I'd like to have the child self-sufficient so the parent can exit (or so the child can take care of itself if the parent gets a kill -9).
}

Community
  • 1
  • 1
ajwood
  • 18,227
  • 15
  • 61
  • 104

2 Answers2

2

On Unix systems, you can make an exec'd process ignore signals (unless the process chooses to override what you say), but you can't force it to set a handler for it. The most you can do is leave the relevant signal being handled by the default handler.

If you think about it, you'll realize why. To install a signal handler, you have to provide a function pointer - but the process that does the exec() can't specify one of its functions because they won't exist as part of the exec'd process, and it can't specify one of the exec'd processes functions because they don't exist as part of the exec'ing process. Similarly, you can't register atexit() handlers in the exec'ing process that will be honoured by the exec'd process.

As to your programming problem, there's a good reason that the lock file normally contains the process ID (pid) of the process that holds the lock; it allows you to check whether that process is still around, even if it isn't your child. You can read the pid from the lock file, and then use kill(pid, 0) which will tell you if the process exists and you can signal it without actually sending any signal.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Great answer. I was hoping there would be a way to somehow load the handler function into the running program... too bad that's impossible. Also, that scheme for the lockfile works *almost* all the time for my situation. The only problem being that there are many computers that share an nfs file system. So if there is a lock started up from A, there's no way for B to see if it's still running or if it's a hanging lockfile. – ajwood Apr 02 '11 at 14:30
1

One approach would be to use two forks.

The first fork would create a child process responsible for cleaning up the lock file if the parent dies. This process will also fork a grandchild which would exec the long running command.

David Harris
  • 2,332
  • 1
  • 13
  • 25