How to run a system command, and pipe PID to pidfile?

How do I run a command and pipe the resulting pid into a pidfile? I'm looking for an UNIX command, but if there's a way to do it in Ruby, that'd be nice too. I tried:

bundle exec clockwork clock_local.rb echo $! > #/tmp/pids/clockwork.pid 
and it seems to pipe the entire output to the pidfile rather than just the pid. asked Apr 20, 2013 at 2:00 Henley Wing Chiu Henley Wing Chiu 22.2k 34 34 gold badges 126 126 silver badges 211 211 bronze badges

2 Answers 2

You can use Ruby's BEGIN <. >and END <. >to help automatically create and delete PID files. Add these to a Ruby script:

BEGIN < File.write("#< $0 >.pid", $$) > END < File.delete("#< $0 >.pid") > 

You could test that they create a simple PID file with a simple script like:

BEGIN < File.write("#< $0 >.pid", $$) > END < File.delete("#< $0 >.pid") > sleep 60 

Run it, then, while it's running check the directory it's in for the pid file. After one minute, when the sleep expires the PID file should automatically disappear.

Those don't do any exception handling in case the file isn't writable or if it already exists and is locked. END will fire off if the script receives CNTRL + C and automatically remove the PID file.

Additional things you'd want to add would be tests for an existing PID file, locking the file after creation so it can't be overwritten, which could be done by keeping it open with an exclusive lock (see flock ).