(* whenjobs * Copyright (C) 2012 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) open Unix open Printf (* See [flock.c]. *) external flock_exclusive_nonblocking : file_descr -> unit = "whenjobs_flock_exclusive_nonblocking" (* Global fd open on daemon_pid file. fd is closed and the lock is * released implicitly when the program exits. *) let pid_fd = ref stdin let rec create_lock jobsdir = let pid_file = get_pid_file jobsdir in pid_fd := openfile pid_file [ O_CREAT; O_RDWR ] 0o600; (try flock_exclusive_nonblocking !pid_fd with Failure _ -> eprintf "whenjobsd: PID file (%s) exists and cannot be locked\n" pid_file; eprintf "Another instance of the daemon may be running.\n"; exit 1 ); update_pid () and update_pid () = let pid = sprintf "%d\n" (getpid ()) in ignore (lseek !pid_fd 0 SEEK_SET); ftruncate !pid_fd 0; ignore (write !pid_fd pid 0 (String.length pid)) and test_locked jobsdir = let pid_file = get_pid_file jobsdir in let fd = openfile pid_file [ O_CREAT; O_RDWR ] 0o600 in let r = ref false in (try flock_exclusive_nonblocking fd with Failure _ -> r := true); close fd; !r and kill_daemon jobsdir = let pid_file = get_pid_file jobsdir in let chan = open_in pid_file in let pid = input_line chan in close_in chan; let pid = int_of_string pid in kill pid 15 and get_pid_file jobsdir = sprintf "%s/daemon_pid" jobsdir