1 { Copyright (C) 2005 Bas Steendijk and Peter Green
\r 
   2   For conditions of distribution and use, see copyright notice in zlib_license.txt
\r 
   3     which is included in the package
\r 
   4       ----------------------------------------------------------------------------- }
\r 
  11 procedure dofork(const programname:string);
\r 
  13 function checkpid(const filename:string):boolean;
\r 
  14 procedure deletepid;
\r 
  22     baseunix,unix,unixutil,sockets,
\r 
  26 {$include unixstuff.inc}
\r 
  35 procedure dofork(const programname:string);
\r 
  39   //writeln('dofork entered');
\r 
  40   //if (paramstr(1) = 'foreground') or (paramstr(1)='debug') then exit; {no fork}
\r 
  42   if a = 0 then exit; {i'm the child}
\r 
  44     writeln('failed to run in background, try "'+programname+' foreground" if it doesnt work otherwise');
\r 
  48   halt; {i'm the parent}
\r 
  58   //debugout(filename);
\r 
  59   assignfile(pidfile,filename);
\r 
  61   {opening file to get a fd for it. can't rewrite because a lock appears to allow the rewrite}
\r 
  62   {$i-}reset(pidfile);{$i+}
\r 
  63   if ioresult <> 0 then begin
\r 
  64     {$i-}rewrite(pidfile);{$i+}
\r 
  65     if ioresult <> 0 then exit;
\r 
  68   {$IF FPC_FULLVERSION>=20602}
\r 
  69   handle := getfilehandle(pidfile);
\r 
  71   handle := getfs(pidfile);
\r 
  74   //debugout('got handle');
\r 
  75   {check if locking is possible: it's not if other process still runs}
\r 
  77   if not flock(handle,LOCK_EX or LOCK_NB)
\r 
  79   if flock(handle,LOCK_EX or LOCK_NB) <> 0
\r 
  82     //debugout('failed to lock pid file');
\r 
  87   {lock again because the rewrite removes the lock}
\r 
  89   if not flock(handle,LOCK_EX or LOCK_NB)
\r 
  91   if flock(handle,LOCK_EX or LOCK_NB) <> 0
\r 
  93   then raise exception.create('flock failed '+inttostr(linuxerror));
\r 
  94   pidfilename := filename;
\r 
 101   writeln(pidfile,getpid);
\r 
 105 procedure deletepid;
\r 
 107   if pidfilename = '' then exit;
\r 
 110     closefile(pidfile);
\r