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 handle := getfs(pidfile);
\r
70 //debugout('got handle');
\r
71 {check if locking is possible: it's not if other process still runs}
\r
73 if not flock(handle,LOCK_EX or LOCK_NB)
\r
75 if flock(handle,LOCK_EX or LOCK_NB) <> 0
\r
78 //debugout('failed to lock pid file');
\r
83 {lock again because the rewrite removes the lock}
\r
85 if not flock(handle,LOCK_EX or LOCK_NB)
\r
87 if flock(handle,LOCK_EX or LOCK_NB) <> 0
\r
89 then raise exception.create('flock failed '+inttostr(linuxerror));
\r
90 pidfilename := filename;
\r
97 writeln(pidfile,getpid);
\r
101 procedure deletepid;
\r
103 if pidfilename = '' then exit;
\r
106 closefile(pidfile);
\r