open Unix
let daemonize cmd args =
  let lockfile = Filename.concat "/tmp/" cmd ^ "_lock" in
  try
    let fd = openfile lockfile [O_WRONLYO_EXCLO_CREAT] 0o600 in
    match fork () with
    | 0 ->
        if fork () <> 0 then exit 0;
        let chan = out_channel_of_descr fd in
        output_binary_int chan (Unix.getpid ());
        close_out chan;
        Shell.mon_exec cmd args
    | _ ->
        ignore (wait ()); close fd;
        0
  with Unix_error (EEXIST,_,_) ->
    Printf.eprintf "Deamond apparently already running %s" cmd;
    1