unix.pp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. {
  2. $Id: unix.pp,v 1.85 2005/03/25 22:53:39 jonas Exp $
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 1999-2000 by Michael Van Canneyt,
  5. BSD parts (c) 2000 by Marco van de Voort
  6. members of the Free Pascal development team.
  7. See the file COPYING.FPC, included in this distribution,
  8. for details about the copyright.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY;without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. **********************************************************************}
  13. Unit Unix;
  14. Interface
  15. Uses BaseUnix,UnixType;
  16. {$i aliasptp.inc}
  17. { Get Types and Constants only exported in this unit }
  18. {$i unxconst.inc}
  19. // We init to zero to be able to put timezone stuff under IFDEF, and still
  20. // keep the code working.
  21. var
  22. Tzseconds : Longint {$ifndef ver1_0} = 0 {$endif};
  23. {********************
  24. File
  25. ********************}
  26. Const
  27. P_IN = 1; // pipes (?)
  28. P_OUT = 2;
  29. Const
  30. LOCK_SH = 1; // flock constants ?
  31. LOCK_EX = 2;
  32. LOCK_UN = 8;
  33. LOCK_NB = 4;
  34. Type
  35. Tpipe = baseunix.tfildes; // compability.
  36. {******************************************************************************
  37. Procedure/Functions
  38. ******************************************************************************}
  39. {**************************
  40. Time/Date Handling
  41. ***************************}
  42. var
  43. tzdaylight : boolean;
  44. tzname : array[boolean] of pchar;
  45. {$IFNDEF DONT_READ_TIMEZONE} // allows to disable linking in and trying for platforms
  46. // it doesn't (yet) work for.
  47. { timezone support }
  48. procedure GetLocalTimezone(timer:cint;var leap_correct,leap_hit:cint);
  49. procedure GetLocalTimezone(timer:cint);
  50. procedure ReadTimezoneFile(fn:string);
  51. function GetTimezoneFile:string;
  52. {$ENDIF}
  53. {**************************
  54. Process Handling
  55. ***************************}
  56. //
  57. // These are much better, in nearly all ways.
  58. //
  59. function FpExecLE (Const PathName:AnsiString;const S:Array Of AnsiString;MyEnv:ppchar):cint;
  60. function FpExecL(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  61. function FpExecLP(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  62. function FpExecV(Const PathName:AnsiString;args:ppchar):cint;
  63. function FpExecVP(Const PathName:AnsiString;args:ppchar):cint;
  64. function FpExecVPE(Const PathName:AnsiString;args,env:ppchar):cint;
  65. Function Shell (const Command:String):cint;
  66. Function Shell (const Command:AnsiString):cint;
  67. Function fpSystem(const Command:AnsiString):cint;
  68. Function WaitProcess (Pid:cint):cint; { like WaitPid(PID,@result,0) Handling of Signal interrupts (errno=EINTR), returning the Exitcode of Process (>=0) or -Status if terminated}
  69. Function WIFSTOPPED (Status: Integer): Boolean;
  70. Function W_EXITCODE (ReturnCode, Signal: Integer): Integer;
  71. Function W_STOPCODE (Signal: Integer): Integer;
  72. {**************************
  73. File Handling
  74. ***************************}
  75. {$ifndef FPC_USE_LIBC} // defined using cdecl for libc.
  76. Function fsync (fd : cint) : cint;
  77. Function fpFlock (fd,mode : cint) : cint ;
  78. Function fStatFS (Fd: cint;Var Info:tstatfs):cint;
  79. Function StatFS (Path:pchar;Var Info:tstatfs):cint;
  80. {$endif}
  81. Function fpFlock (var T : text;mode : cint) : cint;
  82. Function fpFlock (var F : File;mode : cint) : cint;
  83. Function SelectText (var T:Text;TimeOut :PTimeVal):cint;
  84. Function SelectText (var T:Text;TimeOut :cint):cint;
  85. {**************************
  86. Directory Handling
  87. ***************************}
  88. procedure SeekDir(p:pdir;loc:clong);
  89. function TellDir(p:pdir):clong;
  90. {**************************
  91. Pipe/Fifo/Stream
  92. ***************************}
  93. Function AssignPipe (var pipe_in,pipe_out:cint):cint;
  94. Function AssignPipe (var pipe_in,pipe_out:text):cint;
  95. Function AssignPipe (var pipe_in,pipe_out:file):cint;
  96. //Function PClose (Var F:text) : cint;
  97. //Function PClose (Var F:file) : cint;
  98. Function POpen (var F:text;const Prog:String;rw:char):cint;
  99. Function POpen (var F:file;const Prog:String;rw:char):cint;
  100. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  101. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  102. {$ifdef linux}
  103. Function GetDomainName:String;
  104. {$endif}
  105. Function GetHostName:String;
  106. {**************************
  107. Memory functions
  108. ***************************}
  109. const
  110. PROT_READ = $1; { page can be read }
  111. PROT_WRITE = $2; { page can be written }
  112. PROT_EXEC = $4; { page can be executed }
  113. PROT_NONE = $0; { page can not be accessed }
  114. MAP_SHARED = $1; { Share changes }
  115. // MAP_PRIVATE = $2; { Changes are private }
  116. MAP_TYPE = $f; { Mask for type of mapping }
  117. MAP_FIXED = $10; { Interpret addr exactly }
  118. // MAP_ANONYMOUS = $20; { don't use a file }
  119. {$ifdef Linux}
  120. MAP_GROWSDOWN = $100; { stack-like segment }
  121. MAP_DENYWRITE = $800; { ETXTBSY }
  122. MAP_EXECUTABLE = $1000; { mark it as an executable }
  123. MAP_LOCKED = $2000; { pages are locked }
  124. MAP_NORESERVE = $4000; { don't check for reservations }
  125. {$else}
  126. {$ifdef FreeBSD}
  127. // FreeBSD defines MAP_COPY=MAP_PRIVATE=$2;
  128. MAP_FILE = $0000; { map from file (default) }
  129. MAP_ANON = $1000; { allocated from memory, swap space }
  130. MAP_RENAME = $0020; { Sun: rename private pages to file }
  131. MAP_NORESERVE = $0040; { Sun: don't reserve needed swap area }
  132. MAP_INHERIT = $0080; { region is retained after exec }
  133. MAP_NOEXTEND = $0100; { for MAP_FILE, don't change file size }
  134. MAP_HASSEMAPHORE = $0200; { region may contain semaphores }
  135. MAP_STACK = $0400; { region grows down, like a stack }
  136. MAP_NOSYNC = $0800; { page to but do not sync underlying file}
  137. MAP_NOCORE = $20000;{ dont include these pages in a coredump}
  138. {$endif}
  139. {$endif}
  140. {**************************
  141. Utility functions
  142. ***************************}
  143. Type
  144. TFSearchOption = (NoCurrentDirectory,
  145. CurrentDirectoryFirst,
  146. CurrentDirectoryLast);
  147. Function FSearch (const path:AnsiString;dirlist:Ansistring;CurrentDirStrategy:TFSearchOption):AnsiString;
  148. Function FSearch (const path:AnsiString;dirlist:AnsiString):AnsiString;
  149. procedure SigRaise (sig:integer);
  150. {$ifdef FPC_USE_LIBC}
  151. const clib = 'c';
  152. {$i unxdeclh.inc}
  153. {$else}
  154. {$i unxsysch.inc} // calls used in system and not reexported from baseunix
  155. {$endif}
  156. {******************************************************************************
  157. Implementation
  158. ******************************************************************************}
  159. {$i unxovlh.inc}
  160. Implementation
  161. Uses Strings{$ifndef FPC_USE_LIBC},Syscall{$endif};
  162. {$i unxovl.inc}
  163. {$ifndef FPC_USE_LIBC}
  164. {$i syscallh.inc}
  165. {$i unxsysc.inc}
  166. {$endif}
  167. { Get the definitions of textrec and filerec }
  168. {$i textrec.inc}
  169. {$i filerec.inc}
  170. {$i unxfunc.inc} { Platform specific implementations }
  171. Function getenv(name:string):Pchar; external name 'FPC_SYSC_FPGETENV';
  172. {******************************************************************************
  173. Process related calls
  174. ******************************************************************************}
  175. { Most calls of WaitPID do not handle the result correctly, this funktion treats errors more correctly }
  176. Function WaitProcess(Pid:cint):cint; { like WaitPid(PID,@result,0) Handling of Signal interrupts (errno=EINTR), returning the Exitcode of Process (>=0) or -Status if terminated}
  177. var
  178. r,s : cint;
  179. begin
  180. s:=$7F00;
  181. repeat
  182. r:=fpWaitPid(Pid,@s,0);
  183. if (r=-1) and (fpgeterrno=ESysEIntr) Then
  184. r:=0;
  185. until (r<>0);
  186. if (r=-1) or (r=0) then // 0 is not a valid return and should never occur (it means status invalid when using WNOHANG)
  187. WaitProcess:=-1 // return -1 to indicate an error. fpwaitpid updated it.
  188. else
  189. begin
  190. if wifexited(s) then
  191. WaitProcess:=wexitstatus(s)
  192. else if (s>0) then // Until now there is not use of the highest bit , but check this for the future
  193. WaitProcess:=-s // normal case
  194. else
  195. WaitProcess:=s; // s<0 should not occur, but wie return also a negativ value
  196. end;
  197. end;
  198. function intFpExecVEMaybeP (Const PathName:AnsiString;Args,MyEnv:ppchar;SearchPath:Boolean):cint;
  199. // does an ExecVE, but still has to handle P
  200. // execv variants call this directly, execl variants indirectly via
  201. // intfpexecl
  202. Var
  203. NewCmd : ansistring;
  204. ThePath : AnsiString;
  205. Begin
  206. If SearchPath and (pos('/',pathname)=0) Then
  207. Begin
  208. // The above could be better. (check if not escaped/quoted '/'s) ?
  209. // (Jilles says this is ok)
  210. // Stevens says only search if newcmd contains no '/'
  211. // fsearch is not ansistring clean yet.
  212. ThePath:=fpgetenv('PATH');
  213. if thepath='' then
  214. thepath:='.'; // FreeBSD uses _PATH_DEFPATH = /usr/bin:/bin
  215. // but a quick check showed that _PATH_DEFPATH
  216. // varied from OS to OS
  217. newcmd:=FSearch(pathname,thepath,NoCurrentDirectory);
  218. // FreeBSD libc keeps on trying till a file is successfully run.
  219. // Stevens says "try each path prefix"
  220. // execp puts newcmd here.
  221. args^:=pchar(newcmd);
  222. End else
  223. newcmd:=pathname;
  224. // repeat
  225. // if searchpath then args^:=pchar(commandtorun)
  226. IntFpExecVEMaybeP:=fpExecVE(newcmd,Args,MyEnv);
  227. {
  228. // Code that if exec fails due to permissions, tries to run it with sh
  229. // Should we deallocate p on fail? -> no fpexit is run no matter what
  230. //
  231. }
  232. // if intfpexecvemaybep=-1 then zoekvolgende file.
  233. // until (Goexit) or SearchExit;
  234. {
  235. If IntFpExec=-1 Then
  236. Begin
  237. Error:=fpGetErrno
  238. Case Error of
  239. ESysE2Big : Exit(-1);
  240. ESysELoop,
  241. : Exit(-1);
  242. }
  243. end;
  244. function intFpExecl (Const PathName:AnsiString;const s:array of ansistring;MyEnv:ppchar;SearchPath:Boolean):cint;
  245. { Handles the array of ansistring -> ppchar conversion.
  246. Base for the the "l" variants.
  247. }
  248. var p:ppchar;
  249. begin
  250. If PathName='' Then
  251. Begin
  252. fpsetErrno(ESysEnoEnt);
  253. Exit(-1); // Errno?
  254. End;
  255. p:=ArrayStringToPPchar(s,1);
  256. if p=NIL Then
  257. Begin
  258. GetMem(p,2*sizeof(pchar));
  259. if p=nil then
  260. begin
  261. {$ifdef xunix}
  262. fpseterrno(ESysEnoMem);
  263. {$endif}
  264. fpseterrno(ESysEnoEnt);
  265. exit(-1);
  266. end;
  267. p[1]:=nil;
  268. End;
  269. p^:=pchar(PathName);
  270. IntFPExecL:=intFpExecVEMaybeP(PathName,p,MyEnv,SearchPath);
  271. // If we come here, no attempts were executed successfully.
  272. Freemem(p);
  273. end;
  274. function FpExecLE (Const PathName:AnsiString;const S:Array Of AnsiString;MyEnv:ppchar):cint;
  275. Begin
  276. FpExecLE:=intFPExecl(PathName,s,MyEnv,false);
  277. End;
  278. function FpExecL(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  279. Begin
  280. FpExecL:=intFPExecl(PathName,S,EnvP,false);
  281. End;
  282. function FpExecLP(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  283. Begin
  284. FpExecLP:=intFPExecl(PathName,S,EnvP,True);
  285. End;
  286. function FpExecV(Const PathName:AnsiString;args:ppchar):cint;
  287. Begin
  288. fpexecV:=intFpExecVEMaybeP (PathName,args,envp,false);
  289. End;
  290. function FpExecVP(Const PathName:AnsiString;args:ppchar):cint;
  291. Begin
  292. fpexecVP:=intFpExecVEMaybeP (PathName,args,envp,true);
  293. End;
  294. function FpExecVPE(Const PathName:AnsiString;args,env:ppchar):cint;
  295. Begin
  296. fpexecVPE:=intFpExecVEMaybeP (PathName,args,env,true);
  297. End;
  298. // exect and execvP (ExecCapitalP) are not implement
  299. // Non POSIX anyway.
  300. // Exect turns on tracing for the process
  301. // execvP has the searchpath as array of ansistring ( const char *search_path)
  302. {$define FPC_USE_FPEXEC}
  303. Function Shell(const Command:String):cint;
  304. {
  305. Executes the shell, and passes it the string Command. (Through /bin/sh -c)
  306. The current environment is passed to the shell.
  307. It waits for the shell to exit, and returns its exit status.
  308. If the Exec call failed exit status 127 is reported.
  309. }
  310. { Changed the structure:
  311. - the previous version returns an undefinied value if fork fails
  312. - it returns the status of Waitpid instead of the Process returnvalue (see the doc to Shell)
  313. - it uses exit(127) not ExitProc (The Result in pp386: going on Compiling in 2 processes!)
  314. - ShellArgs are now released
  315. - The Old CreateShellArg gives back pointers to a local var
  316. }
  317. var
  318. {$ifndef FPC_USE_FPEXEC}
  319. p : ppchar;
  320. {$endif}
  321. pid : cint;
  322. begin
  323. {$ifndef FPC_USE_FPEXEC}
  324. p:=CreateShellArgv(command);
  325. {$endif}
  326. pid:=fpfork;
  327. if pid=0 then // We are in the Child
  328. begin
  329. {This is the child.}
  330. {$ifndef FPC_USE_FPEXEC}
  331. fpExecve(p^,p,envp);
  332. {$else}
  333. fpexecl('/bin/sh',['-c',Command]);
  334. {$endif}
  335. fpExit(127); // was Exit(127)
  336. end
  337. else if (pid<>-1) then // Successfull started
  338. Shell:=WaitProcess(pid)
  339. else // no success
  340. Shell:=-1; // indicate an error
  341. {$ifndef FPC_USE_FPEXEC}
  342. FreeShellArgV(p);
  343. {$endif}
  344. end;
  345. Function Shell(const Command:AnsiString):cint;
  346. {
  347. AnsiString version of Shell
  348. }
  349. var
  350. {$ifndef FPC_USE_FPEXEC}
  351. p : ppchar;
  352. {$endif}
  353. pid : cint;
  354. begin { Changes as above }
  355. {$ifndef FPC_USE_FPEXEC}
  356. p:=CreateShellArgv(command);
  357. {$endif}
  358. pid:=fpfork;
  359. if pid=0 then // We are in the Child
  360. begin
  361. {$ifdef FPC_USE_FPEXEC}
  362. fpexecl('/bin/sh',['-c',Command]);
  363. {$else}
  364. fpExecve(p^,p,envp);
  365. {$endif}
  366. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  367. end
  368. else if (pid<>-1) then // Successfull started
  369. Shell:=WaitProcess(pid)
  370. else // no success
  371. Shell:=-1;
  372. {$ifndef FPC_USE_FPEXEC}
  373. FreeShellArgV(p);
  374. {$ENDIF}
  375. end;
  376. {$ifdef FPC_USE_LIBC}
  377. function xfpsystem(p:pchar):cint; cdecl; external clib name 'system';
  378. Function fpSystem(const Command:AnsiString):cint;
  379. begin
  380. fpsystem:=xfpsystem(pchar(command));
  381. end;
  382. {$else}
  383. Function fpSystem(const Command:AnsiString):cint;
  384. {
  385. AnsiString version of Shell
  386. }
  387. var
  388. pid,savedpid : cint;
  389. pstat : cint;
  390. ign,intact,
  391. quitact : SigactionRec;
  392. newsigblock,
  393. oldsigblock : tsigset;
  394. begin { Changes as above }
  395. if command='' then exit(1);
  396. ign.sa_handler:=SigActionHandler(SIG_IGN);
  397. fpsigemptyset(ign.sa_mask);
  398. ign.sa_flags:=0;
  399. fpsigaction(SIGINT, @ign, @intact);
  400. fpsigaction(SIGQUIT, @ign, @quitact);
  401. fpsigemptyset(newsigblock);
  402. fpsigaddset(newsigblock,SIGCHLD);
  403. fpsigprocmask(SIG_BLOCK,{$ifdef ver1_0}@{$endif}newsigblock,{$ifdef ver1_0}@{$endif}oldsigblock);
  404. pid:=fpfork;
  405. if pid=0 then // We are in the Child
  406. begin
  407. fpsigaction(SIGINT,@intact,NIL);
  408. fpsigaction(SIGQUIT,@quitact,NIL);
  409. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  410. fpexecl('/bin/sh',['-c',Command]);
  411. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  412. end
  413. else if (pid<>-1) then // Successfull started
  414. begin
  415. savedpid:=pid;
  416. repeat
  417. pid:=fpwaitpid(savedpid,@pstat,0);
  418. until (pid<>-1) and (fpgeterrno()<>ESysEintr);
  419. if pid=-1 Then
  420. fpsystem:=-1
  421. else
  422. fpsystem:=pstat;
  423. end
  424. else // no success
  425. fpsystem:=-1;
  426. fpsigaction(SIGINT,@intact,NIL);
  427. fpsigaction(SIGQUIT,@quitact,NIL);
  428. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  429. end;
  430. {$endif}
  431. Function WIFSTOPPED(Status: Integer): Boolean;
  432. begin
  433. WIFSTOPPED:=((Status and $FF)=$7F);
  434. end;
  435. Function W_EXITCODE(ReturnCode, Signal: Integer): Integer;
  436. begin
  437. W_EXITCODE:=(ReturnCode shl 8) or Signal;
  438. end;
  439. Function W_STOPCODE(Signal: Integer): Integer;
  440. begin
  441. W_STOPCODE:=(Signal shl 8) or $7F;
  442. end;
  443. {$IFNDEF DONT_READ_TIMEZONE}
  444. { Include timezone handling routines which use /usr/share/timezone info }
  445. {$i timezone.inc}
  446. {$endif}
  447. {******************************************************************************
  448. FileSystem calls
  449. ******************************************************************************}
  450. Function fpFlock (var T : text;mode : cint) : cint;
  451. begin
  452. fpFlock:=fpFlock(TextRec(T).Handle,mode);
  453. end;
  454. Function fpFlock (var F : File;mode : cint) :cint;
  455. begin
  456. fpFlock:=fpFlock(FileRec(F).Handle,mode);
  457. end;
  458. Function SelectText(var T:Text;TimeOut :PTimeval):cint;
  459. Var
  460. F:TfdSet;
  461. begin
  462. if textrec(t).mode=fmclosed then
  463. begin
  464. fpseterrno(ESysEBADF);
  465. exit(-1);
  466. end;
  467. FpFD_ZERO(f);
  468. fpFD_SET(textrec(T).handle,f);
  469. if textrec(T).mode=fminput then
  470. SelectText:=fpselect(textrec(T).handle+1,@f,nil,nil,TimeOut)
  471. else
  472. SelectText:=fpselect(textrec(T).handle+1,nil,@f,nil,TimeOut);
  473. end;
  474. Function SelectText(var T:Text;TimeOut :cint):cint;
  475. var
  476. p : PTimeVal;
  477. tv : TimeVal;
  478. begin
  479. if TimeOut=-1 then
  480. p:=nil
  481. else
  482. begin
  483. tv.tv_Sec:=Timeout div 1000;
  484. tv.tv_Usec:=(Timeout mod 1000)*1000;
  485. p:=@tv;
  486. end;
  487. SelectText:=SelectText(T,p);
  488. end;
  489. {******************************************************************************
  490. Directory
  491. ******************************************************************************}
  492. procedure SeekDir(p:pdir;loc:clong);
  493. begin
  494. if p=nil then
  495. begin
  496. fpseterrno(ESysEBADF);
  497. exit;
  498. end;
  499. {$ifndef bsd}
  500. p^.dd_nextoff:=fplseek(p^.dd_fd,loc,seek_set);
  501. {$endif}
  502. p^.dd_size:=0;
  503. p^.dd_loc:=0;
  504. end;
  505. function TellDir(p:pdir):clong;
  506. begin
  507. if p=nil then
  508. begin
  509. fpseterrno(ESysEBADF);
  510. telldir:=-1;
  511. exit;
  512. end;
  513. telldir:=fplseek(p^.dd_fd,0,seek_cur)
  514. { We could try to use the nextoff field here, but on my 1.2.13
  515. kernel, this gives nothing... This may have to do with
  516. the readdir implementation of libc... I also didn't find any trace of
  517. the field in the kernel code itself, So I suspect it is an artifact of libc.
  518. Michael. }
  519. end;
  520. {******************************************************************************
  521. Pipes/Fifo
  522. ******************************************************************************}
  523. Procedure OpenPipe(var F:Text);
  524. begin
  525. case textrec(f).mode of
  526. fmoutput :
  527. if textrec(f).userdata[1]<>P_OUT then
  528. textrec(f).mode:=fmclosed;
  529. fminput :
  530. if textrec(f).userdata[1]<>P_IN then
  531. textrec(f).mode:=fmclosed;
  532. else
  533. textrec(f).mode:=fmclosed;
  534. end;
  535. end;
  536. Function IOPipe(var F:text):cint;
  537. begin
  538. IOPipe:=0;
  539. case textrec(f).mode of
  540. fmoutput :
  541. begin
  542. { first check if we need something to write, else we may
  543. get a SigPipe when Close() is called (PFV) }
  544. if textrec(f).bufpos>0 then
  545. IOPipe:=fpwrite(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufpos);
  546. end;
  547. fminput : Begin
  548. textrec(f).bufend:=fpread(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufsize);
  549. IOPipe:=textrec(f).bufend;
  550. End;
  551. end;
  552. textrec(f).bufpos:=0;
  553. end;
  554. Function FlushPipe(var F:Text):cint;
  555. begin
  556. FlushPipe:=0;
  557. if (textrec(f).mode=fmoutput) and (textrec(f).bufpos<>0) then
  558. FlushPipe:=IOPipe(f);
  559. textrec(f).bufpos:=0;
  560. end;
  561. Function ClosePipe(var F:text):cint;
  562. begin
  563. textrec(f).mode:=fmclosed;
  564. ClosePipe:=fpclose(textrec(f).handle);
  565. end;
  566. Function AssignPipe(var pipe_in,pipe_out:text):cint;
  567. {
  568. Sets up a pair of file variables, which act as a pipe. The first one can
  569. be read from, the second one can be written to.
  570. }
  571. var
  572. f_in,f_out : cint;
  573. begin
  574. if AssignPipe(f_in,f_out)=-1 then
  575. exit(-1);
  576. { Set up input }
  577. Assign(Pipe_in,'');
  578. Textrec(Pipe_in).Handle:=f_in;
  579. Textrec(Pipe_in).Mode:=fmInput;
  580. Textrec(Pipe_in).userdata[1]:=P_IN;
  581. TextRec(Pipe_in).OpenFunc:=@OpenPipe;
  582. TextRec(Pipe_in).InOutFunc:=@IOPipe;
  583. TextRec(Pipe_in).FlushFunc:=@FlushPipe;
  584. TextRec(Pipe_in).CloseFunc:=@ClosePipe;
  585. { Set up output }
  586. Assign(Pipe_out,'');
  587. Textrec(Pipe_out).Handle:=f_out;
  588. Textrec(Pipe_out).Mode:=fmOutput;
  589. Textrec(Pipe_out).userdata[1]:=P_OUT;
  590. TextRec(Pipe_out).OpenFunc:=@OpenPipe;
  591. TextRec(Pipe_out).InOutFunc:=@IOPipe;
  592. TextRec(Pipe_out).FlushFunc:=@FlushPipe;
  593. TextRec(Pipe_out).CloseFunc:=@ClosePipe;
  594. AssignPipe:=0;
  595. end;
  596. Function AssignPipe(var pipe_in,pipe_out:file):cint;
  597. {
  598. Sets up a pair of file variables, which act as a pipe. The first one can
  599. be read from, the second one can be written to.
  600. If the operation was unsuccesful,
  601. }
  602. var
  603. f_in,f_out : cint;
  604. begin
  605. if AssignPipe(f_in,f_out)=-1 then
  606. exit(-1);
  607. { Set up input }
  608. Assign(Pipe_in,'');
  609. Filerec(Pipe_in).Handle:=f_in;
  610. Filerec(Pipe_in).Mode:=fmInput;
  611. Filerec(Pipe_in).recsize:=1;
  612. Filerec(Pipe_in).userdata[1]:=P_IN;
  613. { Set up output }
  614. Assign(Pipe_out,'');
  615. Filerec(Pipe_out).Handle:=f_out;
  616. Filerec(Pipe_out).Mode:=fmoutput;
  617. Filerec(Pipe_out).recsize:=1;
  618. Filerec(Pipe_out).userdata[1]:=P_OUT;
  619. AssignPipe:=0;
  620. end;
  621. Function PCloseText(Var F:text):cint;
  622. {
  623. May not use @PClose due overloading
  624. }
  625. begin
  626. PCloseText:=PClose(f);
  627. end;
  628. function POpen(var F:text;const Prog:String;rw:char):cint;
  629. {
  630. Starts the program in 'Prog' and makes it's input or out put the
  631. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  632. F, will be read from stdin by the program in 'Prog'. The inverse is true
  633. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  634. read from 'f'.
  635. }
  636. var
  637. pipi,
  638. pipo : text;
  639. pid : pid_t;
  640. pl : ^cint;
  641. {$ifndef FPC_USE_FPEXEC}
  642. pp : ppchar;
  643. {$endif not FPC_USE_FPEXEC}
  644. ret : cint;
  645. begin
  646. rw:=upcase(rw);
  647. if not (rw in ['R','W']) then
  648. begin
  649. FpSetErrno(ESysEnoent);
  650. exit(-1);
  651. end;
  652. if AssignPipe(pipi,pipo)=-1 Then
  653. Exit(-1);
  654. pid:=fpfork; // vfork in FreeBSD.
  655. if pid=-1 then
  656. begin
  657. close(pipi);
  658. close(pipo);
  659. exit(-1);
  660. end;
  661. if pid=0 then
  662. begin
  663. { We're in the child }
  664. if rw='W' then
  665. begin
  666. close(pipo);
  667. ret:=fpdup2(pipi,input);
  668. close(pipi);
  669. if ret=-1 then
  670. halt(127);
  671. end
  672. else
  673. begin
  674. close(pipi);
  675. ret:=fpdup2(pipo,output);
  676. close(pipo);
  677. if ret=-1 then
  678. halt(127);
  679. end;
  680. {$ifdef FPC_USE_FPEXEC}
  681. fpexecl('/bin/sh',['-c',Prog]);
  682. {$else}
  683. pp:=createshellargv(prog);
  684. fpExecve(pp^,pp,envp);
  685. {$endif}
  686. halt(127);
  687. end
  688. else
  689. begin
  690. { We're in the parent }
  691. if rw='W' then
  692. begin
  693. close(pipi);
  694. f:=pipo;
  695. textrec(f).bufptr:=@textrec(f).buffer;
  696. end
  697. else
  698. begin
  699. close(pipo);
  700. f:=pipi;
  701. textrec(f).bufptr:=@textrec(f).buffer;
  702. end;
  703. {Save the process ID - needed when closing }
  704. pl:=@(textrec(f).userdata[2]);
  705. pl^:=pid;
  706. textrec(f).closefunc:=@PCloseText;
  707. end;
  708. ret:=0;
  709. end;
  710. Function POpen(var F:file;const Prog:String;rw:char):cint;
  711. {
  712. Starts the program in 'Prog' and makes it's input or out put the
  713. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  714. F, will be read from stdin by the program in 'Prog'. The inverse is true
  715. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  716. read from 'f'.
  717. }
  718. var
  719. pipi,
  720. pipo : file;
  721. pid : cint;
  722. pl : ^cint;
  723. {$ifndef FPC_USE_FPEXEC}
  724. p,pp : ppchar;
  725. temp : string[255];
  726. {$endif not FPC_USE_FPEXEC}
  727. ret : cint;
  728. begin
  729. rw:=upcase(rw);
  730. if not (rw in ['R','W']) then
  731. begin
  732. FpSetErrno(ESysEnoent);
  733. exit(-1);
  734. end;
  735. ret:=AssignPipe(pipi,pipo);
  736. if ret=-1 then
  737. exit(-1);
  738. pid:=fpfork;
  739. if pid=-1 then
  740. begin
  741. close(pipi);
  742. close(pipo);
  743. exit(-1);
  744. end;
  745. if pid=0 then
  746. begin
  747. { We're in the child }
  748. if rw='W' then
  749. begin
  750. close(pipo);
  751. ret:=fpdup2(filerec(pipi).handle,stdinputhandle);
  752. close(pipi);
  753. if ret=-1 then
  754. halt(127);
  755. end
  756. else
  757. begin
  758. close(pipi);
  759. ret:=fpdup2(filerec(pipo).handle,stdoutputhandle);
  760. close(pipo);
  761. if ret=1 then
  762. halt(127);
  763. end;
  764. {$ifdef FPC_USE_FPEXEC}
  765. fpexecl('/bin/sh',['-c',Prog]);
  766. {$else}
  767. getmem(pp,sizeof(pchar)*4);
  768. temp:='/bin/sh'#0'-c'#0+prog+#0;
  769. p:=pp;
  770. p^:=@temp[1];
  771. inc(p);
  772. p^:=@temp[9];
  773. inc(p);
  774. p^:=@temp[12];
  775. inc(p);
  776. p^:=Nil;
  777. fpExecve(ansistring('/bin/sh'),pp,envp);
  778. {$endif}
  779. halt(127);
  780. end
  781. else
  782. begin
  783. { We're in the parent }
  784. if rw='W' then
  785. begin
  786. close(pipi);
  787. f:=pipo;
  788. end
  789. else
  790. begin
  791. close(pipo);
  792. f:=pipi;
  793. end;
  794. {Save the process ID - needed when closing }
  795. pl:=@(filerec(f).userdata[2]);
  796. pl^:=pid;
  797. end;
  798. POpen:=0;
  799. end;
  800. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  801. {
  802. Starts the program in 'Prog' and makes its input and output the
  803. other end of two pipes, which are the stdin and stdout of a program
  804. specified in 'Prog'.
  805. streamout can be used to write to the program, streamin can be used to read
  806. the output of the program. See the following diagram :
  807. Parent Child
  808. STreamout --> Input
  809. Streamin <-- Output
  810. Return value is the process ID of the process being spawned, or -1 in case of failure.
  811. }
  812. var
  813. pipi,
  814. pipo : text;
  815. pid : cint;
  816. pl : ^cint;
  817. begin
  818. AssignStream:=-1;
  819. if AssignPipe(streamin,pipo)=-1 Then
  820. exit(-1);
  821. if AssignPipe(pipi,streamout)=-1 Then // shouldn't this close streamin and pipo?
  822. exit(-1);
  823. pid:=fpfork;
  824. if pid=-1 then
  825. begin
  826. close(pipi);
  827. close(pipo);
  828. close (streamin);
  829. close (streamout);
  830. exit;
  831. end;
  832. if pid=0 then
  833. begin
  834. { We're in the child }
  835. { Close what we don't need }
  836. close(streamout);
  837. close(streamin);
  838. if fpdup2(pipi,input)=-1 Then
  839. halt(127);
  840. close(pipi);
  841. If fpdup2(pipo,output)=-1 Then
  842. halt (127);
  843. close(pipo);
  844. fpExecl(Prog,args);
  845. halt(127);
  846. end
  847. else
  848. begin
  849. { we're in the parent}
  850. close(pipo);
  851. close(pipi);
  852. {Save the process ID - needed when closing }
  853. pl:=@(textrec(StreamIn).userdata[2]);
  854. pl^:=pid;
  855. textrec(StreamIn).closefunc:=@PCloseText;
  856. {Save the process ID - needed when closing }
  857. pl:=@(textrec(StreamOut).userdata[2]);
  858. pl^:=pid;
  859. textrec(StreamOut).closefunc:=@PCloseText;
  860. AssignStream:=Pid;
  861. end;
  862. end;
  863. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  864. {
  865. Starts the program in 'prog' and makes its input, output and error output the
  866. other end of three pipes, which are the stdin, stdout and stderr of a program
  867. specified in 'prog'.
  868. StreamOut can be used to write to the program, StreamIn can be used to read
  869. the output of the program, StreamErr reads the error output of the program.
  870. See the following diagram :
  871. Parent Child
  872. StreamOut --> StdIn (input)
  873. StreamIn <-- StdOut (output)
  874. StreamErr <-- StdErr (error output)
  875. }
  876. var
  877. PipeIn, PipeOut, PipeErr: text;
  878. pid: cint;
  879. pl: ^cint;
  880. begin
  881. AssignStream := -1;
  882. // Assign pipes
  883. if AssignPipe(StreamIn, PipeOut)=-1 Then
  884. Exit(-1);
  885. If AssignPipe(StreamErr, PipeErr)=-1 Then
  886. begin
  887. Close(StreamIn);
  888. Close(PipeOut);
  889. exit(-1);
  890. end;
  891. if AssignPipe(PipeIn, StreamOut)=-1 Then
  892. begin
  893. Close(StreamIn);
  894. Close(PipeOut);
  895. Close(StreamErr);
  896. Close(PipeErr);
  897. exit(-1);
  898. end;
  899. // Fork
  900. pid := fpFork;
  901. if pid=-1 then begin
  902. Close(StreamIn);
  903. Close(PipeOut);
  904. Close(StreamErr);
  905. Close(PipeErr);
  906. Close(PipeIn);
  907. Close(StreamOut);
  908. exit(-1);
  909. end;
  910. if pid = 0 then begin
  911. // *** We are in the child ***
  912. // Close what we don not need
  913. Close(StreamOut);
  914. Close(StreamIn);
  915. Close(StreamErr);
  916. // Connect pipes
  917. if fpdup2(PipeIn, Input)=-1 Then
  918. Halt(127);
  919. Close(PipeIn);
  920. if fpdup2(PipeOut, Output)=-1 Then
  921. Halt(127);
  922. Close(PipeOut);
  923. if fpdup2(PipeErr, StdErr)=-1 Then
  924. Halt(127);
  925. Close(PipeErr);
  926. // Execute program
  927. fpExecl(Prog,args);
  928. Halt(127);
  929. end else begin
  930. // *** We are in the parent ***
  931. Close(PipeErr);
  932. Close(PipeOut);
  933. Close(PipeIn);
  934. // Save the process ID - needed when closing
  935. pl := @(TextRec(StreamIn).userdata[2]);
  936. pl^ := pid;
  937. TextRec(StreamIn).closefunc := @PCloseText;
  938. // Save the process ID - needed when closing
  939. pl := @(TextRec(StreamOut).userdata[2]);
  940. pl^ := pid;
  941. TextRec(StreamOut).closefunc := @PCloseText;
  942. // Save the process ID - needed when closing
  943. pl := @(TextRec(StreamErr).userdata[2]);
  944. pl^ := pid;
  945. TextRec(StreamErr).closefunc := @PCloseText;
  946. AssignStream := pid;
  947. end;
  948. end;
  949. {******************************************************************************
  950. General information calls
  951. ******************************************************************************}
  952. {$ifdef Linux}
  953. Function GetDomainName:String; { linux only!}
  954. // domainname is a glibc extension.
  955. {
  956. Get machines domain name. Returns empty string if not set.
  957. }
  958. Var
  959. Sysn : utsname;
  960. begin
  961. If fpUname(sysn)<>0 then
  962. getdomainname:=''
  963. else
  964. getdomainname:=strpas(@Sysn.domain[0]);
  965. end;
  966. {$endif}
  967. {$ifdef BSD}
  968. function intGetDomainName(Name:PChar; NameLen:Cint):cint;
  969. {$ifndef FPC_USE_LIBC}
  970. external name 'FPC_SYSC_GETDOMAINNAME';
  971. {$else FPC_USE_LIBC}
  972. cdecl; external clib name 'getdomainname';
  973. {$endif FPC_USE_LIBC}
  974. Function GetDomainName:String; { linux only!}
  975. // domainname is a glibc extension.
  976. {
  977. Get machines domain name. Returns empty string if not set.
  978. }
  979. begin
  980. if intGetDomainName(@getdomainname[1],255)=-1 then
  981. getdomainname:=''
  982. else
  983. getdomainname[0]:=chr(strlen(@getdomainname[1]));
  984. end;
  985. {$endif}
  986. Function GetHostName:String;
  987. {
  988. Get machines name. Returns empty string if not set.
  989. }
  990. Var
  991. Sysn : utsname;
  992. begin
  993. If fpuname(sysn)=-1 then
  994. gethostname:=''
  995. else
  996. gethostname:=strpas(@Sysn.nodename[0]);
  997. end;
  998. {******************************************************************************
  999. Signal handling calls
  1000. ******************************************************************************}
  1001. procedure SigRaise(sig:integer);
  1002. begin
  1003. fpKill(fpGetPid,Sig);
  1004. end;
  1005. {******************************************************************************
  1006. Utility calls
  1007. ******************************************************************************}
  1008. Function FSearch(const path:AnsiString;dirlist:Ansistring;CurrentDirStrategy:TFSearchOption):AnsiString;
  1009. {
  1010. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1011. returns an empty string if not found. Wildcards are NOT allowed.
  1012. If dirlist is empty, it is set to '.'
  1013. This function tries to make FSearch use ansistrings, and decrease
  1014. stringhandling overhead at the same time.
  1015. }
  1016. Var
  1017. mydir,NewDir : ansistring;
  1018. p1 : cint;
  1019. Info : Stat;
  1020. i,j : cint;
  1021. p : pchar;
  1022. Begin
  1023. if CurrentDirStrategy=CurrentDirectoryFirst Then
  1024. Dirlist:='.:'+dirlist; {Make sure current dir is first to be searched.}
  1025. if CurrentDirStrategy=CurrentDirectoryLast Then
  1026. Dirlist:=dirlist+':.'; {Make sure current dir is last to be searched.}
  1027. {Replace ':' and ';' with #0}
  1028. for p1:=1 to length(dirlist) do
  1029. if (dirlist[p1]=':') or (dirlist[p1]=';') then
  1030. dirlist[p1]:=#0;
  1031. {Check for WildCards}
  1032. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1033. FSearch:='' {No wildcards allowed in these things.}
  1034. Else
  1035. Begin
  1036. p:=pchar(dirlist);
  1037. i:=length(dirlist);
  1038. j:=1;
  1039. Repeat
  1040. mydir:=ansistring(p);
  1041. if (length(mydir)>0) and (mydir[length(mydir)]<>'/') then
  1042. mydir:=mydir+'/';
  1043. NewDir:=mydir+Path;
  1044. if (FpStat(NewDir,Info)>=0) and
  1045. (not fpS_ISDIR(Info.st_Mode)) then
  1046. Begin
  1047. If Pos('./',NewDir)=1 Then
  1048. Delete(NewDir,1,2);
  1049. {DOS strips off an initial .\}
  1050. End
  1051. Else
  1052. NewDir:='';
  1053. while (j<=i) and (p^<>#0) do begin inc(j); inc(p); end;
  1054. if p^=#0 then inc(p);
  1055. Until (j>=i) or (Length(NewDir) > 0);
  1056. FSearch:=NewDir;
  1057. End;
  1058. End;
  1059. Function FSearch(const path:AnsiString;dirlist:Ansistring):AnsiString;
  1060. Begin
  1061. FSearch:=FSearch(path,dirlist,CurrentDirectoryFirst);
  1062. End;
  1063. {--------------------------------
  1064. Stat.Mode Macro's
  1065. --------------------------------}
  1066. Initialization
  1067. {$IFNDEF DONT_READ_TIMEZONE}
  1068. InitLocalTime;
  1069. {$endif}
  1070. finalization
  1071. {$IFNDEF DONT_READ_TIMEZONE}
  1072. DoneLocalTime;
  1073. {$endif}
  1074. End.
  1075. {
  1076. $Log: unix.pp,v $
  1077. Revision 1.85 2005/03/25 22:53:39 jonas
  1078. * fixed several warnings and notes about unused variables (mainly) or
  1079. uninitialised use of variables/function results (a few)
  1080. Revision 1.84 2005/02/14 17:13:31 peter
  1081. * truncate log
  1082. Revision 1.83 2005/02/13 21:47:56 peter
  1083. * include file cleanup part 2
  1084. Revision 1.82 2005/02/13 20:01:38 peter
  1085. * include file cleanup
  1086. Revision 1.81 2005/02/06 11:20:52 peter
  1087. * threading in system unit
  1088. * removed systhrds unit
  1089. Revision 1.80 2005/01/30 18:01:15 peter
  1090. * signal cleanup for linux
  1091. * sigactionhandler instead of tsigaction for bsds
  1092. * sigcontext moved to cpu dir
  1093. Revision 1.79 2005/01/22 20:56:11 michael
  1094. + Patch for intFpExecVEMaybeP to use the right path (From Colin Western)
  1095. }