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
9 procedure dofork(const programname:string);
\r
11 function checkpid(const filename:string):boolean;
\r
12 procedure deletepid;
\r
20 baseunix,unix,unixutil,sockets,
\r
24 {$include unixstuff.inc}
\r
33 procedure dofork(const programname:string);
\r
37 //writeln('dofork entered');
\r
38 //if (paramstr(1) = 'foreground') or (paramstr(1)='debug') then exit; {no fork}
\r
40 if a = 0 then exit; {i'm the child}
\r
42 writeln('failed to run in background, try "'+programname+' foreground" if it doesnt work otherwise');
\r
46 halt; {i'm the parent}
\r
56 //debugout(filename);
\r
57 assignfile(pidfile,filename);
\r
59 {opening file to get a fd for it. can't rewrite because a lock appears to allow the rewrite}
\r
60 {$i-}reset(pidfile);{$i+}
\r
61 if ioresult <> 0 then begin
\r
62 {$i-}rewrite(pidfile);{$i+}
\r
63 if ioresult <> 0 then exit;
\r
66 handle := getfs(pidfile);
\r
68 //debugout('got handle');
\r
69 {check if locking is possible: it's not if other process still runs}
\r
71 if not flock(handle,LOCK_EX or LOCK_NB)
\r
73 if flock(handle,LOCK_EX or LOCK_NB) <> 0
\r
76 //debugout('failed to lock pid file');
\r
81 {lock again because the rewrite removes the lock}
\r
83 if not flock(handle,LOCK_EX or LOCK_NB)
\r
85 if flock(handle,LOCK_EX or LOCK_NB) <> 0
\r
87 then raise exception.create('flock failed '+inttostr(linuxerror));
\r
88 pidfilename := filename;
\r
95 writeln(pidfile,getpid);
\r
99 procedure deletepid;
\r
101 if pidfilename = '' then exit;
\r
104 closefile(pidfile);
\r