unix.pp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Michael Van Canneyt,
  4. BSD parts (c) 2000 by Marco van de Voort
  5. members of the Free Pascal development team.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY;without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. Unit Unix;
  13. Interface
  14. Uses
  15. BaseUnix,UnixType;
  16. // If you deprecated new symbols, please annotate the version.
  17. // this makes it easier to decide if they can already be removed.
  18. {$if (defined(BSD) or defined(SUNOS)) and defined(FPC_USE_LIBC)}
  19. {$define USE_VFORK}
  20. {$endif}
  21. {$i aliasptp.inc}
  22. {$i unxconst.inc} { Get Types and Constants only exported in this unit }
  23. {** File handling **}
  24. Const
  25. P_IN = 1; // pipes (?)
  26. P_OUT = 2;
  27. LOCK_SH = 1; // flock constants ?
  28. LOCK_EX = 2;
  29. LOCK_UN = 8;
  30. LOCK_NB = 4;
  31. // The portable MAP_* and PROT_ constants are exported from unit Unix for compability.
  32. PROT_READ = baseunix.PROT_READ; { page can be read }
  33. PROT_WRITE = baseunix.PROT_WRITE; { page can be written }
  34. PROT_EXEC = baseunix.PROT_EXEC; { page can be executed }
  35. PROT_NONE = baseunix.PROT_NONE; { page can not be accessed }
  36. MAP_FAILED = baseunix.MAP_FAILED; { mmap() failed }
  37. MAP_SHARED = baseunix.MAP_SHARED; { Share changes }
  38. MAP_PRIVATE = baseunix.MAP_PRIVATE; { Changes are private }
  39. MAP_TYPE = baseunix.MAP_TYPE; { Mask for type of mapping }
  40. MAP_FIXED = baseunix.MAP_FIXED; { Interpret addr exactly }
  41. {** Time/Date Handling **}
  42. type
  43. TTZInfo = record
  44. daylight : boolean;
  45. seconds : Longint; // difference from UTC
  46. validsince : int64; // UTC timestamp
  47. validuntil : int64; // UTC timestamp
  48. end;
  49. TTZInfoEx = record
  50. name : array[boolean] of RawByteString; { False = StandardName, True = DaylightName }
  51. leap_correct : longint;
  52. leap_hit : longint;
  53. end;
  54. Function GetTzseconds : Longint;
  55. property Tzseconds : Longint read GetTzseconds;
  56. function Gettzdaylight : boolean;
  57. property tzdaylight : boolean read Gettzdaylight;
  58. function Gettzname(const b : boolean) : string;
  59. property tzname[b : boolean] : string read Gettzname;
  60. function GetTZInfo : TTZInfo;
  61. property TZInfo : TTZInfo read GetTZInfo;
  62. function GetTZInfoEx : TTZInfoEx;
  63. property TZInfoEx : TTZInfoEx read GetTZInfoEx;
  64. procedure SetTZInfo(const ATZInfo: TTZInfo; const ATZInfoEx: TTZInfoEx);
  65. {************ Procedure/Functions ************}
  66. {$ifdef android}
  67. {$define DONT_READ_TIMEZONE}
  68. {$endif android}
  69. {$IFNDEF DONT_READ_TIMEZONE} // allows to disable linking in and trying for platforms
  70. // it doesn't (yet) work for.
  71. { timezone support }
  72. function GetLocalTimezone(timer:cint;timerIsUTC:Boolean;var ATZInfo:TTZInfo;var ATZInfoEx:TTZInfoEx):Boolean;
  73. function GetLocalTimezone(timer:cint;timerIsUTC:Boolean;var ATZInfo:TTZInfo):Boolean;
  74. procedure RefreshTZInfo;
  75. function ReadTimezoneFile(fn:string) : Boolean;
  76. function GetTimezoneFile:string;
  77. Procedure ReReadLocalTime;
  78. {$ENDIF}
  79. Function UniversalToEpoch(year,month,day,hour,minute,second:Word):int64; // use DateUtils.DateTimeToUnix for cross-platform applications
  80. Function LocalToEpoch(year,month,day,hour,minute,second:Word):int64; // use DateUtils.DateTimeToUnix for cross-platform applications
  81. Procedure EpochToLocal(epoch:int64;var year,month,day,hour,minute,second:Word); // use DateUtils.UnixToDateTime for cross-platform applications
  82. Procedure EpochToUniversal(epoch:int64;var year,month,day,hour,minute,second:Word); // use DateUtils.UnixToDateTime for cross-platform applications
  83. Procedure JulianToGregorian(JulianDN:LongInt;Var Year,Month,Day:Word); // use DateUtils.DateTimetoJulianDate for cross-platform applications
  84. Function GregorianToJulian(Year,Month,Day:Longint):LongInt; // use DateUtils.JulianDateToDateTime for cross-platform applications
  85. {** Process Handling **}
  86. function FpExecLE (Const PathName:RawByteString;const S:Array Of RawByteString;MyEnv:ppchar):cint;
  87. function FpExecL (Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  88. function FpExecLP (Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  89. function FpExecLPE(Const PathName:RawByteString;const S:Array Of RawByteString;env:ppchar):cint;
  90. function FpExecV (Const PathName:RawByteString;args:ppchar):cint;
  91. function FpExecVP (Const PathName:RawByteString;args:ppchar):cint;
  92. function FpExecVPE(Const PathName:RawByteString;args,env:ppchar):cint;
  93. Function fpSystem(const Command:RawByteString):cint;
  94. Function WaitProcess (Pid:cint):cint;
  95. Function WIFSTOPPED (Status: Integer): Boolean;
  96. Function W_EXITCODE (ReturnCode, Signal: Integer): Integer;
  97. Function W_STOPCODE (Signal: Integer): Integer;
  98. {** File Handling **}
  99. Function fpFlock (var T : text;mode : cint) : cint;
  100. Function fpFlock (var F : File;mode : cint) : cint;
  101. {** Directory Handling **}
  102. procedure SeekDir(p:pdir;loc:clong);
  103. function TellDir(p:pdir):TOff;
  104. {** Pipe/Fifo/Stream **}
  105. Function AssignPipe (var pipe_in,pipe_out:cint):cint;
  106. Function AssignPipe (var pipe_in,pipe_out:text):cint;
  107. Function AssignPipe (var pipe_in,pipe_out:file):cint;
  108. Function POpen (var F:text;const Prog:RawByteString;rw:char):cint;
  109. Function POpen (var F:file;const Prog:RawByteString;rw:char):cint;
  110. Function POpen (var F:text;const Prog:UnicodeString;rw:char):cint;
  111. Function POpen (var F:file;const Prog:UnicodeString;rw:char):cint;
  112. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  113. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  114. Function GetDomainName:String; deprecated; // because linux only.
  115. Function GetHostName:String;
  116. {** Utility functions **}
  117. Type
  118. TFSearchOption = (NoCurrentDirectory,
  119. CurrentDirectoryFirst,
  120. CurrentDirectoryLast);
  121. Function FSearch (const path:RawByteString;dirlist:RawByteString;CurrentDirStrategy:TFSearchOption):RawByteString;
  122. Function FSearch (const path:RawByteString;dirlist:RawByteString):RawByteString;
  123. Function FSearch (const path:UnicodeString;dirlist:UnicodeString;CurrentDirStrategy:TFSearchOption):UnicodeString;
  124. Function FSearch (const path:UnicodeString;dirlist:UnicodeString):UnicodeString;
  125. {$ifdef FPC_USE_LIBC}
  126. const clib = 'c';
  127. {$i unxdeclh.inc}
  128. {$else}
  129. {$i unxsysch.inc} // calls used in system and not reexported from baseunix
  130. {$endif}
  131. {******************************************************************************
  132. Implementation
  133. ******************************************************************************}
  134. {$i unxovlh.inc}
  135. Implementation
  136. {$ifndef FPC_USE_LIBC}
  137. Uses
  138. Syscall;
  139. {$endif}
  140. {$i unxovl.inc}
  141. {$ifndef FPC_USE_LIBC}
  142. {$i syscallh.inc}
  143. {$i unxsysc.inc}
  144. {$endif}
  145. {$i unxfunc.inc} { Platform specific implementations }
  146. Function getenv(name:string):Pchar; external name 'FPC_SYSC_FPGETENV';
  147. {******************************************************************************
  148. timezone support
  149. ******************************************************************************}
  150. var
  151. CurrentTZinfo : array [0..1] of TTZInfo;
  152. CurrentTzinfoEx : array [0..1] of TTZInfoEx;
  153. CurrentTZindex : LongInt = 0; // current index for CurrentTZinfo/CurrentTZinfoEx - can be only 0 or 1
  154. {$ifdef FPC_HAS_FEATURE_THREADING}
  155. UseTZThreading: Boolean = false;
  156. TZInfoCS: TRTLCriticalSection;
  157. {$endif}
  158. procedure LockTZInfo;
  159. begin
  160. {$if declared(UseTZThreading)}
  161. if UseTZThreading then
  162. EnterCriticalSection(TZInfoCS);
  163. {$endif}
  164. end;
  165. procedure UnlockTZInfo;
  166. begin
  167. {$if declared(UseTZThreading)}
  168. if UseTZThreading then
  169. LeaveCriticalSection(TZInfoCS);
  170. {$endif}
  171. end;
  172. Function GetTzseconds : Longint;
  173. begin
  174. GetTzseconds:=Tzinfo.seconds;
  175. end;
  176. function Gettzdaylight : boolean;
  177. begin
  178. Gettzdaylight:=Tzinfo.daylight;
  179. end;
  180. function Gettzname(const b : boolean) : string;
  181. begin
  182. Gettzname:=TzinfoEx.name[b];
  183. end;
  184. function GetTZInfo : TTZInfo;
  185. var
  186. curtime: time_t;
  187. begin
  188. GetTZInfo:=CurrentTZinfo[InterlockedExchangeAdd(CurrentTZindex, 0)];
  189. curtime:=fptime;
  190. if not((GetTZInfo.validsince+GetTZInfo.seconds<=curtime) and (curtime<GetTZInfo.validuntil+GetTZInfo.seconds)) then
  191. begin
  192. RefreshTZInfo;
  193. GetTZInfo:=CurrentTZinfo[InterlockedExchangeAdd(CurrentTZindex, 0)];
  194. end;
  195. end;
  196. function GetTZInfoEx : TTZInfoEx;
  197. begin
  198. GetTZInfoEx:=CurrentTzinfoEx[InterlockedExchangeAdd(CurrentTZindex, 0)];
  199. end;
  200. procedure SetTZInfo(const ATZInfo: TTZInfo; const ATZInfoEx: TTZInfoEx);
  201. var
  202. OldTZindex,NewTZindex: longint;
  203. begin
  204. LockTZInfo;
  205. OldTZindex:=InterlockedExchangeAdd(CurrentTZindex,0);
  206. if OldTZindex=0 then
  207. NewTZindex:=1
  208. else
  209. NewTZindex:=0;
  210. CurrentTzinfo[NewTZindex]:=ATZInfo;
  211. CurrentTzinfoEx[NewTZindex]:=ATZInfoEx;
  212. InterlockedExchangeAdd(CurrentTZindex,NewTZindex-OldTZindex);
  213. UnlockTZInfo;
  214. end;
  215. Const
  216. {Date Translation}
  217. C1970=2440588;
  218. D0 = 1461;
  219. D1 = 146097;
  220. D2 =1721119;
  221. Procedure JulianToGregorian(JulianDN:LongInt;Var Year,Month,Day:Word);
  222. Var
  223. YYear,XYear,Temp,TempMonth : LongInt;
  224. Begin
  225. Temp:=((JulianDN-D2) shl 2)-1;
  226. JulianDN:=Temp Div D1;
  227. XYear:=(Temp Mod D1) or 3;
  228. YYear:=(XYear Div D0);
  229. Temp:=((((XYear mod D0)+4) shr 2)*5)-3;
  230. Day:=((Temp Mod 153)+5) Div 5;
  231. TempMonth:=Temp Div 153;
  232. If TempMonth>=10 Then
  233. Begin
  234. inc(YYear);
  235. dec(TempMonth,12);
  236. End;
  237. inc(TempMonth,3);
  238. Month := TempMonth;
  239. Year:=YYear+(JulianDN*100);
  240. end;
  241. Procedure EpochToLocal(epoch:Int64;var year,month,day,hour,minute,second:Word);
  242. {
  243. Transforms Epoch time into local time (hour, minute,seconds)
  244. }
  245. Var
  246. lTZInfo: TTZInfo;
  247. Begin
  248. {$if declared(GetLocalTimezone)}
  249. if GetLocalTimezone(epoch,true,lTZInfo) then
  250. inc(Epoch,lTZInfo.seconds)
  251. else { fallback }
  252. {$endif}
  253. inc(Epoch,TZInfo.seconds);
  254. EpochToUniversal(epoch,year,month,day,hour,minute,second);
  255. End;
  256. Procedure EpochToUniversal(epoch:Int64;var year,month,day,hour,minute,second:Word);
  257. {
  258. Transforms Epoch time into universal time (hour, minute,seconds)
  259. }
  260. Var
  261. DateNum: LongInt;
  262. Begin
  263. Datenum:=(Epoch Div 86400) + c1970;
  264. JulianToGregorian(DateNum,Year,Month,day);
  265. Epoch:=Abs(Epoch Mod 86400);
  266. Hour:=Epoch Div 3600;
  267. Epoch:=Epoch Mod 3600;
  268. Minute:=Epoch Div 60;
  269. Second:=Epoch Mod 60;
  270. End;
  271. Function LocalToEpoch(year,month,day,hour,minute,second:Word):Int64;
  272. {
  273. Transforms local time (year,month,day,hour,minutes,second) to Epoch time
  274. (seconds since 00:00, january 1 1970, corrected for local time zone)
  275. }
  276. Var
  277. lTZInfo: TTZInfo;
  278. LocalEpoch: Int64;
  279. Begin
  280. LocalEpoch:=UniversalToEpoch(year,month,day,hour,minute,second);
  281. {$if declared(GetLocalTimezone)}
  282. if GetLocalTimezone(LocalEpoch,false,lTZInfo) then
  283. LocalToEpoch:=LocalEpoch-lTZInfo.seconds
  284. else { fallback }
  285. {$endif}
  286. LocalToEpoch:=LocalEpoch-TZInfo.seconds;
  287. End;
  288. Function UniversalToEpoch(year,month,day,hour,minute,second:Word):Int64;
  289. {
  290. Transforms universal time (year,month,day,hour,minutes,second) to Epoch time
  291. (seconds since 00:00, january 1 1970, corrected for local time zone)
  292. }
  293. Begin
  294. UniversalToEpoch:=(Int64(GregorianToJulian(Year,Month,Day)-c1970)*86400)+
  295. (LongInt(Hour)*3600)+(Longint(Minute)*60)+Second;
  296. End;
  297. Function GregorianToJulian(Year,Month,Day:Longint):LongInt;
  298. Var
  299. Century,XYear: LongInt;
  300. Begin
  301. If Month<=2 Then
  302. Begin
  303. Dec(Year);
  304. Inc(Month,12);
  305. End;
  306. Dec(Month,3);
  307. Century:=(longint(Year Div 100)*D1) shr 2;
  308. XYear:=(longint(Year Mod 100)*D0) shr 2;
  309. GregorianToJulian:=((((Month*153)+2) div 5)+Day)+D2+XYear+Century;
  310. End;
  311. {******************************************************************************
  312. Process related calls
  313. ******************************************************************************}
  314. { Most calls of WaitPID do not handle the result correctly, this funktion treats errors more correctly }
  315. 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}
  316. var
  317. r,s : cint;
  318. begin
  319. s:=$7F00;
  320. repeat
  321. r:=fpWaitPid(Pid,@s,0);
  322. if (r=-1) and (fpgeterrno=ESysEIntr) Then
  323. r:=0;
  324. until (r<>0);
  325. if (r=-1) or (r=0) then // 0 is not a valid return and should never occur (it means status invalid when using WNOHANG)
  326. WaitProcess:=-1 // return -1 to indicate an error. fpwaitpid updated it.
  327. else
  328. begin
  329. if wifexited(s) then
  330. WaitProcess:=wexitstatus(s)
  331. else if (s>0) then // Until now there is not use of the highest bit , but check this for the future
  332. WaitProcess:=-s // normal case
  333. else
  334. WaitProcess:=s; // s<0 should not occur, but wie return also a negativ value
  335. end;
  336. end;
  337. function intFpExecVEMaybeP (Const PathName:RawByteString;Args,MyEnv:ppchar;SearchPath:Boolean):cint;
  338. // does an ExecVE, but still has to handle P
  339. // execv variants call this directly, execl variants indirectly via
  340. // intfpexecl
  341. Var
  342. NewCmd : RawByteString;
  343. ThePath : RawByteString;
  344. Begin
  345. If SearchPath and (pos('/',pathname)=0) Then
  346. Begin
  347. // The above could be better. (check if not escaped/quoted '/'s) ?
  348. // (Jilles says this is ok)
  349. // Stevens says only search if newcmd contains no '/'
  350. // fsearch is not ansistring clean yet.
  351. ThePath:=fpgetenv('PATH');
  352. SetCodePage(ThePath,DefaultSystemCodePage,false);
  353. SetCodePage(ThePath,DefaultFileSystemCodePage,true);
  354. if thepath='' then
  355. thepath:='.'; // FreeBSD uses _PATH_DEFPATH = /usr/bin:/bin
  356. // but a quick check showed that _PATH_DEFPATH
  357. // varied from OS to OS
  358. newcmd:=ToSingleByteFileSystemEncodedFileName(FSearch(pathname,thepath,NoCurrentDirectory));
  359. // FreeBSD libc keeps on trying till a file is successfully run.
  360. // Stevens says "try each path prefix"
  361. // execp puts newcmd here.
  362. args^:=pchar(newcmd);
  363. End else
  364. newcmd:=ToSingleByteFileSystemEncodedFileName(pathname);
  365. // repeat
  366. // if searchpath then args^:=pchar(commandtorun)
  367. IntFpExecVEMaybeP:=fpExecVE(newcmd,Args,MyEnv);
  368. {
  369. // Code that if exec fails due to permissions, tries to run it with sh
  370. // Should we deallocate p on fail? -> no fpexit is run no matter what
  371. //
  372. }
  373. // if intfpexecvemaybep=-1 then seach next file.
  374. // until (Goexit) or SearchExit;
  375. {
  376. If IntFpExec=-1 Then
  377. Begin
  378. Error:=fpGetErrno
  379. Case Error of
  380. ESysE2Big : Exit(-1);
  381. ESysELoop,
  382. : Exit(-1);
  383. }
  384. end;
  385. function intFpExecl (Const PathName:RawByteString;const s:array of RawByteString;MyEnv:ppchar;SearchPath:Boolean):cint;
  386. { Handles the array of ansistring -> ppchar conversion.
  387. Base for the the "l" variants.
  388. }
  389. var p:ppchar;
  390. i:integer;
  391. s2:array of Rawbytestring;
  392. begin
  393. If PathName='' Then
  394. Begin
  395. fpsetErrno(ESysEnoEnt);
  396. Exit(-1); // Errno?
  397. End;
  398. setlength(s2,high(s)+1);
  399. for i:=low(s) to high(s) do
  400. s2[i]:=ToSingleByteFileSystemEncodedFileName(s[i]);
  401. p:=ArrayStringToPPchar(s2,1);
  402. if p=NIL Then
  403. Begin
  404. GetMem(p,2*sizeof(pchar));
  405. if p=nil then
  406. begin
  407. {$ifdef xunix}
  408. fpseterrno(ESysEnoMem);
  409. {$endif}
  410. fpseterrno(ESysEnoEnt);
  411. exit(-1);
  412. end;
  413. p[1]:=nil;
  414. End;
  415. p^:=pchar(PathName);
  416. IntFPExecL:=intFpExecVEMaybeP(PathName,p,MyEnv,SearchPath);
  417. // If we come here, no attempts were executed successfully.
  418. Freemem(p);
  419. end;
  420. function FpExecLE (Const PathName:RawByteString;const S:Array Of RawByteString;MyEnv:ppchar):cint;
  421. Begin
  422. FpExecLE:=intFPExecl(PathName,s,MyEnv,false);
  423. End;
  424. function FpExecL(Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  425. Begin
  426. FpExecL:=intFPExecl(PathName,S,EnvP,false);
  427. End;
  428. function FpExecLP(Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  429. Begin
  430. FpExecLP:=intFPExecl(PathName,S,EnvP,True);
  431. End;
  432. function FpExecLPE(Const PathName:RawByteString;const S:Array Of RawByteString;env:ppchar):cint;
  433. Begin
  434. FpExecLPE:=intFPExecl(PathName,S,Env,True);
  435. End;
  436. function FpExecV(Const PathName:RawByteString;args:ppchar):cint;
  437. Begin
  438. fpexecV:=intFpExecVEMaybeP (PathName,args,envp,false);
  439. End;
  440. function FpExecVP(Const PathName:RawByteString;args:ppchar):cint;
  441. Begin
  442. fpexecVP:=intFpExecVEMaybeP (PathName,args,envp,true);
  443. End;
  444. function FpExecVPE(Const PathName:RawByteString;args,env:ppchar):cint;
  445. Begin
  446. fpexecVPE:=intFpExecVEMaybeP (PathName,args,env,true);
  447. End;
  448. // exect and execvP (ExecCapitalP) are not implement
  449. // Non POSIX anyway.
  450. // Exect turns on tracing for the process
  451. // execvP has the searchpath as array of ansistring ( const char *search_path)
  452. {$define FPC_USE_FPEXEC}
  453. {$if defined(FPC_USE_FPEXEC) and not defined(USE_VFORK)}
  454. {$define SHELL_USE_FPEXEC}
  455. {$endif}
  456. {$ifdef FPC_USE_LIBC}
  457. function xfpsystem(p:pchar):cint; cdecl; external clib name 'system';
  458. Function fpSystem(const Command:RawByteString):cint;
  459. var
  460. cmd: RawByteString;
  461. begin
  462. cmd:=ToSingleByteFileSystemEncodedFileName(Command);
  463. fpsystem:=xfpsystem(pchar(cmd));
  464. end;
  465. {$else}
  466. Function fpSystem(const Command:RawByteString):cint;
  467. var
  468. pid,savedpid : cint;
  469. pstat : cint;
  470. ign,intact,
  471. quitact : SigactionRec;
  472. newsigblock,
  473. oldsigblock : tsigset;
  474. {$ifndef SHELL_USE_FPEXEC}
  475. p : ppchar;
  476. {$endif}
  477. cmd : RawByteString;
  478. begin { Changes as above }
  479. { fpexec* take care of converting the command to the right code page }
  480. if command='' then exit(1);
  481. {$ifndef SHELL_USE_FPEXEC}
  482. p:=CreateShellArgv(command);
  483. {$endif}
  484. ign.sa_handler:=SigActionHandler(SIG_IGN);
  485. fpsigemptyset(ign.sa_mask);
  486. ign.sa_flags:=0;
  487. fpsigaction(SIGINT, @ign, @intact);
  488. fpsigaction(SIGQUIT, @ign, @quitact);
  489. fpsigemptyset(newsigblock);
  490. fpsigaddset(newsigblock,SIGCHLD);
  491. fpsigprocmask(SIG_BLOCK,newsigblock,oldsigblock);
  492. {$ifdef USE_VFORK}
  493. pid:=fpvfork;
  494. {$else USE_VFORK}
  495. pid:=fpfork;
  496. {$endif USE_VFORK}
  497. if pid=0 then // We are in the Child
  498. begin
  499. fpsigaction(SIGINT,@intact,NIL);
  500. fpsigaction(SIGQUIT,@quitact,NIL);
  501. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  502. {$ifndef SHELL_USE_FPEXEC}
  503. fpExecve(p^,p,envp);
  504. {$else}
  505. fpexecl('/bin/sh',['-c',Command]);
  506. {$endif}
  507. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  508. end
  509. else if (pid<>-1) then // Successfull started
  510. begin
  511. savedpid:=pid;
  512. repeat
  513. pid:=fpwaitpid(savedpid,@pstat,0);
  514. until (pid<>-1) and (fpgeterrno()<>ESysEintr);
  515. if pid=-1 Then
  516. fpsystem:=-1
  517. else
  518. fpsystem:=pstat;
  519. end
  520. else // no success
  521. fpsystem:=-1;
  522. fpsigaction(SIGINT,@intact,NIL);
  523. fpsigaction(SIGQUIT,@quitact,NIL);
  524. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  525. {$ifndef SHELL_USE_FPEXEC}
  526. FreeShellArgV(p);
  527. {$endif}
  528. end;
  529. {$endif}
  530. Function WIFSTOPPED(Status: Integer): Boolean;
  531. begin
  532. WIFSTOPPED:=((Status and $FF)=$7F);
  533. end;
  534. Function W_EXITCODE(ReturnCode, Signal: Integer): Integer;
  535. begin
  536. W_EXITCODE:=(ReturnCode shl 8) or Signal;
  537. end;
  538. Function W_STOPCODE(Signal: Integer): Integer;
  539. begin
  540. W_STOPCODE:=(Signal shl 8) or $7F;
  541. end;
  542. {$IFNDEF DONT_READ_TIMEZONE}
  543. { Include timezone handling routines which use /usr/share/timezone info }
  544. {$i timezone.inc}
  545. {$endif}
  546. {******************************************************************************
  547. FileSystem calls
  548. ******************************************************************************}
  549. Function fpFlock (var T : text;mode : cint) : cint;
  550. begin
  551. {$ifndef beos}
  552. fpFlock:=fpFlock(TextRec(T).Handle,mode);
  553. {$endif}
  554. end;
  555. Function fpFlock (var F : File;mode : cint) :cint;
  556. begin
  557. {$ifndef beos}
  558. fpFlock:=fpFlock(FileRec(F).Handle,mode);
  559. {$endif}
  560. end;
  561. Function SelectText(var T:Text;TimeOut :PTimeval):cint;
  562. Var
  563. F:TfdSet;
  564. begin
  565. if textrec(t).mode=fmclosed then
  566. begin
  567. fpseterrno(ESysEBADF);
  568. exit(-1);
  569. end;
  570. FpFD_ZERO(f);
  571. fpFD_SET(textrec(T).handle,f);
  572. if textrec(T).mode=fminput then
  573. SelectText:=fpselect(textrec(T).handle+1,@f,nil,nil,TimeOut)
  574. else
  575. SelectText:=fpselect(textrec(T).handle+1,nil,@f,nil,TimeOut);
  576. end;
  577. Function SelectText(var T:Text;TimeOut :cint):cint;
  578. var
  579. p : PTimeVal;
  580. tv : TimeVal;
  581. begin
  582. if TimeOut=-1 then
  583. p:=nil
  584. else
  585. begin
  586. tv.tv_Sec:=Timeout div 1000;
  587. tv.tv_Usec:=(Timeout mod 1000)*1000;
  588. p:=@tv;
  589. end;
  590. SelectText:=SelectText(T,p);
  591. end;
  592. {******************************************************************************
  593. Directory
  594. ******************************************************************************}
  595. procedure SeekDir(p:pdir;loc:clong);
  596. begin
  597. if p=nil then
  598. begin
  599. fpseterrno(ESysEBADF);
  600. exit;
  601. end;
  602. {$if not(defined(bsd)) and not(defined(solaris)) and not(defined(beos)) and not(defined(aix)) }
  603. p^.dd_nextoff:=fplseek(p^.dd_fd,loc,seek_set);
  604. {$endif}
  605. {$if not(defined(beos))}
  606. p^.dd_size:=0;
  607. p^.dd_loc:=0;
  608. {$endif}
  609. end;
  610. function TellDir(p:pdir):TOff;
  611. begin
  612. if p=nil then
  613. begin
  614. fpseterrno(ESysEBADF);
  615. telldir:=-1;
  616. exit;
  617. end;
  618. {$ifndef beos}
  619. telldir:=fplseek(p^.dd_fd,0,seek_cur)
  620. {$endif}
  621. { We could try to use the nextoff field here, but on my 1.2.13
  622. kernel, this gives nothing... This may have to do with
  623. the readdir implementation of libc... I also didn't find any trace of
  624. the field in the kernel code itself, So I suspect it is an artifact of libc.
  625. Michael. }
  626. end;
  627. {******************************************************************************
  628. Pipes/Fifo
  629. ******************************************************************************}
  630. Procedure OpenPipe(var F:Text);
  631. begin
  632. case textrec(f).mode of
  633. fmoutput :
  634. if textrec(f).userdata[1]<>P_OUT then
  635. textrec(f).mode:=fmclosed;
  636. fminput :
  637. if textrec(f).userdata[1]<>P_IN then
  638. textrec(f).mode:=fmclosed;
  639. else
  640. textrec(f).mode:=fmclosed;
  641. end;
  642. end;
  643. Function IOPipe(var F:text):cint;
  644. begin
  645. IOPipe:=0;
  646. case textrec(f).mode of
  647. fmoutput :
  648. begin
  649. { first check if we need something to write, else we may
  650. get a SigPipe when Close() is called (PFV) }
  651. if textrec(f).bufpos>0 then
  652. IOPipe:=fpwrite(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufpos);
  653. end;
  654. fminput : Begin
  655. textrec(f).bufend:=fpread(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufsize);
  656. IOPipe:=textrec(f).bufend;
  657. End;
  658. end;
  659. textrec(f).bufpos:=0;
  660. end;
  661. Function FlushPipe(var F:Text):cint;
  662. begin
  663. FlushPipe:=0;
  664. if (textrec(f).mode=fmoutput) and (textrec(f).bufpos<>0) then
  665. FlushPipe:=IOPipe(f);
  666. textrec(f).bufpos:=0;
  667. end;
  668. Function ClosePipe(var F:text):cint;
  669. begin
  670. textrec(f).mode:=fmclosed;
  671. ClosePipe:=fpclose(textrec(f).handle);
  672. end;
  673. Function AssignPipe(var pipe_in,pipe_out:text):cint;
  674. {
  675. Sets up a pair of file variables, which act as a pipe. The first one can
  676. be read from, the second one can be written to.
  677. }
  678. var
  679. f_in,f_out : cint;
  680. begin
  681. if AssignPipe(f_in,f_out)=-1 then
  682. exit(-1);
  683. { Set up input }
  684. Assign(Pipe_in,'');
  685. Textrec(Pipe_in).Handle:=f_in;
  686. Textrec(Pipe_in).Mode:=fmInput;
  687. Textrec(Pipe_in).userdata[1]:=P_IN;
  688. TextRec(Pipe_in).OpenFunc:=@OpenPipe;
  689. TextRec(Pipe_in).InOutFunc:=@IOPipe;
  690. TextRec(Pipe_in).FlushFunc:=@FlushPipe;
  691. TextRec(Pipe_in).CloseFunc:=@ClosePipe;
  692. { Set up output }
  693. Assign(Pipe_out,'');
  694. Textrec(Pipe_out).Handle:=f_out;
  695. Textrec(Pipe_out).Mode:=fmOutput;
  696. Textrec(Pipe_out).userdata[1]:=P_OUT;
  697. TextRec(Pipe_out).OpenFunc:=@OpenPipe;
  698. TextRec(Pipe_out).InOutFunc:=@IOPipe;
  699. TextRec(Pipe_out).FlushFunc:=@FlushPipe;
  700. TextRec(Pipe_out).CloseFunc:=@ClosePipe;
  701. AssignPipe:=0;
  702. end;
  703. Function AssignPipe(var pipe_in,pipe_out:file):cint;
  704. {
  705. Sets up a pair of file variables, which act as a pipe. The first one can
  706. be read from, the second one can be written to.
  707. If the operation was unsuccesful,
  708. }
  709. var
  710. f_in,f_out : cint;
  711. begin
  712. if AssignPipe(f_in,f_out)=-1 then
  713. exit(-1);
  714. { Set up input }
  715. Assign(Pipe_in,'');
  716. Filerec(Pipe_in).Handle:=f_in;
  717. Filerec(Pipe_in).Mode:=fmInput;
  718. Filerec(Pipe_in).recsize:=1;
  719. Filerec(Pipe_in).userdata[1]:=P_IN;
  720. { Set up output }
  721. Assign(Pipe_out,'');
  722. Filerec(Pipe_out).Handle:=f_out;
  723. Filerec(Pipe_out).Mode:=fmoutput;
  724. Filerec(Pipe_out).recsize:=1;
  725. Filerec(Pipe_out).userdata[1]:=P_OUT;
  726. AssignPipe:=0;
  727. end;
  728. Function PCloseText(Var F:text):cint;
  729. {
  730. May not use @PClose due overloading
  731. }
  732. begin
  733. PCloseText:=PClose(f);
  734. end;
  735. Function POpen_internal(var F:text;const Prog:RawByteString;rw:char):cint;
  736. {
  737. Starts the program in 'Prog' and makes it's input or out put the
  738. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  739. F, will be read from stdin by the program in 'Prog'. The inverse is true
  740. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  741. read from 'f'.
  742. }
  743. var
  744. pipi,
  745. pipo : text;
  746. pid : cint;
  747. pl : ^cint;
  748. {$if not defined(FPC_USE_FPEXEC) or defined(USE_VFORK)}
  749. pp : array[0..3] of pchar;
  750. temp : string[255];
  751. {$endif not FPC_USE_FPEXEC or USE_VFORK}
  752. ret : cint;
  753. begin
  754. rw:=upcase(rw);
  755. if not (rw in ['R','W']) then
  756. begin
  757. FpSetErrno(ESysEnoent);
  758. exit(-1);
  759. end;
  760. ret:=AssignPipe(pipi,pipo);
  761. if ret=-1 then
  762. exit(-1);
  763. {$ifdef USE_VFORK}
  764. pid:=fpvfork;
  765. {$else USE_VFORK}
  766. pid:=fpfork;
  767. {$endif USE_VFORK}
  768. if pid=-1 then
  769. begin
  770. close(pipi);
  771. close(pipo);
  772. exit(-1);
  773. end;
  774. if pid=0 then
  775. begin
  776. { We're in the child }
  777. if rw='W' then
  778. begin
  779. if (textrec(pipi).handle <> stdinputhandle) then
  780. begin
  781. ret:=fpdup2(pipi,input);
  782. {$ifdef USE_VFORK}
  783. fpclose(textrec(pipi).handle);
  784. {$else USE_VFORK}
  785. close(pipi);
  786. {$endif USE_VFORK}
  787. end;
  788. {$ifdef USE_VFORK}
  789. fpclose(textrec(pipo).handle);
  790. {$else USE_VFORK}
  791. close(pipo);
  792. {$endif USE_VFORK}
  793. if ret=-1 then
  794. fpexit(127);
  795. end
  796. else
  797. begin
  798. {$ifdef USE_VFORK}
  799. fpclose(textrec(pipi).handle);
  800. {$else USE_VFORK}
  801. close(pipi);
  802. {$endif USE_VFORK}
  803. if (textrec(pipo).handle <> stdoutputhandle) then
  804. begin
  805. ret:=fpdup2(pipo,output);
  806. {$ifdef USE_VFORK}
  807. fpclose(textrec(pipo).handle);
  808. {$else USE_VFORK}
  809. close(pipo);
  810. {$endif USE_VFORK}
  811. end;
  812. if ret=-1 then
  813. fpexit(127);
  814. end;
  815. {$if defined(FPC_USE_FPEXEC) and not defined(USE_VFORK)}
  816. fpexecl(pchar('/bin/sh'),['-c',Prog]);
  817. {$else}
  818. temp:='/bin/sh'#0'-c'#0;
  819. pp[0]:=@temp[1];
  820. pp[1]:=@temp[9];
  821. pp[2]:=@prog[1];
  822. pp[3]:=Nil;
  823. fpExecve('/bin/sh',@pp,envp);
  824. {$endif}
  825. fpexit(127);
  826. end
  827. else
  828. begin
  829. { We're in the parent }
  830. if rw='W' then
  831. begin
  832. close(pipi);
  833. f:=pipo;
  834. end
  835. else
  836. begin
  837. close(pipo);
  838. f:=pipi;
  839. end;
  840. textrec(f).bufptr:=@textrec(f).buffer;
  841. {Save the process ID - needed when closing }
  842. pl:=pcint(@textrec(f).userdata[2]);
  843. { avoid alignment error on sparc }
  844. move(pid,pl^,sizeof(pid));
  845. textrec(f).closefunc:=@PCloseText;
  846. end;
  847. POpen_internal:=0;
  848. end;
  849. Function POpen_internal(var F:file;const Prog:RawByteString;rw:char):cint;
  850. {
  851. Starts the program in 'Prog' and makes it's input or out put the
  852. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  853. F, will be read from stdin by the program in 'Prog'. The inverse is true
  854. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  855. read from 'f'.
  856. }
  857. var
  858. pipi,
  859. pipo : file;
  860. pid : cint;
  861. pl : ^cint;
  862. {$if not defined(FPC_USE_FPEXEC) or defined(USE_VFORK)}
  863. pp : array[0..3] of pchar;
  864. temp : string[255];
  865. {$endif not FPC_USE_FPEXEC or USE_VFORK}
  866. ret : cint;
  867. begin
  868. rw:=upcase(rw);
  869. if not (rw in ['R','W']) then
  870. begin
  871. FpSetErrno(ESysEnoent);
  872. exit(-1);
  873. end;
  874. ret:=AssignPipe(pipi,pipo);
  875. if ret=-1 then
  876. exit(-1);
  877. {$ifdef USE_VFORK}
  878. pid:=fpvfork;
  879. {$else USE_VFORK}
  880. pid:=fpfork;
  881. {$endif USE_VFORK}
  882. if pid=-1 then
  883. begin
  884. close(pipi);
  885. close(pipo);
  886. exit(-1);
  887. end;
  888. if pid=0 then
  889. begin
  890. { We're in the child }
  891. if rw='W' then
  892. begin
  893. if (filerec(pipi).handle <> stdinputhandle) then
  894. begin
  895. ret:=fpdup2(filerec(pipi).handle,stdinputhandle);
  896. {$ifdef USE_VFORK}
  897. fpclose(filerec(pipi).handle);
  898. {$else USE_VFORK}
  899. close(pipi);
  900. {$endif USE_VFORK}
  901. end;
  902. {$ifdef USE_VFORK}
  903. fpclose(filerec(pipo).handle);
  904. {$else USE_VFORK}
  905. close(pipo);
  906. {$endif USE_VFORK}
  907. if ret=-1 then
  908. fpexit(127);
  909. end
  910. else
  911. begin
  912. {$ifdef USE_VFORK}
  913. fpclose(filerec(pipi).handle);
  914. {$else USE_VFORK}
  915. close(pipi);
  916. {$endif USE_VFORK}
  917. if (filerec(pipo).handle <> stdoutputhandle) then
  918. begin
  919. ret:=fpdup2(filerec(pipo).handle,stdoutputhandle);
  920. {$ifdef USE_VFORK}
  921. fpclose(filerec(pipo).handle);
  922. {$else USE_VFORK}
  923. close(pipo);
  924. {$endif USE_VFORK}
  925. end;
  926. if ret=-1 then
  927. fpexit(127);
  928. end;
  929. {$if defined(FPC_USE_FPEXEC) and not defined(USE_VFORK)}
  930. fpexecl(pchar('/bin/sh'),['-c',Prog]);
  931. {$else}
  932. temp:='/bin/sh'#0'-c'#0;
  933. pp[0]:=@temp[1];
  934. pp[1]:=@temp[9];
  935. pp[2]:=@prog[1];
  936. pp[3]:=Nil;
  937. fpExecve('/bin/sh',@pp,envp);
  938. {$endif}
  939. fpexit(127);
  940. end
  941. else
  942. begin
  943. { We're in the parent }
  944. if rw='W' then
  945. begin
  946. close(pipi);
  947. f:=pipo;
  948. end
  949. else
  950. begin
  951. close(pipo);
  952. f:=pipi;
  953. end;
  954. {Save the process ID - needed when closing }
  955. pl:=pcint(@filerec(f).userdata[2]);
  956. { avoid alignment error on sparc }
  957. move(pid,pl^,sizeof(pid));
  958. end;
  959. POpen_internal:=0;
  960. end;
  961. Function POpen(var F:text;const Prog:RawByteString;rw:char):cint;
  962. begin
  963. { can't do the ToSingleByteFileSystemEncodedFileName() conversion inside
  964. POpen_internal, because this may destroy the temp rawbytestring result
  965. of that function in the parent before the child is finished with it }
  966. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  967. end;
  968. Function POpen(var F:file;const Prog:RawByteString;rw:char):cint;
  969. begin
  970. { can't do the ToSingleByteFileSystemEncodedFileName() conversion inside
  971. POpen_internal, because this may destroy the temp rawbytestring result
  972. of that function in the parent before the child is finished with it }
  973. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  974. end;
  975. function POpen(var F: text; const Prog: UnicodeString; rw: char): cint;
  976. begin
  977. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  978. end;
  979. function POpen(var F: file; const Prog: UnicodeString; rw: char): cint;
  980. begin
  981. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  982. end;
  983. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  984. {
  985. Starts the program in 'Prog' and makes its input and output the
  986. other end of two pipes, which are the stdin and stdout of a program
  987. specified in 'Prog'.
  988. streamout can be used to write to the program, streamin can be used to read
  989. the output of the program. See the following diagram :
  990. Parent Child
  991. STreamout --> Input
  992. Streamin <-- Output
  993. Return value is the process ID of the process being spawned, or -1 in case of failure.
  994. }
  995. var
  996. pipi,
  997. pipo : text;
  998. pid : cint;
  999. pl : ^cint;
  1000. begin
  1001. AssignStream:=-1;
  1002. if fpAccess(prog,X_OK)<>0 then
  1003. exit(-1);
  1004. if AssignPipe(streamin,pipo)=-1 Then
  1005. exit(-1);
  1006. if AssignPipe(pipi,streamout)=-1 Then
  1007. begin
  1008. close(streamin);
  1009. close(pipo);
  1010. exit(-1);
  1011. end;
  1012. pid:=fpfork;
  1013. if pid=-1 then
  1014. begin
  1015. close(pipi);
  1016. close(pipo);
  1017. close (streamin);
  1018. close (streamout);
  1019. exit;
  1020. end;
  1021. if pid=0 then
  1022. begin
  1023. { We're in the child }
  1024. { Close what we don't need }
  1025. close(streamout);
  1026. close(streamin);
  1027. if fpdup2(pipi,input)=-1 Then
  1028. halt(127);
  1029. close(pipi);
  1030. If fpdup2(pipo,output)=-1 Then
  1031. halt (127);
  1032. close(pipo);
  1033. fpExecl(Prog,args);
  1034. halt(127);
  1035. end
  1036. else
  1037. begin
  1038. { we're in the parent}
  1039. close(pipo);
  1040. close(pipi);
  1041. {Save the process ID - needed when closing }
  1042. pl:=pcint(@textrec(StreamIn).userdata[2]);
  1043. { avoid alignment error on sparc }
  1044. move(pid,pl^,sizeof(pid));
  1045. textrec(StreamIn).closefunc:=@PCloseText;
  1046. {Save the process ID - needed when closing }
  1047. pl:=pcint(@textrec(StreamOut).userdata[2]);
  1048. { avoid alignment error on sparc }
  1049. move(pid,pl^,sizeof(pid));
  1050. textrec(StreamOut).closefunc:=@PCloseText;
  1051. AssignStream:=Pid;
  1052. end;
  1053. end;
  1054. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  1055. {
  1056. Starts the program in 'prog' and makes its input, output and error output the
  1057. other end of three pipes, which are the stdin, stdout and stderr of a program
  1058. specified in 'prog'.
  1059. StreamOut can be used to write to the program, StreamIn can be used to read
  1060. the output of the program, StreamErr reads the error output of the program.
  1061. See the following diagram :
  1062. Parent Child
  1063. StreamOut --> StdIn (input)
  1064. StreamIn <-- StdOut (output)
  1065. StreamErr <-- StdErr (error output)
  1066. }
  1067. var
  1068. PipeIn, PipeOut, PipeErr: text;
  1069. pid: cint;
  1070. pl: ^cint;
  1071. begin
  1072. AssignStream := -1;
  1073. if fpAccess(prog,X_OK)<>0 then
  1074. exit(-1);
  1075. // Assign pipes
  1076. if AssignPipe(StreamIn, PipeOut)=-1 Then
  1077. Exit(-1);
  1078. If AssignPipe(StreamErr, PipeErr)=-1 Then
  1079. begin
  1080. Close(StreamIn);
  1081. Close(PipeOut);
  1082. exit(-1);
  1083. end;
  1084. if AssignPipe(PipeIn, StreamOut)=-1 Then
  1085. begin
  1086. Close(StreamIn);
  1087. Close(PipeOut);
  1088. Close(StreamErr);
  1089. Close(PipeErr);
  1090. exit(-1);
  1091. end;
  1092. // Fork
  1093. pid := fpFork;
  1094. if pid=-1 then begin
  1095. Close(StreamIn);
  1096. Close(PipeOut);
  1097. Close(StreamErr);
  1098. Close(PipeErr);
  1099. Close(PipeIn);
  1100. Close(StreamOut);
  1101. exit(-1);
  1102. end;
  1103. if pid = 0 then begin
  1104. // *** We are in the child ***
  1105. // Close what we don not need
  1106. Close(StreamOut);
  1107. Close(StreamIn);
  1108. Close(StreamErr);
  1109. // Connect pipes
  1110. if fpdup2(PipeIn, Input)=-1 Then
  1111. Halt(127);
  1112. Close(PipeIn);
  1113. if fpdup2(PipeOut, Output)=-1 Then
  1114. Halt(127);
  1115. Close(PipeOut);
  1116. if fpdup2(PipeErr, StdErr)=-1 Then
  1117. Halt(127);
  1118. Close(PipeErr);
  1119. // Execute program
  1120. fpExecl(Prog,args);
  1121. Halt(127);
  1122. end else begin
  1123. // *** We are in the parent ***
  1124. Close(PipeErr);
  1125. Close(PipeOut);
  1126. Close(PipeIn);
  1127. // Save the process ID - needed when closing
  1128. pl := pcint(@TextRec(StreamIn).userdata[2]);
  1129. { avoid alignment error on sparc }
  1130. move(pid,pl^,sizeof(pid));
  1131. TextRec(StreamIn).closefunc := @PCloseText;
  1132. // Save the process ID - needed when closing
  1133. pl := pcint(@TextRec(StreamOut).userdata[2]);
  1134. { avoid alignment error on sparc }
  1135. move(pid,pl^,sizeof(pid));
  1136. TextRec(StreamOut).closefunc := @PCloseText;
  1137. // Save the process ID - needed when closing
  1138. pl := pcint(@TextRec(StreamErr).userdata[2]);
  1139. { avoid alignment error on sparc }
  1140. move(pid,pl^,sizeof(pid));
  1141. TextRec(StreamErr).closefunc := @PCloseText;
  1142. AssignStream := pid;
  1143. end;
  1144. end;
  1145. {******************************************************************************
  1146. General information calls
  1147. ******************************************************************************}
  1148. {$if defined(Linux)}
  1149. Function GetDomainName:String; { linux only!}
  1150. // domainname is a glibc extension.
  1151. {
  1152. Get machines domain name. Returns empty string if not set.
  1153. }
  1154. Var
  1155. Sysn : utsname;
  1156. begin
  1157. If fpUname(sysn)<>0 then
  1158. getdomainname:=''
  1159. else
  1160. getdomainname:=strpas(@Sysn.domain[0]);
  1161. end;
  1162. {$endif}
  1163. {$ifdef sunos}
  1164. { sunos doesn't support GetDomainName, see also
  1165. http://www.sun.com/software/solaris/programs/abi/appcert_faq.xml#q18
  1166. }
  1167. Function GetDomainName:String;
  1168. begin
  1169. GetDomainName:='';
  1170. end;
  1171. {$endif sunos}
  1172. {$ifdef android}
  1173. { android doesn't seem to implement GetDomainName
  1174. }
  1175. Function GetDomainName:String;
  1176. begin
  1177. GetDomainName:='';
  1178. end;
  1179. {$endif}
  1180. {$if defined(BSD) or defined(aix)}
  1181. function intGetDomainName(Name:PChar; NameLen:Cint):cint;
  1182. {$ifndef FPC_USE_LIBC}
  1183. external name 'FPC_SYSC_GETDOMAINNAME';
  1184. {$else FPC_USE_LIBC}
  1185. cdecl; external clib name 'getdomainname';
  1186. {$endif FPC_USE_LIBC}
  1187. Function GetDomainName:String; { linux only!}
  1188. // domainname is a glibc extension.
  1189. {
  1190. Get machines domain name. Returns empty string if not set.
  1191. }
  1192. begin
  1193. if intGetDomainName(@getdomainname[1],255)=-1 then
  1194. getdomainname:=''
  1195. else
  1196. getdomainname[0]:=chr(strlen(@getdomainname[1]));
  1197. end;
  1198. {$endif}
  1199. Function GetHostName:String;
  1200. {
  1201. Get machines name. Returns empty string if not set.
  1202. }
  1203. Var
  1204. Sysn : utsname;
  1205. begin
  1206. If fpuname(sysn)=-1 then
  1207. gethostname:=''
  1208. else
  1209. gethostname:=strpas(@Sysn.nodename[0]);
  1210. end;
  1211. {******************************************************************************
  1212. Utility calls
  1213. ******************************************************************************}
  1214. Function FSearch(const path:RawByteString;dirlist:RawByteString;CurrentDirStrategy:TFSearchOption):RawByteString;
  1215. {
  1216. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1217. returns an empty string if not found. Wildcards are NOT allowed.
  1218. If dirlist is empty, it is set to '.'
  1219. This function tries to make FSearch use ansistrings, and decrease
  1220. stringhandling overhead at the same time.
  1221. }
  1222. Var
  1223. mypath,
  1224. mydir,NewDir : RawByteString;
  1225. p1 : cint;
  1226. Info : Stat;
  1227. i,j : cint;
  1228. p : pchar;
  1229. Begin
  1230. SetCodePage(dirlist,DefaultFileSystemCodePage);
  1231. if CurrentDirStrategy=CurrentDirectoryFirst Then
  1232. Dirlist:=ToSingleByteFileSystemEncodedFileName('.:')+dirlist {Make sure current dir is first to be searched.}
  1233. else if CurrentDirStrategy=CurrentDirectoryLast Then
  1234. Dirlist:=dirlist+ToSingleByteFileSystemEncodedFileName('.:'); {Make sure current dir is last to be searched.}
  1235. {Replace ':' and ';' with #0}
  1236. for p1:=1 to length(dirlist) do
  1237. if (dirlist[p1]=':') or (dirlist[p1]=';') then
  1238. dirlist[p1]:=#0;
  1239. {Check for WildCards}
  1240. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1241. FSearch:='' {No wildcards allowed in these things.}
  1242. Else
  1243. Begin
  1244. mypath:=ToSingleByteFileSystemEncodedFileName(path);
  1245. p:=pchar(dirlist);
  1246. i:=length(dirlist);
  1247. j:=1;
  1248. Repeat
  1249. mydir:=RawByteString(p);
  1250. if (length(mydir)>0) and (mydir[length(mydir)]<>'/') then
  1251. begin
  1252. { concatenate character without influencing code page }
  1253. setlength(mydir,length(mydir)+1);
  1254. mydir[length(mydir)]:='/';
  1255. end;
  1256. NewDir:=mydir+mypath;
  1257. if (FpStat(NewDir,Info)>=0) and
  1258. (not fpS_ISDIR(Info.st_Mode)) then
  1259. Begin
  1260. If Pos('./',NewDir)=1 Then
  1261. Delete(NewDir,1,2);
  1262. {DOS strips off an initial .\}
  1263. End
  1264. Else
  1265. NewDir:='';
  1266. while (j<=i) and (p^<>#0) do begin inc(j); inc(p); end;
  1267. if p^=#0 then inc(p);
  1268. Until (j>=i) or (Length(NewDir) > 0);
  1269. FSearch:=NewDir;
  1270. SetCodePage(FSearch,DefaultRTLFileSystemCodePage);
  1271. End;
  1272. End;
  1273. Function FSearch(const path:RawByteString;dirlist:RawByteString):RawByteString;
  1274. Begin
  1275. FSearch:=FSearch(path,dirlist,CurrentDirectoryFirst);
  1276. End;
  1277. function FSearch(const path: UnicodeString; dirlist: UnicodeString; CurrentDirStrategy: TFSearchOption): UnicodeString;
  1278. begin
  1279. FSearch:=FSearch(ToSingleByteFileSystemEncodedFileName(path),ToSingleByteFileSystemEncodedFileName(dirlist),CurrentDirStrategy);
  1280. end;
  1281. function FSearch(const path: UnicodeString; dirlist: UnicodeString): UnicodeString;
  1282. begin
  1283. FSearch:=FSearch(ToSingleByteFileSystemEncodedFileName(path),ToSingleByteFileSystemEncodedFileName(dirlist),CurrentDirectoryFirst);
  1284. end;
  1285. {$ifdef android}
  1286. {$I unixandroid.inc}
  1287. {$endif android}
  1288. {$if declared(UseTZThreading)}
  1289. procedure InitTZThreading;
  1290. begin
  1291. UseTZThreading:=True;
  1292. InitCriticalSection(TZInfoCS);
  1293. end;
  1294. {$endif}
  1295. Initialization
  1296. {$if declared(UseTZThreading)}
  1297. RegisterLazyInitThreadingProc(@InitTZThreading);
  1298. {$endif}
  1299. {$IFNDEF DONT_READ_TIMEZONE}
  1300. InitLocalTime;
  1301. {$endif}
  1302. {$ifdef android}
  1303. InitLocalTime;
  1304. {$endif android}
  1305. finalization
  1306. {$IFNDEF DONT_READ_TIMEZONE}
  1307. DoneLocalTime;
  1308. {$endif}
  1309. {$if declared(UseTZThreading)}
  1310. if UseTZThreading then
  1311. DoneCriticalSection(TZInfoCS);
  1312. {$endif}
  1313. End.