unix.pp 39 KB

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