12.3 Functions and procedures

Access

Declaration:
Function Access (Path : Pathstr; Mode : integer) : Boolean;
Description:
Tests user’s access rights on the specified file. Mode is a mask existing of one or more of
R__OK
User has read rights.
W__OK
User has write rights.
X__OK
User has execute rights.
F__OK
User has search rights in the directory where the file is.

The test is done with the real user ID, instead of the effective user ID. If access is denied, or an error occurred, false is returned.

Errors:
LinuxError is used to report errors:
sys__eaccess
The requested access is denied, either to the file or one of the directories in its path.
sys__einval
Mode was incorrect.
sys__enoent
A directory component in Path doesn’t exist or is a dangling symbolic link.
sys__enotdir
A directory component in Path is not a directory.
sys__enomem
Insufficient kernel memory.
sys__eloop
Path has a circular symbolic link.
See also:
Chown (361), Chmod (362), Access (2)

Listing: linuxex/ex26.pp


Program Example26;

{ Program to demonstrate the Access function. }

Uses linux;

begin
  if Access ('/etc/passwd',W_OK) then
    begin
    Writeln ('Better check your system.');
    Writeln ('I can write to the /etc/passwd file !');
    end;
end.

Alarm

Declaration:
Function Alarm(Sec : longint) : Longint;
Description:
Alarm schedules an alarm signal to be delivered to your process in Sec seconds. When Sec seconds have elapsed, Linux will send a SIGALRM signal to the current process. If Sec is zero, then no new alarm will be set. Whatever the value of Sec, any previous alarm is cancelled.

The function returns the number of seconds till the previously scheduled alarm was due to be delivered, or zero if there was none.

Errors:
None

Listing: linuxex/ex59.pp


Program Example59;

{ Program to demonstrate the Alarm function. }

Uses linux;

Procedure AlarmHandler(Sig : longint);cdecl;

begin
  Writeln ('Got to alarm handler');
end;

begin
  Writeln('Setting alarm handler');
  Signal(SIGALRM,@AlarmHandler);
  Writeln ('Scheduling Alarm in 10 seconds');
  Alarm(10);
  Writeln ('Pausing');
  Pause;
  Writeln ('Pause returned');
end.

AssignPipe

Declaration:
Function AssignPipe(var pipe_in,pipe_out:longint):boolean; Function AssignPipe(var pipe_in,pipe_out:text):boolean; Function AssignPipe(var pipe_in,pipe_out:file):boolean;
Description:
AssignePipe creates a pipe, i.e. two file objects, one for input, one for output. What is written to Pipe_out, can be read from Pipe_in.

This call is overloaded. The in and out pipe can take three forms: an typed or untyped file, a text file or a file descriptor.

If a text file is passed then reading and writing from/to the pipe can be done through the usual Readln(Pipe_in,...) and Writeln (Pipe_out,...) procedures.

The function returns True if everything went succesfully, False otherwise.

Errors:
In case the function fails and returns False, LinuxError is used to report errors:
sys__emfile
Too many file descriptors for this process.
sys__enfile
The system file table is full.
See also:
POpen (417), MkFifo (411), pipe (2)

Listing: linuxex/ex36.pp


Program Example36;

{ Program to demonstrate the AssignPipe function. }

Uses linux;

Var pipi,pipo : Text;
    s : String;

begin
  Writeln ('Assigning Pipes.');
  If Not assignpipe(pipi,pipo) then
    Writeln('Error assigning pipes !',LinuxError);
  Writeln ('Writing to pipe, and flushing.');
  Writeln (pipo,'This is a textstring');close(pipo);
  Writeln ('Reading from pipe.');
  While not eof(pipi) do
    begin
    Readln (pipi,s);
    Writeln ('Read from pipe : ',s);
    end;
  close (pipi);
  writeln ('Closed pipes.');
  writeln
end.

AssignStream

Declaration:
Function AssignStream(Var StreamIn,Streamout:text; Const Prog:String) : longint; Function AssignStream(var StreamIn, StreamOut, StreamErr: Text; const prog: String): LongInt;
Description:
AssignStream creates a 2 or 3 pipes, i.e. two (or three) file objects, one for input, one for output,(and one for standard error) the other ends of these pipes are connected to standard input and output (and standard error) of Prog. Prog is the name of a program (including path) with options, which will be executed.

What is written to StreamOut, will go to the standard input of Prog. Whatever is written by Prog to it’s standard output can be read from StreamIn. Whatever is written by Prog to it’s standard error read from StreamErr, if present.

Reading and writing happens through the usual Readln(StreamIn,...) and Writeln (StreamOut,...) procedures.

Remark: You should not use Reset or Rewrite on a file opened with POpen. This will close the file before re-opening it again, thereby closing the connection with the program.

The function returns the process ID of the spawned process, or -1 in case of error.

Errors:
In case of error (return value -1) LinuxError is used to report errors:
sys__emfile
Too many file descriptors for this process.
sys__enfile
The system file table is full.

Other errors include the ones by the fork and exec programs

See also:
AssignPipe (357), POpen (417),pipe (2)

Listing: linuxex/ex38.pp


Program Example38;

{ Program to demonstrate the AssignStream function. }

Uses linux;

Var Si,So : Text;
    S : String;
    i : longint;

begin
  if not (paramstr(1)='-son') then
    begin
    Writeln ('Calling son');
    Assignstream (Si,So,'./ex38 -son');
    if linuxerror<>0 then
      begin
      writeln ('AssignStream failed !');
      halt(1);
      end;
    Writeln ('Speaking to son');
    For i:=1 to 10 do
      begin
      writeln (so,'Hello son !');
      if ioresult<>0 then writeln ('Can''t speak to son...');
      end;
    For i:=1 to 3 do writeln (so,'Hello chap !');
    close (so);
    while not eof(si) do
      begin
      readln (si,s);
      writeln ('Father: Son said : ',S);
      end;
    Writeln ('Stopped conversation');
    Close (Si);
    Writeln ('Put down phone');
    end
  Else
    begin
    Writeln ('This is the son ');
    While not eof (input) do
      begin
      readln (s);
      if pos ('Hello son !',S)<>0 then
         Writeln ('Hello Dad !')
      else
         writeln ('Who are you ?');
      end;
    close (output);
    end
end.

BaseName

Declaration:
Function BaseName (Const Path;Const Suf : Pathstr) : Pathstr;
Description:
Returns the filename part of Path, stripping off Suf if it exists. The filename part is the whole name if Path contains no slash, or the part of Path after the last slash. The last character of the result is not a slash, unless the directory is the root directory.
Errors:
None.
See also:
DirName (367), FExpand (383), Basename (1)

Listing: linuxex/ex48.pp


Program Example48;

{ Program to demonstrate the BaseName function. }

Uses linux;

Var S : String;

begin
  S:=FExpand(Paramstr(0));
  Writeln ('This program is called : ',Basename(S,''));
end.

CFMakeRaw

Declaration:
Procedure CFMakeRaw (var Tios:TermIOS);
Description:
CFMakeRaw Sets the flags in the Termios structure Tios to a state so that the terminal will function in Raw Mode.
Errors:
None.
See also:
CFSetOSpeed (361), CFSetISpeed (360), termios (2)

For an example, see TCGetAttr (435).

CFSetISpeed

Declaration:
Procedure CFSetISpeed (var Tios:TermIOS;Speed:Longint);
Description:
CFSetISpeed Sets the input baudrate in the TermIOS structure Tios to Speed.
Errors:
None.
See also:
CFSetOSpeed (361), CFMakeRaw (360), termios (2)

CFSetOSpeed

Declaration:
Procedure CFSetOSpeed (var Tios:TermIOS;Speed:Longint);
Description:
CFSetOSpeed Sets the output baudrate in the Termios structure Tios to Speed.
Errors:
None.
See also:
CFSetISpeed (360), CFMakeRaw (360), termios (2)

Chown

Declaration:
Function Chown (Path : Pathstr;NewUid,NewGid : Longint) : Boolean;
Description:
Chown sets the User ID and Group ID of the file in Path to NewUid, NewGid. The function returns True if the call was succesfull, False if the call failed.
Errors:
Errors are returned in LinuxError.
sys__eperm
The effective UID doesn’t match the ownership of the file, and is not zero. Owner or group were not specified correctly.
sys__eaccess
One of the directories in Path has no search (=execute) permission.
sys__enoent
A directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory.
sys__enotdir
A directory entry in OldPath or NewPath is nor a directory.
sys__enomem
Insufficient kernel memory.
sys__erofs
The file is on a read-only filesystem.
sys__eloop
Path has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself.
See also:
Chmod (362), Access (355), Chown (() 2)

Listing: linuxex/ex24.pp


Program Example24;

{ Program to demonstrate the Chown function. }

Uses linux;

Var UID,GID : Longint;
    F : Text;

begin

  Writeln ('This will only work if you are root.');
  Write ('Enter a UID : ');readln(UID);
  Write ('Enter a GID : ');readln(GID);
  Assign (f,'test.txt');
  Rewrite (f);
  Writeln (f,'The owner of this file should become : ');
  Writeln (f,'UID : ',UID);
  Writeln (f,'GID : ',GID);
  Close (F);
  if not Chown ('test.txt',UID,GID) then
    if LinuxError=Sys_EPERM then
      Writeln ('You are not root !')
    else
      Writeln ('Chmod failed with exit code : ',LinuxError)
  else
    Writeln ('Changed owner successfully !');
end.

Chmod

Declaration:
Function Chmod (Path : Pathstr;NewMode : Longint) : Boolean;
Description:
Chmod Sets the Mode bits of the file in Path to NewMode. Newmode can be specified by ’or’-ing the following:
S__ISUID
Set user ID on execution.
S__ISGID
Set Group ID on execution.
S__ISVTX
Set sticky bit.
S__IRUSR
Read by owner.
S__IWUSR
Write by owner.
S__IXUSR
Execute by owner.
S__IRGRP
Read by group.
S__IWGRP
Write by group.
S__IXGRP
Execute by group.
S__IROTH
Read by others.
S__IWOTH
Write by others.
S__IXOTH
Execute by others.
S__IRWXO
Read, write, execute by others.
S__IRWXG
Read, write, execute by groups.
S__IRWXU
Read, write, execute by user.
Errors:
Errors are returned in LinuxError.
sys__eperm
The effective UID doesn’t match the ownership of the file, and is not zero. Owner or group were not specified correctly.
sys__eaccess
One of the directories in Path has no search (=execute) permission.
sys__enoent
A directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory.
sys__enotdir
A directory entry in OldPath or NewPath is nor a directory.
sys__enomem
Insufficient kernel memory.
sys__erofs
The file is on a read-only filesystem.
sys__eloop
Path has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself.
See also:
Chown (361), Access (355), Chmod (() 2), Octal (415)

Listing: linuxex/ex23.pp


Program Example23;

{ Program to demonstrate the Chmod function. }

Uses linux;

Var F : Text;

begin
  { Create a file }
  Assign (f,'testex21');
  Rewrite (F);
  Writeln (f,'#!/bin/sh');
  Writeln (f,'echo Some text for this file');
  Close (F);
  { Octal() makes the correct number from a
    number that LOOKS octal }
  Chmod ('testex21',octal (777));
  { File is now executable  }
  execl ('./testex21');
end.

Clone

Declaration:
TCloneFunc=function(args:pointer):longint;cdecl; Clone(func:TCloneFunc;sp:pointer;flags:longint;args:pointer):longint;
Description:
Clone creates a child process which is a copy of the parent process, just like Fork (390) does. In difference with Fork, however, the child process shares some parts of it’s execution context with its parent, so it is suitable for the implementation of threads: many instances of a program that share the same memory.

When the child process is created, it starts executing the function Func, and passes it Args. The return value of Func is either the explicit return value of the function, or the exit code of the child process.

The sp pointer points to the memory reserved as stack space for the child process. This address should be the top of the memory block to be used as stack.

The Flags determine the behaviour of the Clone call. The low byte of the Flags contains the number of the signal that will be sent to the parent when the child dies. This may be bitwise OR’ed with the following constants:

CLONE__VM
Parent and child share the same memory space, including memory (un)mapped with subsequent mmap calls.
CLONE__FS
Parent and child have the same view of the filesystem; the chroot, chdir and umask calls affect both processes.
CLONE__FILES
the file descriptor table of parent and child is shared.
CLONE__SIGHAND
the parent and child share the same table of signal handlers. The signal masks are different, though.
CLONE__PID
PArent and child have the same process ID.

Clone returns the process ID in the parent process, and -1 if an error occurred.

Errors:
On error, -1 is returned to the parent, and no child is created.
sys__eagain
Too many processes are running.
sys__enomem
Not enough memory to create child process.
See also:
Fork (390), clone (2)

Listing: linuxex/ex71.pp


program TestC{lone};

uses
  Linux, Errors, crt;

const
  Ready : Boolean = false;
  aChar : Char    = 'a';

function CloneProc( Arg: Pointer ): LongInt; Cdecl;
begin
  WriteLn('Hello from the clone ',PChar(Arg));
  repeat
    Write(aChar);
    Select(0,0,0,0,600);
  until Ready;
  WriteLn( 'Clone finished.');
  CloneProc := 1;
end;

var
  PID : LongInt;

procedure MainProc;
begin
  WriteLn('cloned process PID: ', PID );
  WriteLn('Press <ESC> to kill ... ' );
  repeat
    Write('.');
    Select(0,0,0,0,300);
    if KeyPressed then
      case ReadKey of
        #27: Ready := true;
        'a': aChar := 'A';
        'A': aChar := 'a';
        'b': aChar := 'b';
        'B': aChar := 'B';
      end;
  until Ready;
  WriteLn('Ready.');
end;

const
  StackSze = 16384;
  theFlags = CLONE_VM+CLONE_FS+CLONE_FILES+CLONE_SIGHAND;
  aMsg     : PChar = 'Oops !';

var
  theStack : Pointer;
  ExitStat : LongInt;

begin
  GetMem(theStack,StackSze);
  PID := Clone(@CloneProc,
               Pointer( LongInt(theStack)+StackSze),
               theFlags,
               aMsg);
  if PID < 0 then
    WriteLn('Error : ', LinuxError, ' when cloning.')
  else
    begin
    MainProc;
    case WaitPID(0,@ExitStat,Wait_Untraced or wait_clone) of
      -1: WriteLn('error:',LinuxError,'; ',StrError(LinuxError));
       0: WriteLn('error:',LinuxError,'; ',StrError(LinuxError));
    else
      WriteLn('Clone exited with: ',ExitStat shr 8);
    end;
    end;
  FreeMem( theStack, StackSze );
end.

CloseDir

Declaration:
Function CloseDir (p:pdir) : integer;
Description:
CloseDir closes the directory pointed to by p. It returns zero if the directory was closed succesfully, -1 otherwise.
Errors:
Errors are returned in LinuxError.
See also:
OpenDir (416), ReadDir (419), SeekDir (422), TellDir (438), closedir (3)

For an example, see OpenDir (416).

CreateShellArgV

Declaration:
function CreateShellArgV(const prog:string):ppchar; function CreateShellArgV(const prog:Ansistring):ppchar;
Description:
CreateShellArgV creates an array of 3 PChar pointers that can be used as arguments to ExecVE the first elements in the array will contain /bin/sh, the second will contain -c, and the third will contain prog.

The function returns a pointer to this array, of type PPChar.

Errors:
None.
See also:
Shell (425)

Listing: linuxex/ex61.pp


Program ex61;

{ Example program to demonstrate the CreateShellArgV function }

uses linux;

Var
  S: String;
  PP : PPchar;
   I : longint;

begin
  S:='script -a -b -c -d -e fghijk';
  PP:=CreateShellArgV(S);
  I:=0;
  If PP<>Nil then
    While PP[i]<>Nil do
      begin
      Writeln ('Got : "',PP[i],'"');
      Inc(i);
      end;
end.

DirName

Declaration:
Function DirName (Const Path : Pathstr) : Pathstr;
Description:
Returns the directory part of Path. The directory is the part of Path before the last slash, or empty if there is no slash. The last character of the result is not a slash, unless the directory is the root directory.
Errors:
None.
See also:
BaseName (359), FExpand (383), Dirname (1)

Listing: linuxex/ex47.pp


Program Example47;

{ Program to demonstrate the DirName function. }

Uses linux;

Var S : String;

begin
  S:=FExpand(Paramstr(0));
  Writeln ('This program is in directory : ',Dirname(S));
end.

Dup

Declaration:
Function Dup(oldfile:longint;var newfile:longint):Boolean; Function Dup(var oldfile,newfile:text):Boolean; Function Dup(var oldfile,newfile:file):Boolean;
Description:
Makes NewFile an exact copy of OldFile, after having flushed the buffer of OldFile in case it is a Text file or untyped file. Due to the buffering mechanism of Pascal, this has not the same functionality as the dup (2) call in C. The internal Pascal buffers are not the same after this call, but when the buffers are flushed (e.g. after output), the output is sent to the same file. Doing an lseek will, however, work as in C, i.e. doing a lseek will change the fileposition in both files.

The function returns False in case of an error, True if successful.

Errors:
In case of errors, Linuxerror is used to report errors.
sys__ebadf
OldFile hasn’t been assigned.
sys__emfile
Maximum number of open files for the process is reached.
See also:
Dup2 (369), Dup (2)

Listing: linuxex/ex31.pp


program Example31;

{ Program to demonstrate the Dup function. }

uses linux;

var f : text;

begin
  if not dup (output,f) then
    Writeln ('Dup Failed !');
  writeln ('This is written to stdout.');
  writeln (f,'This is written to the dup file, and flushed');flush(f);
  writeln
end.

Dup2

Declaration:
Function Dup2(oldfile,newfile:longint):Boolean; Function Dup2(var oldfile,newfile:text):Boolean; Function Dup2(var oldfile,newfile:file):Boolean;
Description:
Makes NewFile an exact copy of OldFile, after having flushed the buffer of OldFile in the case of text or untyped files.

NewFile can be an assigned file. If newfile was open, it is closed first. Due to the buffering mechanism of Pascal, this has not the same functionality as the dup2 (2) call in C. The internal Pascal buffers are not the same after this call, but when the buffers are flushed (e.g. after output), the output is sent to the same file. Doing an lseek will, however, work as in C, i.e. doing a lseek will change the fileposition in both files.

The function returns True if succesful, false otherwise.

Errors:
In case of error, Linuxerror is used to report errors.
sys__ebadf
OldFile hasn’t been assigned.
sys__emfile
Maximum number of open files for the process is reached.
See also:
Dup (368), Dup2 (2)

Listing: linuxex/ex32.pp


program Example31;

{ Program to demonstrate the Dup function. }

uses linux;

var f : text;
    i : longint;

begin
  Assign (f,'text.txt');
  Rewrite (F);
  For i:=1 to 10 do writeln (F,'Line : ',i);
  if not dup2 (output,f) then
    Writeln ('Dup2 Failed !');
  writeln ('This is written to stdout.');
  writeln (f,'This is written to the dup file, and flushed');
  flush(f);
  writeln;
  { Remove file. Comment this if you want to check flushing.}
  Unlink ('text.txt');
end.

EpochToLocal

Declaration:
Procedure EpochToLocal (Epoch : Longint; var Year,Month,Day,Hour,Minute,Second : Word);
Description:
Converts the epoch time (=Number of seconds since 00:00:00 , January 1, 1970, corrected for your time zone ) to local date and time.

This function takes into account the timzeone settings of your system.

Errors:
None
See also:
GetEpochTime (395), LocalToEpoch (410), GetTime (399),GetDate (391)

Listing: linuxex/ex3.pp


Program Example3;

{ Program to demonstrate the EpochToLocal function. }

Uses linux;

Var Year,month,day,hour,minute,seconds : Word;

begin
  EpochToLocal (GetEpochTime,Year,month,day,hour,minute,seconds);
  Writeln ('Current date : ',Day:2,'/',Month:2,'/',Year:4);
  Writeln ('Current time : ',Hour:2,':',minute:2,':',seconds:2);
end.

Execl

Declaration:
Procedure Execl (Path : pathstr);
Description:
Replaces the currently running program with the program, specified in path. Path is split into a command and it’s options. The executable in path is NOT searched in the path. The current environment is passed to the program. On success, execl does not return.
Errors:
Errors are reported in LinuxError:
sys__eacces
File is not a regular file, or has no execute permission. A compononent of the path has no search permission.
sys__eperm
The file system is mounted noexec.
sys__e2big
Argument list too big.
sys__enoexec
The magic number in the file is incorrect.
sys__enoent
The file does not exist.
sys__enomem
Not enough memory for kernel, or to split command line.
sys__enotdir
A component of the path is not a directory.
sys__eloop
The path contains a circular reference (via symlinks).
See also:
Execve (375), Execv (374), Execvp (376), Execle (372), Execlp (373), Fork (390), execvp (3)

Listing: linuxex/ex10.pp


Program Example10;

{ Program to demonstrate the Execl function. }

Uses linux, strings;

begin
  { Execute 'ls -l', with current environment. }
  { 'ls' is NOT looked for in PATH environment variable.}
  Execl ('/bin/ls -l');
end.

Execle

Declaration:
Procedure Execle (Path : pathstr, Ep : ppchar);
Description:
Replaces the currently running program with the program, specified in path. Path is split into a command and it’s options. The executable in path is searched in the path, if it isn’t an absolute filename. The environment in ep is passed to the program. On success, execle does not return.
Errors:
Errors are reported in LinuxError:
sys__eacces
File is not a regular file, or has no execute permission. A compononent of the path has no search permission.
sys__eperm
The file system is mounted noexec.
sys__e2big
Argument list too big.
sys__enoexec
The magic number in the file is incorrect.
sys__enoent
The file does not exist.
sys__enomem
Not enough memory for kernel, or to split command line.
sys__enotdir
A component of the path is not a directory.
sys__eloop
The path contains a circular reference (via symlinks).
See also:
Execve (375), Execv (374), Execvp (376), Execl (371), Execlp (373), Fork (390), execvp (3)

Listing: linuxex/ex11.pp


Program Example11;

{ Program to demonstrate the Execle function. }

Uses linux, strings;

begin
  { Execute 'ls -l', with current environment. }
  { 'ls' is NOT looked for in PATH environment variable.}
  { envp is defined in the system unit.}
  Execle ('/bin/ls -l',envp);
end.

Execlp

Declaration:
Procedure Execlp (Path : pathstr);
Description:
Replaces the currently running program with the program, specified in path. Path is split into a command and it’s options. The executable in path is searched in the path, if it isn’t an absolute filename. The current environment is passed to the program. On success, execlp does not return.
Errors:
Errors are reported in LinuxError:
sys__eacces
File is not a regular file, or has no execute permission. A compononent of the path has no search permission.
sys__eperm
The file system is mounted noexec.
sys__e2big
Argument list too big.
sys__enoexec
The magic number in the file is incorrect.
sys__enoent
The file does not exist.
sys__enomem
Not enough memory for kernel, or to split command line.
sys__enotdir
A component of the path is not a directory.
sys__eloop
The path contains a circular reference (via symlinks).
See also:
Execve (375), Execv (374), Execvp (376), Execle (372), Execl (371), Fork (390), execvp (3)

Listing: linuxex/ex12.pp


Program Example12;

{ Program to demonstrate the Execlp function. }

Uses linux, strings;

begin
  { Execute 'ls -l', with current environment. }
  { 'ls' is looked for in PATH environment variable.}
  { envp is defined in the system unit.}
  Execlp ('ls -l',envp);
end.

Execv

Declaration:
Procedure Execv (Path : pathstr; args : ppchar);
Description:
Replaces the currently running program with the program, specified in path. It gives the program the options in args. This is a pointer to an array of pointers to null-terminated strings. The last pointer in this array should be nil. The current environment is passed to the program. On success, execv does not return.
Errors:
Errors are reported in LinuxError:
sys__eacces
File is not a regular file, or has no execute permission. A compononent of the path has no search permission.
sys__eperm
The file system is mounted noexec.
sys__e2big
Argument list too big.
sys__enoexec
The magic number in the file is incorrect.
sys__enoent
The file does not exist.
sys__enomem
Not enough memory for kernel.
sys__enotdir
A component of the path is not a directory.
sys__eloop
The path contains a circular reference (via symlinks).
See also:
Execve (375), Execvp (376), Execle (372), Execl (371), Execlp (373), Fork (390), execv (3)

Listing: linuxex/ex8.pp


Program Example8;

{ Program to demonstrate the Execv function. }

Uses linux, strings;

Const Arg0 : PChar = '/bin/ls';
      Arg1 : Pchar = '-l';

Var PP : PPchar;


begin
  GetMem (PP,3*SizeOf(Pchar));
  PP[0]:=Arg0;
  PP[1]:=Arg1;
  PP[3]:=Nil;
  { Execute '/bin/ls -l', with current environment }
  Execv ('/bin/ls',pp);
end.

Execve

Declaration:
Procedure Execve(Path:pchar;args:ppchar;ep:ppchar); Procedure Execve (Path : pathstr; args,ep : ppchar);
Description:
Replaces the currently running program with the program, specified in path. It gives the program the options in args, and the environment in ep. They are pointers to an array of pointers to null-terminated strings. The last pointer in this array should be nil. On success, execve does not return.
Errors:
Errors are reported in LinuxError:
eacces
File is not a regular file, or has no execute permission. A compononent of the path has no search permission.
sys__eperm
The file system is mounted noexec.
sys__e2big
Argument list too big.
sys__enoexec
The magic number in the file is incorrect.
sys__enoent
The file does not exist.
sys__enomem
Not enough memory for kernel.
sys__enotdir
A component of the path is not a directory.
sys__eloop
The path contains a circular reference (via symlinks).
See also:
Execve (375), Execv (374), Execvp (376) Execle (372), Execl (371), Execlp (373), Fork (390), execve (2)

Listing: linuxex/ex7.pp


Program Example7;

{ Program to demonstrate the Execve function. }

Uses linux, strings;

Const Arg0 : PChar = '/bin/ls';
      Arg1 : Pchar = '-l';

Var PP : PPchar;


begin
  GetMem (PP,3*SizeOf(Pchar));
  PP[0]:=Arg0;
  PP[1]:=Arg1;
  PP[3]:=Nil;
  { Execute '/bin/ls -l', with current environment }
  { Envp is defined in system.inc }
  ExecVe ('/bin/ls',pp,envp);
end.

Execvp

Declaration:
Procedure Execvp (Path : pathstr; args : ppchar);
Description:
Replaces the currently running program with the program, specified in path. The executable in path is searched in the path, if it isn’t an absolute filename. It gives the program the options in args. This is a pointer to an array of pointers to null-terminated strings. The last pointer in this array should be nil. The current environment is passed to the program. On success, execvp does not return.
Errors:
Errors are reported in LinuxError:
sys__eacces
File is not a regular file, or has no execute permission. A compononent of the path has no search permission.
sys__eperm
The file system is mounted noexec.
sys__e2big
Argument list too big.
sys__enoexec
The magic number in the file is incorrect.
sys__enoent
The file does not exist.
sys__enomem
Not enough memory for kernel.
sys__enotdir
A component of the path is not a directory.
sys__eloop
The path contains a circular reference (via symlinks).
See also:
Execve (375), Execv (374), Execle (372), Execl (371), Execlp (373), Fork (390), execvp (3)

Listing: linuxex/ex9.pp


Program Example9;

{ Program to demonstrate the Execvp function. }

Uses linux, strings;

Const Arg0 : PChar = 'ls';
      Arg1 : Pchar = '-l';

Var PP : PPchar;


begin
  GetMem (PP,3*SizeOf(Pchar));
  PP[0]:=Arg0;
  PP[1]:=Arg1;
  PP[3]:=Nil;
  { Execute 'ls -l', with current environment. }
  { 'ls' is looked for in PATH environment variable.}
  { Envp is defined in the system unit. }
  Execvp ('ls',pp,envp);
end.

FD__ZERO

Declaration:
Procedure FD_ZERO (var fds:fdSet);
Description:
FD_ZERO clears all the filedescriptors in the file descriptor set fds.
Errors:
None.
See also:
Select (423), SelectText (424), GetFS (395), FD__Clr (377), FD__Set (378), FD__IsSet (378)

For an example, see Select (423).

FD__Clr

Declaration:
Procedure FD_Clr (fd:longint;var fds:fdSet);
Description:
FD_Clr clears file descriptor fd in filedescriptor s et fds.
Errors:
None.
See also:
Select (423), SelectText (424), GetFS (395), FD__ZERO (377), FD__Set (378), FD__IsSet (378)

For an example, see Select (423).

FD__IsSet

Declaration:
Function FD_IsSet (fd:longint;var fds:fdSet) : boolean;
Description:
FD_Set Checks whether file descriptor fd in filedescriptor set fds is set.
Errors:
None.
See also:
Select (423), SelectText (424), GetFS (395), FD__ZERO (377), FD__Clr (377), FD__Set (378)

For an example, see Select (423).

FD__Set

Declaration:
Procedure FD_Set (fd:longint;var fds:fdSet);
Description:
FD_Set sets file descriptor fd in filedescriptor set fds.
Errors:
None.
See also:
Select (423), SelectText (424), GetFS (395),FD__ZERO (377), FD__Clr (377), FD__IsSet (378)

For an example, see Select (423).

fdClose

Declaration:
Function fdClose (fd:longint) : boolean;
Description:
fdClose closes a file with file descriptor Fd. The function returns True if the file was closed successfully, False otherwise.
Errors:
Errors are returned in LinuxError
See also:
fdOpen (379), fdRead (381), fdWrite (383),fdTruncate (382), fdFlush (379), seefFdSeek

For an example, see fdOpen (379).

fdFlush

Declaration:
Function fdFlush (fd:Longint) : boolean;
Description:
fdflush flushes the Linux kernel file buffer, so the file is actually written to disk. This is NOT the same as the internal buffer, maintained by Free Pascal. The function returns True if the call was successful, false if an error occurred.
Errors:
Errors are returned in LinuxError.
See also:
fdOpen (379), fdClose (378), fdRead (381),fdWrite (383), fdTruncate (382), fdSeek (382)

For an example, see fdRead (381).

fdOpen

Declaration:
Function fdOpen(PathName:String;flags:longint):longint; Function fdOpen(PathName:Pchar ;flags:longint):longint; Function fdOpen(PathName:String;flags,mode:longint):longint; Function fdOpen(PathName:Pchar ;flags,mode:longint):longint;
Description:
fdOpen opens a file in PathName with flags flags One of the following:
Open__RdOnly
File is opened Read-only.
Open__WrOnly
File is opened Write-only.
Open__RdWr
File is opened Read-Write.

The flags may beOR-ed with one of the following constants:

Open__Accmode
File is opened
Open__Creat
File is created if it doesn’t exist.
Open__Excl
If the file is opened with Open_Creat and it already exists, the call wil fail.
Open__NoCtty
If the file is a terminal device, it will NOT become the process’ controlling terminal.
Open__Trunc
If the file exists, it will be truncated.
Open__Append
the file is opened in append mode. Before each write, the file pointer is positioned at the end of the file.
Open__NonBlock
The file is opened in non-blocking mode. No operation on the file descriptor will cause the calling process to wait till.
Open__NDelay
Idem as Open_NonBlock
Open__Sync
The file is opened for synchronous IO. Any write operation on the file will not return untill the data is physically written to disk.
Open__NoFollow
if the file is a symbolic link, the open fails. (LINUX 2.1.126 and higher only)
Open__Directory
if the file is not a directory, the open fails. (LINUX 2.1.126 and higher only)

PathName can be of type PChar or String. The optional mode argument specifies the permissions to set when opening the file. This is modified by the umask setting. The real permissions are Mode and not umask. The return value of the function is the filedescriptor, or a negative value if there was an error.

Errors:
Errors are returned in LinuxError
See also:
fdClose (378), fdRead (381), fdWrite (383),fdTruncate (382), fdFlush (379), fdSeek (382)

Listing: linuxex/ex19.pp


Program Example19;

{ Program to demonstrate the fdOpen, fdwrite and fdCLose functions. }

Uses linux;

Const Line : String[80] = 'This is easy writing !';

Var FD : Longint;

begin
  FD:=fdOpen ('Test.dat',Open_WrOnly or Open_Creat);
  if FD>0 then
    begin
    if length(Line)<>fdwrite (FD,Line[1],Length(Line)) then
      Writeln ('Error when writing to file !');
    fdClose(FD);
    end;
end.

fdRead

Declaration:
Function fdRead (fd:longint;var buf;size:longint) : longint;
Description:
fdRead reads at most size bytes from the file descriptor fd, and stores them in buf. The function returns the number of bytes actually read, or -1 if an error occurred. No checking on the length of buf is done.
Errors:
Errors are returned in LinuxError.
See also:
fdOpen (379), fdClose (378), fdWrite (383),fdTruncate (382), fdFlush (379), fdSeek (382)

Listing: linuxex/ex20.pp


Program Example20;

{ Program to demonstrate the fdRead and fdTruncate functions. }

Uses linux;

Const Data : string[10] = '12345687890';

Var FD : Longint;
    l : longint;

begin
  FD:=fdOpen('test.dat',open_wronly or open_creat,octal(666));
  if fd>0 then
    begin
    { Fill file with data }
    for l:=1 to 10 do
      if fdWrite (FD,Data[1],10)<>10 then
        begin
        writeln ('Error when writing !');
        halt(1);
        end;
    fdClose(FD);
    FD:=fdOpen('test.dat',open_rdonly);
    { Read data again }
    If FD>0 then
      begin
      For l:=1 to 5 do
        if fdRead (FD,Data[1],10)<>10 then
          begin
          Writeln ('Error when Reading !');
          Halt(2);
          end;
      fdCLose(FD);
      { Truncating file at 60 bytes }
      { For truncating, file must be open or write }
      FD:=fdOpen('test.dat',open_wronly,octal(666));
      if FD>0 then
        begin
        if not fdTruncate(FD,60) then
           Writeln('Error when truncating !');
        fdClose (FD);
        end;
      end;
    end;
end.

fdSeek

Declaration:
Function fdSeek (fd,Pos,SeekType:longint) : longint;
Description:
fdSeek sets the current fileposition of file fd to Pos, starting from SeekType, which can be one of the following:
Seek__Set
 Pos is the absolute position in the file.
Seek__Cur
 Pos is relative to the current position.
Seek__end
 Pos is relative to the end of the file.

The function returns the new fileposition, or -1 of an error occurred.

Errors:
Errors are returned in LinuxError.
See also:
fdOpen (379), fdWrite (383), fdClose (378), fdRead (381),fdTruncate (382), fdFlush (379)

For an example, see fdOpen (379).

fdTruncate

Declaration:
Function fdTruncate (fd,size:longint) : boolean;
Description:
fdTruncate sets the length of a file in fd on size bytes, where size must be less than or equal to the current length of the file in fd. The function returns True if the call was successful, false if an error occurred.
Errors:
Errors are returned in LinuxError.
See also:
fdOpen (379), fdClose (378), fdRead (381),fdWrite (383),fdFlush (379), fdSeek (382)

fdWrite

Declaration:
Function fdWrite (fd:longint;var buf;size:longint) : longint;
Description:
fdWrite writes at most size bytes from buf to file descriptor fd. The function returns the number of bytes actually written, or -1 if an error occurred.
Errors:
Errors are returned in LinuxError.
See also:
fdOpen (379), fdClose (378), fdRead (381),fdTruncate (382), fdSeek (382), fdFlush (379)

FExpand

Declaration:
Function FExpand (Const Path: Pathstr) : pathstr;
Description:
Expands Path to a full path, starting from root, eliminating directory references such as . and .. from the result.
Errors:
None
See also:
BaseName (359),DirName (367)

Listing: linuxex/ex45.pp


Program Example45;

{ Program to demonstrate the FExpand function. }

Uses linux;

begin
  Writeln ('This program is in : ',FExpand(Paramstr(0)));
end.

FLock

Declaration:
Function Flock (fd,mode : longint) : boolean; Function Flock (var T : text;mode : longint) : boolean; Function Flock (var F : File;mode : longint) : boolean;
Description:
FLock implements file locking. it sets or removes a lock on the file F. F can be of type Text or File, or it can be a LINUX filedescriptor (a longint) Mode can be one of the following constants :
LOCK__SH
 sets a shared lock.
LOCK__EX
 sets an exclusive lock.
LOCK__UN
 unlocks the file.
LOCK__NB
 This can be OR-ed together with the other. If this is done the application doesn’t block when locking.

The function returns True if successful, False otherwise.

Errors:
If an error occurs, it is reported in LinuxError.
See also:
Fcntl (389), flock (2)

FNMatch

Declaration:
Function FNMatch(const Pattern,Name:string):Boolean;
Description:
FNMatch returns True if the filename in Name matches the wildcard pattern in Pattern, False otherwise.

Pattern can contain the wildcards * (match zero or more arbitrary characters) or ? (match a single character).

Errors:
None.
See also:
FSearch (385), FExpand (383)

Listing: linuxex/ex69.pp


Program Example69;

{ Program to demonstrate the FNMatch function. }

Uses linux;

  Procedure TestMatch(Pattern,Name : String);

  begin
    Write ('"',Name,'" ');
    If FNMatch (Pattern,Name) then
      Write ('matches')
    else
      Write ('does not match');
    Writeln(' "',Pattern,'".');
  end;

begin
  TestMatch('*','FileName');
  TestMatch('.*','FileName');
  TestMatch('*a*','FileName');
  TestMatch('?ile*','FileName');
  TestMatch('?','FileName');
  TestMatch('.?','FileName');
  TestMatch('?a*','FileName');
  TestMatch('??*me?','FileName');
end.

FSearch

Declaration:
Function FSearch (Path : pathstr;DirList : string) : Pathstr;
Description:
Searches in DirList, a colon separated list of directories, for a file named Path. It then returns a path to the found file.
Errors:
An empty string if no such file was found.
See also:
BaseName (359), DirName (367), FExpand (383), FNMatch (384)

Listing: linuxex/ex46.pp


Program Example46;

{ Program to demonstrate the FSearch function. }

Uses linux,strings;

begin
  Writeln ('ls is in : ',FSearch ('ls',strpas(Getenv('PATH'))));
end.

FSplit

Declaration:
Procedure FSplit(const Path:PathStr;
Var Dir:DirStr;Var Name:NameStr;Var Ext:ExtStr);
Description:
FSplit splits a full file name into 3 parts : A Path, a Name and an extension (in ext). The extension is taken to be all letters after the last dot (.).
Errors:
None.
See also:
FSearch (385)

Listing: linuxex/ex67.pp


Program Example67;

uses Linux;

{ Program to demonstrate the FSplit function. }

var
  Path,Name,Ext : string;

begin
  FSplit(ParamStr(1),Path,Name,Ext);
  WriteLn('Split ',ParamStr(1),' in:');
  WriteLn('Path     : ',Path);
  WriteLn('Name     : ',Name);
  WriteLn('Extension: ',Ext);
end.

FSStat

Declaration:
Function FSStat (Path : Pathstr; Var Info : statfs) : Boolean; Function FSStat (Fd:longint;Var Info:stat) : Boolean;
Description:
Return in Info information about the filesystem on which the file Path resides, or on which the file with file descriptor fd resides. Info is of type statfs. The function returns True if the call was succesfull, False if the call failed.
Errors:
LinuxError is used to report errors.
sys__enotdir
A component of Path is not a directory.
sys__einval
Invalid character in Path.
sys__enoent
Path does not exist.
sys__eaccess
Search permission is denied for component in Path.
sys__eloop
A circular symbolic link was encountered in Path.
sys__eio
An error occurred while reading from the filesystem.
See also:
FStat (387), LStat (407), statfs (2)

Listing: linuxex/ex30.pp


program Example30;

{ Program to demonstrate the FSStat function. }

uses linux;

var s : string;
    info : statfs;

begin
  writeln ('Info about current partition : ');
  s:='.';
  while s<>'q' do
    begin
    if not fsstat (s,info) then
       begin
       writeln('Fstat failed. Errno : ',linuxerror);
       halt (1);
       end;
    writeln;
    writeln ('Result of fsstat on file ''',s,'''.');
    writeln ('fstype  : ',info.fstype);
    writeln ('bsize   : ',info.bsize);
    writeln ('bfree   : ',info.bfree);
    writeln ('bavail  : ',info.bavail);
    writeln ('files   : ',info.files);
    writeln ('ffree   : ',info.ffree);
    writeln ('fsid    : ',info.fsid);
    writeln ('Namelen : ',info.namelen);
    write ('Type name of file to do fsstat. (q quits) :');
    readln (s)
    end;
end.

FStat

Declaration:
Function FStat(Path:Pathstr;Var Info:stat):Boolean; Function FStat(Fd:longint;Var Info:stat):Boolean; Function FStat(var F:Text;Var Info:stat):Boolean; Function FStat(var F:File;Var Info:stat):Boolean;
Description:
FStat gets information about the file specified in one of the following:
Path
a file on the filesystem.
Fd
a valid file descriptor.
F
an opened text file or untyped file.

and stores it in Info, which is of type stat. The function returns True if the call was succesfull, False if the call failed.

Errors:
LinuxError is used to report errors.
sys__enoent
Path does not exist.
See also:
FSStat (386), LStat (407), stat (2)

Listing: linuxex/ex28.pp


program example28;

{ Program to demonstrate the FStat function. }

uses linux;

var f : text;
    i : byte;
    info : stat;

begin
  { Make a file }
  assign (f,'test.fil');
  rewrite (f);
  for i:=1 to 10 do writeln (f,'Testline # ',i);
  close (f);
  { Do the call on made file. }
  if not fstat ('test.fil',info) then
     begin
     writeln('Fstat failed. Errno : ',linuxerror);
     halt (1);
     end;
  writeln;
  writeln ('Result of fstat on file ''test.fil''.');
  writeln ('Inode   : ',info.ino);
  writeln ('Mode    : ',info.mode);
  writeln ('nlink   : ',info.nlink);
  writeln ('uid     : ',info.uid);
  writeln ('gid     : ',info.gid);
  writeln ('rdev    : ',info.rdev);
  writeln ('Size    : ',info.size);
  writeln ('Blksize : ',info.blksze);
  writeln ('Blocks  : ',info.blocks);
  writeln ('atime   : ',info.atime);
  writeln ('mtime   : ',info.mtime);
  writeln ('ctime   : ',info.ctime);
  { Remove file }
  erase (f);
end.

Fcntl

Declaration:
Function Fcntl(Fd:longint;Cmd:Integer):integer; Function Fcntl(var Fd:Text;Cmd:Integer):integer;
Description:
Read a file’s attributes. Fd is an assigned file, or a valid file descriptor. Cmd speciefies what to do, and is one of the following:
F__GetFd
Read the close__on__exec flag. If the low-order bit is 0, then the file will remain open across execve calls.
F__GetFl
Read the descriptor’s flags.
F__GetOwn
Get the Process ID of the owner of a socket.
Errors:
LinuxError is used to report errors.
sys__ebadf
Fd has a bad file descriptor.
See also:
Fcntl (389), Fcntl (2)

Fcntl

Declaration:
Procedure Fcntl (Fd : text, Cmd : Integer; Arg : longint); Procedure Fcntl (Fd:longint;Cmd:longint;Arg:Longint);
Description:
Read or Set a file’s attributes. Fd is an assigned file or a valid file descriptor. Cmd speciefies what to do, and is one of the following:
F__SetFd
Set the close__on__exec flag of Fd. (only the least siginificant bit is used).
F__GetLk
Return the flock record that prevents this process from obtaining the lock, or set the l_type field of the lock of there is no obstruction. Arg is a pointer to a flock record.
F__SetLk
Set the lock or clear it (depending on l_type in the flock structure). if the lock is held by another process, an error occurs.
F__GetLkw
Same as for F__Setlk, but wait until the lock is released.
F__SetOwn
Set the Process or process group that owns a socket.
Errors:

LinuxError is used to report errors.

sys__ebadf
Fd has a bad file descriptor.
sys__eagain or sys__eaccess
For F__SetLk, if the lock is held by another process.
See also:
Fcntl (389), Fcntl (2) , seefFLock

Fork

Declaration:
Function Fork : Longint;
Description:
Fork creates a child process which is a copy of the parent process. Fork returns the process ID in the parent process, and zero in the child’s process. (you can get the parent’s PID with GetPPid (398)).
Errors:
On error, -1 is returned to the parent, and no child is created.
sys__eagain
Not enough memory to create child process.
See also:
Execve (375), Clone (364), fork (2)

FRename

Declaration:
Function FReName (OldName,NewName : Pchar) : Boolean; Function FReName (OldName,NewName : String) : Boolean;
Description:
FRename renames the file OldName to NewName. NewName can be in a different directory than OldName, but it cannot be on another partition (device). Any existing file on the new location will be replaced.

If the operation fails, then the OldName file will be preserved.

The function returns True on succes, False on failure.

Errors:
On error, errors are reported in LinuxError. Possible errors include:
sys__eisdir
NewName exists and is a directory, but OldName is not a directory.
sys__exdev
NewName and OldName are on different devices.
sys__enotempty or sys__eexist
NewName is an existing, non-empty directory.
sys__ebusy
OldName or NewName is a directory and is in use by another process.
sys__einval
NewName is part of OldName.
sys__emlink
OldPath or NewPath already have tha maximum amount of links pointing to them.
sys__enotdir
part of OldName or NewName is not directory.
sys__efault
For the pchar case: One of the pointers points to an invalid address.
sys__eaccess
access is denied when attempting to move the file.
sys__enametoolong
Either OldName or NewName is too long.
sys__enoent
a directory component in OldName or NewName didn’t exist.
sys__enomem
not enough kernel memory.
sys__erofs
NewName or OldName is on a read-only file system.
sys__eloop
too many symbolic links were encountered trying to expand OldName or NewName
sys__enospc
the filesystem has no room for the new directory entry.
See also:
UnLink (439)

GetDate

Declaration:
Procedure GetDate (Var Year, Month, Day : Word) ;
Description:
Returns the current date.
Errors:
None
See also:
GetEpochTime (395), GetTime (399), GetDateTime (392), EpochToLocal (370)

Listing: linuxex/ex6.pp


Program Example6;

{ Program to demonstrate the GetDate function. }

Uses linux;

Var Year, Month, Day : Word;

begin
 GetDate (Year, Month, Day);
 Writeln ('Date : ',Day:2,'/',Month:2,'/',Year:4);
end.

GetDateTime

Declaration:
Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
Description:
Returns the current date and time. The time is corrected for the local time zone. This procedure is equivalent to the GetDate (391) and GetTime calls.
Errors:
None
See also:
GetEpochTime (395), GetTime (399), EpochToLocal (370), GetDate (391)

Listing: linuxex/ex60.pp


Program Example6;

{ Program to demonstrate the GetDateTime function. }

Uses linux;

Var Year, Month, Day, Hour, min, sec : Word;

begin
 GetDateTime (Year, Month, Day, Hour, min, sec);
 Writeln ('Date : ',Day:2,'/',Month:2,'/',Year:4);
 Writeln ('Time : ',Hour:2,':',Min:2,':',Sec:2);
end.

GetDomainName

Declaration:
Function GetDomainName : String;
Description:
Get the domain name of the machine on which the process is running. An empty string is returned if the domain is not set.
Errors:
None.
See also:
GetHostName (397),seemGetdomainname2

Listing: linuxex/ex39.pp


Program Example39;

{ Program to demonstrate the GetDomainName function. }

Uses linux;

begin
  Writeln ('Domain name of this machine is : ',GetDomainName);
end.

GetEGid

Declaration:
Function GetEGid : Longint;
Description:
Get the effective group ID of the currently running process.
Errors:
None.
See also:
GetGid (396), getegid (2)

Listing: linuxex/ex18.pp


Program Example18;

{ Program to demonstrate the GetGid and GetEGid functions. }

Uses linux;

begin
 writeln ('Group Id = ',getgid,' Effective group Id = ',getegid);
end.

GetEUid

Declaration:
Function GetEUid : Longint;
Description:
Get the effective user ID of the currently running process.
Errors:
None.
See also:
GetEUid (394), geteuid (2)

Listing: linuxex/ex17.pp


Program Example17;

{ Program to demonstrate the GetUid and GetEUid functions. }

Uses linux;

begin
  writeln ('User Id = ',getuid,' Effective user Id = ',geteuid);
end.

GetEnv

Declaration:
Function GetEnv (P : String) : PChar;
Description:
Returns the value of the environment variable in P. If the variable is not defined, nil is returned. The value of the environment variable may be the empty string. A PChar is returned to accomodate for strings longer than 255 bytes, TERMCAP and LS_COLORS, for instance.
Errors:
None.
See also:
sh (1) , csh (1)

Listing: linuxex/ex41.pp


Program Example41;

{ Program to demonstrate the GetEnv function. }

Uses linux;

begin
  Writeln ('Path is : ',Getenv('PATH'));
end.

GetEpochTime

Declaration:
Function GetEpochTime : longint;
Description:
returns the number of seconds since 00:00:00 gmt, january 1, 1970. it is adjusted to the local time zone, but not to DST.
Errors:
no errors
See also:
EpochToLocal (370), GetTime (399), time (2)

Listing: linuxex/ex1.pp


Program Example1;

{ Program to demonstrate the GetEpochTime function. }

Uses linux;

begin
  Write ('Secs past the start of the Epoch (00:00 1/1/1980) : ');
  Writeln (GetEpochTime);
end.

GetFS

Declaration:
Function GetFS (Var F : Any File Type) : Longint;
Description:
GetFS returns the file selector that the kernel provided for your file. In principle you don’ need this file selector. Only for some calls it is needed, such as the Select (423) call or so.
Errors:
In case the file was not opened, then -1 is returned.
See also:
Select (423)

Listing: linuxex/ex34.pp


Program Example33;

{ Program to demonstrate the SelectText function. }

Uses linux;

Var tv : TimeVal;

begin
  Writeln ('Press the <ENTER> to continue the program.');
  { Wait until File descriptor 0 (=Input) changes }
  SelectText (Input,nil);
  { Get rid of <ENTER> in buffer }
  readln;
  Writeln ('Press <ENTER> key in less than 2 seconds...');
  tv.sec:=2;
  tv.usec:=0;
  if SelectText (Input,@tv)>0 then
    Writeln ('Thank you !')
  else
    Writeln ('Too late !');
end.

GetGid

Declaration:
Function GetGid : Longint;
Description:
Get the real group ID of the currently running process.
Errors:
None.
See also:
GetEGid (393), getgid (2)

Listing: linuxex/ex18.pp


Program Example18;

{ Program to demonstrate the GetGid and GetEGid functions. }

Uses linux;

begin
 writeln ('Group Id = ',getgid,' Effective group Id = ',getegid);
end.

GetHostName

Declaration:
Function GetHostName : String;
Description:
Get the hostname of the machine on which the process is running. An empty string is returned if hostname is not set.
Errors:
None.
See also:
GetDomainName (392),seemGethostname2

Listing: linuxex/ex40.pp


Program Example40;

{ Program to demonstrate the GetHostName function. }

Uses linux;

begin
  Writeln ('Name of this machine is : ',GetHostName);
end.

GetLocalTimezone

Declaration:
procedure GetLocalTimezone(timer:longint;var leap_correct,leap_hit:longint); procedure GetLocalTimezone(timer:longint);
Description:
GetLocalTimeZone returns the local timezone information. It also initializes the TZSeconds variable, which is used to correct the epoch time to local time.

There should never be any need to call this function directly. It is called by the initialization routines of the Linux unit.

See also:
GetTimezoneFile (400), ReadTimezoneFile (422)

GetPid

Declaration:
Function GetPid : Longint;
Description:
Get the Process ID of the currently running process.
Errors:
None.
See also:
GetPPid (398), getpid (2)

Listing: linuxex/ex16.pp


Program Example16;

{ Program to demonstrate the GetPid, GetPPid function. }

Uses linux;

begin
  Writeln ('Process Id = ',getpid,' Parent process Id = ',getppid);
end.

GetPPid

Declaration:
Function GetPPid : Longint;
Description:
Get the Process ID of the parent process.
Errors:
None.
See also:
GetPid (397), getppid (2)

Listing: linuxex/ex16.pp


Program Example16;

{ Program to demonstrate the GetPid, GetPPid function. }

Uses linux;

begin
  Writeln ('Process Id = ',getpid,' Parent process Id = ',getppid);
end.

GetPriority

Declaration:
Function GetPriority (Which,Who : Integer) : Integer;
Description:
GetPriority returns the priority with which a process is running. Which process(es) is determined by the Which and Who variables. Which can be one of the pre-defined Prio_Process, Prio_PGrp, Prio_User, in which case Who is the process ID, Process group ID or User ID, respectively.
Errors:

Error checking must be done on LinuxError, since a priority can be negative.

sys__esrch
No process found using which and who.
sys__einval
Which was not one of Prio_Process, Prio_Grp or Prio_User.
See also:
SetPriority (424), Nice (414), Getpriority (2)

For an example, see Nice (414).

GetTime

Declaration:
procedure GetTime(var hour,min,sec,msec,usec:word); procedure GetTime(var hour,min,sec,sec100:word); procedure GetTime(var hour,min,sec:word);
Description:
Returns the current time of the day, adjusted to local time. Upon return, the parameters are filled with
hour
Hours since 00:00 today.
min
minutes in current hour.
sec
seconds in current minute.
sec100
hundreds of seconds in current second.
msec
milliseconds in current second.
usec
microseconds in current second.
Errors:
None
See also:
GetEpochTime (395), GetDate (391), GetDateTime (392), EpochToLocal (370)

Listing: linuxex/ex5.pp


Program Example5;

{ Program to demonstrate the GetTime function. }

Uses linux;

Var Hour, Minute, Second : Word;

begin
  GetTime (Hour, Minute, Second);
  Writeln ('Time : ',Hour:2,':',Minute:2,':',Second:2);
end.

GetTimeOfDay

Declaration:
Procedure GetTimeOfDay(var tv:timeval);
Description:
GetTimeOfDay returns the number of seconds since 00:00, January 1 1970, GMT in a timeval record. This time NOT corrected any way, not taking into account timezones, daylight savings time and so on.

It is simply a wrapper to the kernel system call. To get the local time, GetTime (399).

Errors:
None.
See also:
GetTime (399), GetTimeOfDay (400)

GetTimeOfDay

Declaration:
Function GetTimeOfDay:longint;
Description:
GetTimeOfDay returns the number of seconds since 00:00, January 1 1970, GMT. This time NOT corrected any way, not taking into account timezones, daylight savings time and so on.

It is simply a wrapper to the kernel system call. To get the local time, GetTime (399).

Errors:
None.
See also:
GetTimeOfDay (400), GetTime (399)

GetTimezoneFile

Declaration:
function GetTimezoneFile:string;
Description:
GetTimezoneFile returns the location of the current timezone file. The location of file is determined as follows:
  1. If /etc/timezone exists, it is read, and the contents of this file is returned. This should work on Debian systems.
  2. If /usr/lib/zoneinfo/localtime exists, then it is returned. (this file is a symlink to the timezone file on SuSE systems)
  3. If /etc/localtime exists, then it is returned. (this file is a symlink to the timezone file on RedHat systems)
Errors:
If no file was found, an empty string is returned.
See also:
ReadTimezoneFile (422)

GetUid

Declaration:
Function GetUid : Longint;
Description:
Get the real user ID of the currently running process.
Errors:
None.
See also:
GetEUid (394), getuid (2)

Listing: linuxex/ex17.pp


Program Example17;

{ Program to demonstrate the GetUid and GetEUid functions. }

Uses linux;

begin
  writeln ('User Id = ',getuid,' Effective user Id = ',geteuid);
end.

Glob

Declaration:
Function Glob (Const Path : Pathstr) : PGlob;
Description:
Glob returns a pointer to a glob structure which contains all filenames which exist and match the pattern in Path. The pattern can contain wildcard characters, which have their usual meaning.
Errors:
Returns nil on error, and LinuxError is set.
sys__enomem
No memory on heap for glob structure.
others
As returned by the opendir call, and sys__readdir.
See also:
GlobFree (402), Glob (3)

Listing: linuxex/ex49.pp


Program Example49;

{ Program to demonstrate the Glob and GlobFree functions. }

Uses linux;

Var G1,G2 : PGlob;

begin
  G1:=Glob ('*');
  if LinuxError=0 then
    begin
    G2:=G1;
    Writeln ('Files in this directory : ');
    While g2<>Nil do
      begin
      Writeln (g2^.name);
      g2:=g2^.next;
      end;
    GlobFree (g1);
    end;
end.

GlobFree

Declaration:
Procedure GlobFree (Var P : Pglob);
Description:
Releases the memory, occupied by a pglob structure. P is set to nil.
Errors:
None
See also:
Glob (401)

For an example, see Glob (401).

IOCtl

Declaration:
Procedure IOCtl (Handle,Ndx: Longint; Data: Pointer);
Description:
This is a general interface to the Unix/ LINUX ioctl call. It performs various operations on the filedescriptor Handle. Ndx describes the operation to perform. Data points to data needed for the Ndx function. The structure of this data is function-dependent, so we don’t elaborate on this here. For more information on this, see various manual pages under linux.
Errors:

Errors are reported in LinuxError. They are very dependent on the used function, that’s why we don’t list them here

See also:
ioctl (2)

Listing: linuxex/ex54.pp


Program Example54;

uses Linux;

{ Program to demonstrate the IOCtl function. }

var
  tios : Termios;
begin
  IOCtl(1,TCGETS,@tios);
  WriteLn('Input Flags  : $',hexstr(tios.c_iflag,8));
  WriteLn('Output Flags : $',hexstr(tios.c_oflag,8));
  WriteLn('Line Flags   : $',hexstr(tios.c_lflag,8));
  WriteLn('Control Flags: $',hexstr(tios.c_cflag,8));
end.

IOperm

Declaration:
Function IOperm (From,Num : Cadinal; Value : Longint) : boolean;
Description:
IOperm sets permissions on Num ports starting with port From to Value. The function returns True if the call was successfull, False otherwise. Remark:
Errors:
Errors are returned in LinuxError
See also:
ioperm (2)

IsATTY

Declaration:
Function IsATTY (var f) : Boolean;
Description:
Check if the filehandle described by f is a terminal. f can be of type
  1. longint for file handles;
  2. Text for text variables such as input etc.

Returns True if f is a terminal, False otherwise.

Errors:
No errors are reported
See also:
IOCtl (403),TTYName (437)

S__ISBLK

Declaration:
Function S_ISBLK (m:integer) : boolean;
Description:
S_ISBLK checks the file mode m to see whether the file is a block device file. If so it returns True.
Errors:
FStat (387), S__ISLNK (405), S__ISREG (406), S__ISDIR (405), S__ISCHR (404), S__ISFIFO (405), S__ISSOCK (407)
See also:
ISLNK.

S__ISCHR

Declaration:
Function S_ISCHR (m:integer) : boolean;
Description:
S_ISCHR checks the file mode m to see whether the file is a character device file. If so it returns True.
Errors:
FStat (387), S__ISLNK (405), S__ISREG (406), S__ISDIR (405), S__ISBLK (404), S__ISFIFO (405), S__ISSOCK (407)
See also:
ISLNK.

S__ISDIR

Declaration:
Function S_ISDIR (m:integer) : boolean;
Description:
S_ISDIR checks the file mode m to see whether the file is a directory. If so it returns True
Errors:
FStat (387), S__ISLNK (405), S__ISREG (406), S__ISCHR (404), S__ISBLK (404), S__ISFIFO (405), S__ISSOCK (407)
See also:
ISLNK.

S__ISFIFO

Declaration:
Function S_ISFIFO (m:integer) : boolean;
Description:
S_ISFIFO checks the file mode m to see whether the file is a fifo (a named pipe). If so it returns True.
Errors:
FStat (387), S__ISLNK (405), S__ISREG (406), S__ISDIR (405), S__ISCHR (404), S__ISBLK (404), S__ISSOCK (407)
See also:
ISLNK.

S__ISLNK

Declaration:
Function S_ISLNK (m:integer) : boolean;
Description:
S_ISLNK checks the file mode m to see whether the file is a symbolic link. If so it returns True
Errors:
FStat (387), S__ISREG (406), S__ISDIR (405), S__ISCHR (404), S__ISBLK (404), S__ISFIFO (405), S__ISSOCK (407)
See also:

Listing: linuxex/ex53.pp


Program Example53;

{ Program to demonstrate the S_ISLNK function. }

Uses linux;

Var Info : Stat;

begin
  if LStat (paramstr(1),info) then
    begin
    if S_ISLNK(info.mode) then
      Writeln ('File is a link');
    if S_ISREG(info.mode) then
      Writeln ('File is a regular file');
    if S_ISDIR(info.mode) then
      Writeln ('File is a directory');
    if S_ISCHR(info.mode) then
      Writeln ('File is a character device file');
    if S_ISBLK(info.mode) then
      Writeln ('File is a block device file');
    if S_ISFIFO(info.mode) then
      Writeln ('File is a named pipe (FIFO)');
    if S_ISSOCK(info.mode) then
      Writeln ('File is a socket');
    end;
end.

S__ISREG

Declaration:
Function S_ISREG (m:integer) : boolean;
Description:
S_ISREG checks the file mode m to see whether the file is a regular file. If so it returns True
Errors:
FStat (387), S__ISLNK (405), S__ISDIR (405), S__ISCHR (404), S__ISBLK (404), S__ISFIFO (405), S__ISSOCK (407)
See also:
ISLNK.

S__ISSOCK

Declaration:
Function S_ISSOCK (m:integer) : boolean;
Description:
S_ISSOCK checks the file mode m to see whether the file is a socket. If so it returns True.
Errors:
FStat (387), S__ISLNK (405), S__ISREG (406), S__ISDIR (405), S__ISCHR (404), S__ISBLK (404), S__ISFIFO (405)
See also:
ISLNK.

Kill

Declaration:
Function Kill (Pid : Longint; Sig : Integer) : Integer;
Description:
Send a signal Sig to a process or process group. If Pid¿0 then the signal is sent to Pid, if it equals -1, then the signal is sent to all processes except process 1. If Pid¡-1 then the signal is sent to process group -Pid. The return value is zero, except in case three, where the return value is the number of processes to which the signal was sent.
Errors:
LinuxError is used to report errors:
sys__einval
An invalid signal is sent.
sys__esrch
The Pid or process group don’t exist.
sys__eperm
The effective userid of the current process doesn’t math the one of process Pid.
See also:
SigAction (425), Signal (429), Kill (2)

LStat

Declaration:
Function LStat (Path : Pathstr; Var Info : stat) : Boolean;
Description:
LStat gets information about the link specified in Path, and stores it in Info, which is of type stat. Contrary to FStat, it stores information about the link, not about the file the link points to. The function returns True if the call was succesfull, False if the call failed.
Errors:
LinuxError is used to report errors.
sys__enoent
Path does not exist.
See also:
FStat (387), FSStat (386), stat (2)

Listing: linuxex/ex29.pp


program example29;

{ Program to demonstrate the LStat function. }

uses linux;

var f : text;
    i : byte;
    info : stat;

begin
  { Make a file }
  assign (f,'test.fil');
  rewrite (f);
  for i:=1 to 10 do writeln (f,'Testline # ',i);
  close (f);
  { Do the call on made file. }
  if not fstat ('test.fil',info) then
     begin
     writeln('Fstat failed. Errno : ',linuxerror);
     halt (1);
     end;
  writeln;
  writeln ('Result of fstat on file ''test.fil''.');
  writeln ('Inode   : ',info.ino);
  writeln ('Mode    : ',info.mode);
  writeln ('nlink   : ',info.nlink);
  writeln ('uid     : ',info.uid);
  writeln ('gid     : ',info.gid);
  writeln ('rdev    : ',info.rdev);
  writeln ('Size    : ',info.size);
  writeln ('Blksize : ',info.blksze);
  writeln ('Blocks  : ',info.blocks);
  writeln ('atime   : ',info.atime);
  writeln ('mtime   : ',info.mtime);
  writeln ('ctime   : ',info.ctime);

  If not SymLink ('test.fil','test.lnk') then
    writeln ('Link failed ! Errno :',linuxerror);

  if not lstat ('test.lnk',info) then
     begin
     writeln('LStat failed. Errno : ',linuxerror);
     halt (1);
     end;
  writeln;
  writeln ('Result of fstat on file ''test.lnk''.');
  writeln ('Inode   : ',info.ino);
  writeln ('Mode    : ',info.mode);
  writeln ('nlink   : ',info.nlink);
  writeln ('uid     : ',info.uid);
  writeln ('gid     : ',info.gid);
  writeln ('rdev    : ',info.rdev);
  writeln ('Size    : ',info.size);
  writeln ('Blksize : ',info.blksze);
  writeln ('Blocks  : ',info.blocks);
  writeln ('atime   : ',info.atime);
  writeln ('mtime   : ',info.mtime);
  writeln ('ctime   : ',info.ctime);
  { Remove file and link }
  erase (f);
  unlink ('test.lnk');
end.

Link

Declaration:
Function Link (OldPath,NewPath : pathstr) : Boolean;
Description:
Link makes NewPath point to the same file als OldPath. The two files then have the same inode number. This is known as a ’hard’ link. The function returns True if the call was succesfull, False if the call failed.
Errors:
Errors are returned in LinuxError.
sys__exdev
OldPath and NewPath are not on the same filesystem.
sys__eperm
The filesystem containing oldpath and newpath doesn’t support linking files.
sys__eaccess
Write access for the directory containing Newpath is disallowed, or one of the directories in OldPath or NewPath has no search (=execute) permission.
sys__enoent
A directory entry in OldPath or NewPath does not exist or is a symbolic link pointing to a non-existent directory.
sys__enotdir
A directory entry in OldPath or NewPath is nor a directory.
sys__enomem
Insufficient kernel memory.
sys__erofs
The files are on a read-only filesystem.
sys__eexist
NewPath already exists.
sys__emlink
OldPath has reached maximal link count.
sys__eloop
OldPath or NewPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself.
sys__enospc
The device containing NewPath has no room for anothe entry.
sys__eperm
OldPath points to . or .. of a directory.
See also:
SymLink (431), UnLink (439), Link (2)

Listing: linuxex/ex21.pp


:pserver:mazen@cvs.freepascal.org:/FPC/CVS

LocalToEpoch

Declaration:
Function LocalToEpoch (Year,Month,Day,Hour,Minute,Second : Word) : longint;
Description:
Converts the Local time to epoch time (=Number of seconds since 00:00:00 , January 1, 1970 ).
Errors:
None
See also:
GetEpochTime (395), EpochToLocal (370), GetTime (399),GetDate (391)

Listing: linuxex/ex4.pp


Program Example4;

{ Program to demonstrate the LocalToEpoch function. }

Uses linux;

Var year,month,day,hour,minute,second : Word;

begin
  Write ('Year    : ');readln(Year);
  Write ('Month   : ');readln(Month);
  Write ('Day     : ');readln(Day);
  Write ('Hour    : ');readln(Hour);
  Write ('Minute  : ');readln(Minute);
  Write ('Seonds  : ');readln(Second);
  Write ('This is : ');
  Write (LocalToEpoch(year,month,day,hour,minute,second));
  Writeln (' seconds past 00:00 1/1/1980');
end.

MkFifo

Declaration:
Function MkFifo (PathName: String; Mode : Longint) : Boolean;
Description:
MkFifo creates named a named pipe in the filesystem, with name PathName and mode Mode.
Errors:
LinuxError is used to report errors:
sys__emfile
Too many file descriptors for this process.
sys__enfile
The system file table is full.
See also:
POpen (417), MkFifo (411), mkfifo (4)

MMap

Declaration:
Function MMap(const m:tmmapargs):longint;
Description:
MMap maps or unmaps files or devices into memory. The different fields of the argument m determine what and how the mmap maps this:
address
Address where to mmap the device. This address is a hint, and may not be followed.
size
Size (in bytes) of area to be mapped.
prot
Protection of mapped memory. This is a OR-ed combination of the following constants:
PROT__EXEC
The memory can be executed.
PROT__READ
The memory can be read.
PROT__WRITE
The memory can be written.
PROT__NONE
The memory can not be accessed.
flags
Contains some options for the mmap call. It is an OR-ed combination of the following constants:
MAP__FIXED
Do not map at another address than the given address. If the address cannot be used, MMap will fail.
MAP__SHARED
Share this map with other processes that map this object.
MAP__PRIVATE
Create a private map with copy-on-write semantics.
MAP__ANONYMOUS
fd does not have to be a file descriptor.

One of the options MAP_SHARED and MAP_PRIVATE must be present, but not both at the same time.

fd
File descriptor from which to map.
offset
Offset to be used in file descriptor fd.

The function returns a pointer to the mapped memory, or a -1 in case of en error.

Errors:
On error, -1 is returned and LinuxError is set to the error code:
Sys__EBADF
fd is not a valid file descriptor and MAP_ANONYMOUS was not specified.
Sys__EACCES
MAP_PRIVATE was specified, but fd is not open for reading. Or MAP_SHARED was asked and PROT_WRITE is set, fd is not open for writing
Sys__EINVAL
One of the record fields Start, length or offset is invalid.
Sys__ETXTBUSY
MAP_DENYWRITE was set but the object specified by fd is open for writing.
Sys__EAGAIN
fd is locked, or too much memory is locked.
Sys__ENOMEM
Not enough memory for this operation.
See also:
MUnMap (413), mmap (2)

Listing: linuxex/ex66.pp


Program Example66;

{ Program to demonstrate the MMap function. }

Uses linux;

Var S : String;
    fd,Len : Longint;
    args : tmmapargs;
    P : PChar;

begin
  S:='This is a string'#0;
  Len:=Length(S);
  fd:=fdOpen('testfile.txt',Open_wrOnly or open_creat);
  If fd=-1 then
    Halt(1);
  If fdWrite(fd,S[1],Len)=-1 then
    Halt(2);
  fdClose(fd);
  fdOpen('testfile.txt',Open_rdOnly);
  if fd=-1 then
    Halt(3);
  args.address:=0;
  args.offset:=0;
  args.size:=Len+1;
  args.fd:=Fd;
  args.flags:=MAP_PRIVATE;
  args.prot:=PROT_READ or PROT_WRITE;
  P:=Pchar(mmap(args));
  If longint(P)=-1 then
    Halt(4);
  Writeln('Read in memory  :',P);
  fdclose(fd);
  if Not MUnMap(P,Len) Then
    Halt(LinuxError);
end.

MUnMap

Declaration:
function MUnMap (P : Pointer; Size : Longint) : Boolean;
Description:
MUnMap unmaps the memory block of size Size, pointed to by P, which was previously allocated with MMap (411).

The function returns True if successful, False otherwise.

Errors:
In case of error the function returns False and LinuxError is set to an error value. See MMap (411) for possible error values.
See also:
MMap (411), munmap (2)

For an example, see MMap (411).

NanoSleep

Declaration:
Function NanoSleep(const req : timespec;var rem : timespec) : longint;
Description:
NanoSleep suspends the process till a time period as specified in req has passed. Then the function returns. If the call was interrupted (e.g. by some signal) then the function may return earlier, and rem will contain the remaining time till the end of the intended period. In this case the return value will be -1, and LinuxError will be set to EINTR

If the function returns without error, the return value is zero.

Errors:
If the call was interrupted, -1 is returned, and LinuxError is set to EINTR. If invalid time values were specified, then -1 is returned and LinuxError is set to EINVAL.
See also:
Pause (??), Alarm (356)

Listing: linuxex/ex70.pp


Program Example70;

{ Program to demonstrate the StringToPPchar function. }

Uses linux;

Var S : String;
    P : PPChar;
    I : longint;

begin
  // remark whitespace at end.
  S:='This is a string with words. ';
  P:=StringToPPChar(S);
  I:=0;
  While P[i]<>Nil do
    begin
    Writeln('Word ',i,' : ',P[i]);
    Inc(I);
    end;
  FreeMem(P,i*SizeOf(Pchar));
end.

Nice

Declaration:
Procedure Nice ( N : Integer);
Description:
Nice adds -N to the priority of the running process. The lower the priority numerically, the less the process is favored. Only the superuser can specify a negative N, i.e. increase the rate at which the process is run.
Errors:
Errors are returned in LinuxError
sys__eperm
A non-superuser tried to specify a negative N, i.e. do a priority increase.
See also:
GetPriority (398), SetPriority (424), Nice (2)

Listing: linuxex/ex15.pp


Program Example15;

{ Program to demonstrate the Nice and Get/SetPriority functions. }

Uses linux;

begin
  writeln ('Setting priority to 5');
  setpriority (prio_process,getpid,5);
  writeln ('New priority = ',getpriority (prio_process,getpid));
  writeln ('Doing nice 10');
  nice (10);
  writeln ('New Priority = ',getpriority (prio_process,getpid));
end.

Octal

Declaration:
Function Octal(l:longint):longint;
Description:
Octal will convert a number specified as an octal number to it’s decimal value.

This is useful for the Chmod (362) call, where permissions are specified as octal numbers.

Errors:
No checking is performed whether the given number is a correct Octal number. e.g. specifying 998 is possible; the result will be wrong in that case.
See also:
Chmod (362).

Listing: linuxex/ex68.pp


Program Example68;

{ Program to demonstrate the Octal function. }

Uses linux;

begin
  Writeln('Mode 777 : ', Octal(777));
  Writeln('Mode 644 : ', Octal(644));
  Writeln('Mode 755 : ', Octal(755));
end.

OpenDir

Declaration:
Function OpenDir (f:pchar) : pdir; Function OpenDir (f:string) : pdir;
Description:
OpenDir opens the directory f, and returns a pdir pointer to a Dir record, which can be used to read the directory structure. If the directory cannot be opened, nil is returned.
Errors:
Errors are returned in LinuxError.
See also:
CloseDir (366), ReadDir (419), SeekDir (422), TellDir (438), opendir (3)

Listing: linuxex/ex35.pp


Program Example35;

{ Program to demonstrate the
  OpenDir,ReadDir, SeekDir and TellDir functions. }

Uses linux;

Var TheDir : PDir;
    ADirent : PDirent;
    Entry : Longint;

begin
  TheDir:=OpenDir('./.');
  Repeat
    Entry:=TellDir(TheDir);
    ADirent:=ReadDir (TheDir);
    If ADirent<>Nil then
      With ADirent^ do
        begin
        Writeln ('Entry No : ',Entry);
        Writeln ('Inode    : ',ino);
        Writeln ('Offset   : ',off);
        Writeln ('Reclen   : ',reclen);
        Writeln ('Name     : ',pchar(@name[0]));
        end;
  Until ADirent=Nil;
  Repeat
    Write ('Entry No. you would like to see again (-1 to stop): ');
    ReadLn (Entry);
    If Entry<>-1 then
      begin
      SeekDir (TheDir,Entry);
      ADirent:=ReadDir (TheDir);
      If ADirent<>Nil then
        With ADirent^ do
          begin
          Writeln ('Entry No : ',Entry);
          Writeln ('Inode    : ',ino);
          Writeln ('Offset   : ',off);
          Writeln ('Reclen   : ',reclen);
          Writeln ('Name     : ',pchar(@name[0]));
          end;
    end;
  Until Entry=-1;
  CloseDir (TheDir);
end.

pause

Declaration:
Procedure Pause;
Description:
Pause puts the process to sleep and waits until the application receives a signal. If a signal handler is installed for the received sigal, the handler will be called and after that pause will return control to the process.
Errors:
None.

For an example, see Alarm (356).

PClose

Declaration:
Function PClose (Var F : FileType) : longint;
Description:
PClose closes a file opened with POpen. It waits for the command to complete, and then returns the exit status of the command.
Errors:
LinuxError is used to report errors. If it is different from zero, the exit status is not valid.
See also:
POpen (417)

For an example, see POpen (417)

POpen

Declaration:
Procedure POpen (Var F : FileType; Cmd : pathstr; rw : char);
Description:
Popen runs the command specified in Cmd, and redirects the standard in or output of the command to the other end of the pipe F. The parameter rw indicates the direction of the pipe. If it is set to 'W', then F can be used to write data, which will then be read by the command from stdinput. If it is set to 'R', then the standard output of the command can be read from F. F should be reset or rewritten prior to using it. F can be of type Text or File. A file opened with POpen can be closed with Close, but also with PClose (417). The result is the same, but PClose returns the exit status of the command Cmd.
Errors:
Errors are reported in LinuxError and are essentially those of the Execve, Dup and AssignPipe commands.
See also:
AssignPipe (357), popen (3) , PClose (417)

Listing: linuxex/ex37.pp


Program Example37;

{ Program to demonstrate the Popen function. }

uses linux;

var f : text;
    i : longint;

begin
  writeln ('Creating a shell script to which echoes its arguments');
  writeln ('and input back to stdout');
  assign (f,'test21a');
  rewrite (f);
  writeln (f,'#!/bin/sh');
  writeln (f,'echo this is the child speaking.... ');
  writeln (f,'echo got arguments \*"$*"\*');
  writeln (f,'cat');
  writeln (f,'exit 2');
  writeln (f);
  close (f);
  chmod ('test21a',octal (755));
  popen (f,'./test21a arg1 arg2','W');
  if linuxerror<>0 then
     writeln ('error from POpen : Linuxerror : ', Linuxerror);
  for i:=1 to 10 do
    writeln (f,'This is written to the pipe, and should appear on stdout.');
  Flush(f);
  Writeln ('The script exited with status : ',PClose (f));
  writeln;
  writeln ('Press <return> to remove shell script.');
  readln;
  assign (f,'test21a');
  erase (f)
end.

ReadDir

Declaration:
Function ReadDir (p:pdir) : pdirent;
Description:
ReadDir reads the next entry in the directory pointed to by p. It returns a pdirent pointer to a structure describing the entry. If the next entry can’t be read, Nil is returned.
Errors:
Errors are returned in LinuxError.
See also:
CloseDir (366), OpenDir (416), SeekDir (422), TellDir (438), readdir (3)

For an example, see OpenDir (416).

ReadLink

Declaration:
Function ReadLink(name,linkname:pchar;maxlen:longint):longint; Function ReadLink(name:pathstr):pathstr;
Description:
ReadLink returns the file the symbolic link name is pointing to. The first form of this function accepts a buffer linkname of length maxlen where the filename will be stored. It returns the actual number of characters stored in the buffer.

The second form of the function returns simply the name of the file.

Errors:
On error, the first form of the function returns -1; the second one returns an empty string. LinuxError is set to report errors:
SYS__ENOTDIR
A part of the path in Name is not a directory.
SYS__EINVAL
maxlen is not positive, or the file is not a symbolic link.
SYS__ENAMETOOLONG
A pathname, or a component of a pathname, was too long.
SYS__ENOENT
the link name does not exist.
SYS__EACCES
No permission to search a directory in the path
SYS__ELOOP
Too many symbolic links were encountered in trans lating the pathname.
SYS__EIO
An I/O error occurred while reading from the file system.
SYS__EFAULT
The buffer is not part of the the process’s memory space.
SYS__ENOMEM
Not enough kernel memory was available.
See also:
SymLink (431)

Listing: linuxex/ex62.pp


Program Example62;

{ Program to demonstrate the ReadLink function. }

Uses linux;

Var F : Text;
    S : String;

begin
  Assign (F,'test.txt');
  Rewrite (F);
  Writeln (F,'This is written to test.txt');
  Close(f);
  { new.txt and test.txt are now the same file }
  if not SymLink ('test.txt','new.txt') then
    writeln ('Error when symlinking !');
  S:=ReadLink('new.txt');
  If S='' then
    Writeln ('Error reading link !')
  Else
    Writeln ('Link points to : ',S);
 { Now remove links }
 If not Unlink ('new.txt') then
   Writeln ('Error when unlinking !');
 If not Unlink ('test.txt') then
   Writeln ('Error when unlinking !');
end.

ReadPort

Declaration:
Procedure ReadPort (Port : Longint; Var Value : Byte); Procedure ReadPort (Port : Longint; Var Value : Word); Procedure ReadPort (Port : Longint; Var Value : Longint);
Description:
ReadPort reads one Byte, Word or Longint from port Port into Value.

Note that you need permission to read a port. This permission can be set by the root user with the IOperm (403) call.

Errors:
In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur.
See also:

IOperm (403), ReadPortB (421), ReadPortW (421), ReadPortL (421),WritePort (441), WritePortB (442), WritePortL (442), WritePortW (443)

ReadPortB

Declaration:
Procedure ReadPortB (Port : Longint; Var Buf; Count: longint); Function ReadPortB (Port : Longint): Byte;
Description:
The procedural form of ReadPortB reads Count bytes from port Port and stores them in Buf. There must be enough memory allocated at Buf to store Count bytes.

The functional form of ReadPortB reads 1 byte from port B and returns the byte that was read.

Note that you need permission to read a port. This permission can be set by the root user with the IOperm (403) call.

Errors:
In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur.
See also:
IOperm (403), ReadPort (420), ReadPortW (421), ReadPortL (421),WritePort (441), WritePortB (442), WritePortL (442), WritePortW (443)

ReadPortL

Declaration:
function ReadPortL (Port : Longint): LongInt; Procedure ReadPortL (Port : Longint; Var Buf; Count: longint);
Description:
The procedural form of ReadPortL reads Count longints from port Port and stores them in Buf. There must be enough memory allocated at Buf to store Count Longints.

The functional form of ReadPortB reads 1 longint from port B and returns the longint that was read.

Note that you need permission to read a port. This permission can be set by the root user with the IOperm (403) call.

Errors:
In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur.
See also:
IOperm (403), ReadPort (420), ReadPortW (421), ReadPortB (421),WritePort (441), WritePortB (442), WritePortL (442), WritePortW (443)

ReadPortW

Declaration:
Procedure ReadPortW (Port : Longint; Var Buf; Count: longint); function ReadPortW (Port : Longint): Word;
Description:
The procedural form of ReadPortB reads Count words from port Port and stores them in Buf. There must be enough memory allocated at Buf to store Count words.

The functional form of ReadPortB reads 1 word from port B and returns the word that was read.

Note that you need permission to read a port. This permission can be set by the root user with the IOperm (403) call.

Errors:
In case of an error (not enough permissions read this port), runtime 216 (Access Violation) will occur.
See also:
IOperm (403), ReadPort (420), ReadPortB (421), ReadPortL (421),WritePort (441), WritePortB (442), WritePortL (442), WritePortW (443)

ReadTimezoneFile

Declaration:
procedure ReadTimezoneFile(fn:string);
Description:
ReadTimeZoneFile reads the timezone file fn and initializes the local time routines based on the information found there.

There should be no need to call this function. The initialization routines of the linux unit call this routine at unit startup.

Errors:
None.
See also:
GetTimezoneFile (400), GetLocalTimezone (397)

SeekDir

Declaration:
Procedure SeekDir (p:pdir;off:longint);
Description:
SeekDir sets the directory pointer to the off-th entry in the directory structure pointed to by p.
Errors:
Errors are returned in LinuxError.
See also:
CloseDir (366), ReadDir (419), OpenDir (416), TellDir (438), seekdir (3)

For an example, see OpenDir (416).

Select

Declaration:
Function Select (N : Longint;
var readfds,writefds,exceptfds : PFDset; Var Timeout) : Longint;
Description:
Select checks one of the file descriptors in the FDSets to see if its status changed. readfds, writefds and exceptfds are pointers to arrays of 256 bits. If you want a file descriptor to be checked, you set the corresponding element in the array to 1. The other elements in the array must be set to zero. Three arrays are passed : The entries in readfds are checked to see if characters become available for reading. The entries in writefds are checked to see if it is OK to write to them, while entries in exceptfds are cheked to see if an exception occorred on them. You can use the functions FD__ZERO (377), FD__Clr (377), FD__Set (378), FD__IsSet (378) to manipulate the individual elements of a set. The pointers can be nil. N is the largest index of a nonzero entry plus 1. (= the largest file-descriptor + 1). TimeOut can be used to set a time limit. If TimeOut can be two types :
  1. TimeOut is of type PTime and contains a zero time, the call returns immediately. If TimeOut is Nil, the kernel will wait forever, or until a status changed.
  2. TimeOut is of type Longint. If it is -1, this has the same effect as a Timeout of type PTime which is Nil. Otherwise, TimeOut contains a time in milliseconds.

When the TimeOut is reached, or one of the file descriptors has changed, the Select call returns. On return, it will have modified the entries in the array which have actually changed, and it returns the number of entries that have been changed. If the timout was reached, and no decsriptor changed, zero is returned; The arrays of indexes are undefined after that. On error, -1 is returned.

Errors:
On error, the function returns -1, and Errors are reported in LinuxError :
SYS__EBADF 
An invalid descriptot was specified in one of the sets.
SYS__EINTR 
A non blocked signal was caught.
SYS__EINVAL 
N is negative or too big.
SYS__ENOMEM 
Select was unable to allocate memory for its internal tables.
See also:
SelectText (424), GetFS (395), FD__ZERO (377), FD__Clr (377), FD__Set (378), FD__IsSet (378)

Listing: linuxex/ex33.pp


Program Example33;

{ Program to demonstrate the Select function. }

Uses linux;

Var FDS : FDSet;

begin
  FD_Zero (FDS);
  FD_Set (0,FDS);
  Writeln ('Press the <ENTER> to continue the program.');
  { Wait until File descriptor 0 (=Input) changes }
  Select (1,@FDS,nil,nil,nil);
  { Get rid of <ENTER> in buffer }
  readln;
  Writeln ('Press <ENTER> key in less than 2 seconds...');
  FD_Zero (FDS);
  FD_Set (0,FDS);
  if Select (1,@FDS,nil,nil,2000)>0 then
    Writeln ('Thank you !')
    { FD_ISSET(0,FDS) would be true here. }
  else
    Writeln ('Too late !');
end.

SelectText

Declaration:
Function SelectText ( var T : Text; TimeOut :PTime) : Longint;
Description:
SelectText executes the Select (423) call on a file of type Text. You can specify a timeout in TimeOut. The SelectText call determines itself whether it should check for read or write, depending on how the file was opened : With Reset it is checked for reading, with Rewrite and Append it is checked for writing.
Errors:
See Select (423). SYS_EBADF can also mean that the file wasn’t opened.
See also:
Select (423), GetFS (395)

SetPriority

Declaration:
Function SetPriority (Which,Who,Prio : Integer) : Integer;
Description:
SetPriority sets the priority with which a process is running. Which process(es) is determined by the Which and Who variables. Which can be one of the pre-defined Prio_Process, Prio_PGrp, Prio_User, in which case Who is the process ID, Process group ID or User ID, respectively. Prio is a value in the range -20 to 20.
Errors:

Error checking must be done on LinuxError, since a priority can be negative.

sys__esrch
No process found using which and who.
sys__einval
Which was not one of Prio_Process, Prio_Grp or Prio_User.
sys__eperm
A process was found, but neither its effective or real user ID match the effective user ID of the caller.
sys__eacces
A non-superuser tried to a priority increase.
See also:
GetPriority (398), Nice (414), Setpriority (2)

For an example, see Nice (414).

Shell

Declaration:
Function Shell (Command : String) : Longint;
Description:
Shell invokes the bash shell (/bin/sh), and feeds it the command Command (using the -c option). The function then waits for the command to complete, and then returns the exit status of the command, or 127 if it could not complete the Fork (390) or Execve (375) calls.
Errors:
Errors are reported in LinuxError.
See also:
POpen (417), Fork (390), Execve (375), system (3)

Listing: linuxex/ex56.pp


program example56;

uses linux;

{ Program to demonstrate the Shell function }

Var S : Longint;

begin
  Writeln ('Output of ls -l *.pp');
  S:=Shell ('ls -l *.pp');
  Writeln ('Command exited wwith status : ',S);
end.

SigAction

Declaration:
Procedure SigAction (Signum : Integer; Var Act,OldAct : PSigActionRec);
Description:
Changes the action to take upon receipt of a signal. Act and Oldact are pointers to a SigActionRec record. SigNum specifies the signal, and can be any signal except SIGKILL or SIGSTOP. If Act is non-nil, then the new action for signal SigNum is taken from it. If OldAct is non-nil, the old action is stored there. Sa_Handler may be SIG_DFL for the default action or SIG_IGN to ignore the signal. Sa_Mask Specifies which signals should be ignord during the execution of the signal handler. Sa_Flags Speciefies a series of flags which modify the behaviour of the signal handler. You can ’or’ none or more of the following :
SA__NOCLDSTOP
If signum is SIGCHLD do not receive notification when child processes stop.
SA__ONESHOT or SA__RESETHAND
Restore the signal action to the default state once the signal handler has been called.
SA__RESTART
For compatibility with BSD signals.
SA__NOMASK or SA__NODEFER
Do not prevent the signal from being received from within its own signal handler.
Errors:
LinuxError is used to report errors.
sys__einval
an invalid signal was specified, or it was SIGKILL or SIGSTOP.
sys__efault
Act,OldAct point outside this process address space
sys__eintr
System call was interrupted.
See also:

SigProcMask (427), SigPending (427), SigSuspend (429), Kill (407), Sigaction (2)

Listing: linuxex/ex57.pp


Program example57;

{ Program to demonstrate the SigAction function.}

{
do a kill -USR1 pid from another terminal to see what happens.
replace pid with the real pid of this program.
You can get this pid by running 'ps'.
}

uses Linux;

Var
   oa,na : PSigActionRec;

Procedure DoSig(sig : Longint);cdecl;

begin
   writeln('Receiving signal: ',sig);
end;

begin
   new(na);
   new(oa);
   na^.Handler.sh:=@DoSig;
   na^.Sa_Mask:=0;
   na^.Sa_Flags:=0;
   na^.Sa_Restorer:=Nil;
   SigAction(SigUsr1,na,oa);
   if LinuxError<>0 then
     begin
     writeln('Error: ',linuxerror,'.');
     halt(1);
     end;
   Writeln ('Send USR1 signal or press <ENTER> to exit');
   readln;
end.

SigPending

Declaration:
Function SigPending : SigSet;
Description:
Sigpending allows the examination of pending signals (which have been raised while blocked.) The signal mask of pending signals is returned.
Errors:
None
See also:
SigAction (425), SigProcMask (427), SigSuspend (429), Signal (429), Kill (407), Sigpending (2)

SigProcMask

Declaration:
Procedure SigProcMask (How : Integer; SSet,OldSSet : PSigSet);
Description:
Changes the list of currently blocked signals. The behaviour of the call depends on How :
SIG__BLOCK
The set of blocked signals is the union of the current set and the SSet argument.
SIG__UNBLOCK
The signals in SSet are removed from the set of currently blocked signals.
SIG__SETMASK
The list of blocked signals is set so SSet.

If OldSSet is non-nil, then the old set is stored in it.

Errors:
LinuxError is used to report errors.
sys__efault
SSet or OldSSet point to an adress outside the range of the process.
sys__eintr
System call was interrupted.
See also:
SigAction (425), SigPending (427), SigSuspend (429), Kill (407), Sigprocmask (2)

SigRaise

Declaration:
Procedure SigRaise(Sig:integer);
Description:
SigRaise sends a Sig signal to the current process.
Errors:
None.
See also:
Kill (407), GetPid (397)

Listing: linuxex/ex65.pp


Program example64;

{ Program to demonstrate the SigRaise function.}

uses Linux;

Var
   oa,na : PSigActionRec;

Procedure DoSig(sig : Longint);cdecl;

begin
   writeln('Receiving signal: ',sig);
end;

begin
   new(na);
   new(oa);
   na^.handler.sh:=@DoSig;
   na^.Sa_Mask:=0;
   na^.Sa_Flags:=0;
   na^.Sa_Restorer:=Nil;
   SigAction(SigUsr1,na,oa);
   if LinuxError<>0 then
     begin
     writeln('Error: ',linuxerror,'.');
     halt(1);
     end;
   Writeln('Sending USR1 (',sigusr1,') signal to self.');
   SigRaise(sigusr1);
end.

SigSuspend

Declaration:
Procedure SigSuspend (Mask : SigSet);
Description:
SigSuspend temporarily replaces the signal mask for the process with the one given in Mask, and then suspends the process until a signal is received.
Errors:
None
See also:
SigAction (425), SigProcMask (427), SigPending (427), Signal (429), Kill (407), SigSuspend (2)

Signal

Declaration:
Function Signal (SigNum : Integer; Handler : SignalHandler) : SignalHandler;
Description:
Signal installs a new signal handler for signal SigNum. This call has the same functionality as the SigAction call. The return value for Signal is the old signal handler, or nil on error.
Errors:
LinuxError is used to report errors :
SIG__ERR
An error occurred.
See also:
SigAction (425),Kill (407), Signal (2)

Listing: linuxex/ex58.pp


Program example58;

{ Program to demonstrate the Signal function.}

{
do a kill -USR1 pid from another terminal to see what happens.
replace pid with the real pid of this program.
You can get this pid by running 'ps'.
}

uses Linux;

Procedure DoSig(sig : Longint);cdecl;

begin
   writeln('Receiving signal: ',sig);
end;

begin
   SigNal(SigUsr1,@DoSig);
   if LinuxError<>0 then
     begin
     writeln('Error: ',linuxerror,'.');
     halt(1);
     end;
   Writeln ('Send USR1 signal or press <ENTER> to exit');
   readln;
end.

StringToPPchar

Declaration:
Function StringToPPChar(Var S:STring):ppchar;
Description:
StringToPPChar splits the string S in words, replacing any whitespace with zero characters. It returns a pointer to an array of pchars that point to the first letters of the words in S. This array is terminated by a Nil pointer.

The function does not add a zero character to the end of the string unless it ends on whitespace.

The function reserves memory on the heap to store the array of PChar; The caller is responsible for freeing this memory.

This function can be called to create arguments for the various Exec calls.

Errors:
None.
See also:
CreateShellArgV (366), Execve (375), Execv (374)

Listing: linuxex/ex70.pp


Program Example70;

{ Program to demonstrate the StringToPPchar function. }

Uses linux;

Var S : String;
    P : PPChar;
    I : longint;

begin
  // remark whitespace at end.
  S:='This is a string with words. ';
  P:=StringToPPChar(S);
  I:=0;
  While P[i]<>Nil do
    begin
    Writeln('Word ',i,' : ',P[i]);
    Inc(I);
    end;
  FreeMem(P,i*SizeOf(Pchar));
end.

SymLink

Declaration:
Function SymLink (OldPath,NewPath : pathstr) : Boolean;
Description:
SymLink makes Newpath point to the file in OldPath, which doesn’t necessarily exist. The two files DO NOT have the same inode number. This is known as a ’soft’ link. The permissions of the link are irrelevant, as they are not used when following the link. Ownership of the file is only checked in case of removal or renaming of the link. The function returns True if the call was succesfull, False if the call failed.
Errors:
Errors are returned in LinuxError.
sys__eperm
The filesystem containing oldpath and newpath doesn’t support linking files.
sys__eaccess
Write access for the directory containing Newpath is disallowed, or one of the directories in OldPath or NewPath has no search (=execute) permission.
sys__enoent
A directory entry in OldPath or NewPath does not exist or is a symbolic link pointing to a non-existent directory.
sys__enotdir
A directory entry in OldPath or NewPath is nor a directory.
sys__enomem
Insufficient kernel memory.
sys__erofs
The files are on a read-only filesystem.
sys__eexist
NewPath already exists.
sys__eloop
OldPath or NewPath has a reference to a circular symbolic link, i.e. a symbolic link, whose expansion points to itself.
sys__enospc
The device containing NewPath has no room for anothe entry.
See also:
Link (409), UnLink (439), ReadLink (419), Symlink (2)

Listing: linuxex/ex22.pp


Program Example22;

{ Program to demonstrate the SymLink and UnLink functions. }

Uses linux;

Var F : Text;
    S : String;

begin
  Assign (F,'test.txt');
  Rewrite (F);
  Writeln (F,'This is written to test.txt');
  Close(f);
  { new.txt and test.txt are now the same file }
  if not SymLink ('test.txt','new.txt') then
    writeln ('Error when symlinking !');
  { Removing test.txt still leaves new.txt
    Pointing now to a non-existent file ! }
  If not Unlink ('test.txt') then
    Writeln ('Error when unlinking !');
  Assign (f,'new.txt');
  { This should fail, since the symbolic link
    points to a non-existent file! }
  {$i-}
  Reset (F);
  {$i+}
  If IOResult=0 then
    Writeln ('This shouldn''t happen');
 { Now remove new.txt also }
 If not Unlink ('new.txt') then
   Writeln ('Error when unlinking !');
end.

SysInfo

Declaration:
Function SysInfo(var Info:TSysinfo):Boolean;
Description:
SysInfo returns system information in Info. Returned information in Info includes:
uptime
Number of seconds since boot.
loads
1, 5 and 15 minute load averages.
totalram
total amount of main memory.
freeram
amount of free memory.
sharedram
amount of shared memory
bufferram
amount of memory used by buffers.
totalswap
total amount of swapspace.
freeswap
amount of free swapspace.
procs
number of current processes.
Errors:
None.
See also:
Uname (439)

Listing: linuxex/ex64.pp


program Example64;

{ Example to demonstrate the SysInfo function }

Uses Linux;

Function Mb(L : Longint) : longint;

begin
  Mb:=L div (1024*1024);
end;

Var Info : TSysInfo;
    D,M,Secs,H : longint;

begin
  If Not SysInfo(Info) then
    Halt(1);
  With Info do
    begin
    D:=Uptime div (3600*24);
    UpTime:=UpTime mod (3600*24);
    h:=uptime div 3600;
    uptime:=uptime mod 3600;
    m:=uptime div 60;
    secs:=uptime mod 60;
    Writeln('Uptime : ',d,'days, ',h,' hours, ',m,' min, ',secs,' s.');
    Writeln('Loads  : ',Loads[1],'/',Loads[2],'/',Loads[3]);
    Writeln('Total Ram  : ',Mb(totalram),'Mb.');
    Writeln('Free Ram   : ',Mb(freeram),'Mb.');
    Writeln('Shared Ram : ',Mb(sharedram),'Mb.');
    Writeln('Buffer Ram : ',Mb(bufferram),'Mb.');
    Writeln('Total Swap : ',Mb(totalswap),'Mb.');
    Writeln('Free Swap  : ',Mb(freeswap),'Mb.');
    end;
end.

TCDrain

Declaration:
Function TCDrain (Fd:longint) : Boolean;
Description:
TCDrain waits until all data to file descriptor Fd is transmitted.

The function returns True if the call was succesfull, False otherwise.

Errors:
Errors are reported in LinuxError
See also:
termios (2)

TCFlow

Declaration:
Function TCFlow (Fd,Act:longint) : Boolean;
Description:
TCFlow suspends/resumes transmission or reception of data to or from the file descriptor Fd, depending on the action Act. This can be one of the following pre-defined values:
TCOOFF 
suspend reception/transmission,
TCOON 
resume reception/transmission,
TCIOFF 
transmit a stop character to stop input from the terminal,
TCION 
transmit start to resume input from the terminal.

The function returns True if the call was succesfull, False otherwise.

Errors:
Errors are reported in LinuxError.
See also:
termios (2)

TCFlush

Declaration:
Function TCFlush (Fd,QSel:longint) : Boolean;
Description:
TCFlush discards all data sent or received to/from file descriptor fd. QSel indicates which queue should be discard. It can be one of the following pre-defined values :
TCIFLUSH 
input,
TCOFLUSH 
output,
TCIOFLUSH 
both input and output.

The function returns True if the call was succesfull, False otherwise.

Errors:
Errors are reported in LinuxError.
See also:
termios (2)

TCGetAttr

Declaration:
Function TCGetAttr (fd:longint;var tios:TermIOS) : Boolean;
Description:
TCGetAttr gets the terminal parameters from the terminal referred to by the file descriptor fd and returns them in a TermIOS structure tios. The function returns True if the call was succesfull, False otherwise.
Errors:
Errors are reported in LinuxError
See also:
TCSetAttr (437), termios (2)

Listing: linuxex/ex55.pp


Program Example55;

uses Linux;

{ Program to demonstrate the TCGetAttr/TCSetAttr/CFMakeRaw functions. }

procedure ShowTermios(var tios:Termios);
begin
  WriteLn('Input Flags  : $',hexstr(tios.c_iflag,8)+#13);
  WriteLn('Output Flags : $',hexstr(tios.c_oflag,8));
  WriteLn('Line Flags   : $',hexstr(tios.c_lflag,8));
  WriteLn('Control Flags: $',hexstr(tios.c_cflag,8));
end;

var
  oldios,
  tios : Termios;
begin
  WriteLn('Old attributes:');
  TCGetAttr(1,tios);
  ShowTermios(tios);
  oldios:=tios;
  Writeln('Setting raw terminal mode');
  CFMakeRaw(tios);
  TCSetAttr(1,TCSANOW,tios);
  WriteLn('Current attributes:');
  TCGetAttr(1,tios);
  ShowTermios(tios);
  TCSetAttr(1,TCSANOW,oldios);
end.

TCGetPGrp

Declaration:
Function TCGetPGrp (Fd:longint;var Id:longint) : boolean;
Description:
TCGetPGrp returns the process group ID of a foreground process group in Id The function returns True if the call was succesfull, False otherwise
Errors:
Errors are reported in LinuxError
See also:
termios (2)

TCSendBreak

Declaration:
Function TCSendBreak (Fd,Duration:longint) : Boolean;
Description:
TCSendBreak Sends zero-valued bits on an asynchrone serial connection decsribed by file-descriptor Fd, for duration Duration. The function returns True if the action was performed successfully, False otherwise.
Errors:
Errors are reported in LinuxError.
See also:
termios (2)

TCSetAttr

Declaration:
Function TCSetAttr (Fd:longint;OptAct:longint;var Tios:TermIOS) : Boolean;
Description:
TCSetAttr Sets the terminal parameters you specify in a TermIOS structure Tios for the terminal referred to by the file descriptor Fd. OptAct specifies an optional action when the set need to be done, this could be one of the following pre-defined values:
TCSANOW 
set immediately.
TCSADRAIN 
wait for output.
TCSAFLUSH 
wait for output and discard all input not yet read.

The function Returns True if the call was succesfull, False otherwise.

Errors:
Errors are reported in LinuxError.
See also:
TCGetAttr (435), termios (2)

For an example, see TCGetAttr (435).

TCSetPGrp

Declaration:
Function TCSetPGrp (Fd,Id:longint) : boolean;
Description:
TCSetPGrp Sets the Process Group Id to Id. The function returns True if the call was successful, False otherwise.
Errors:
Errors are returned in LinuxError.
See also:
TCGetPGrp (436), termios (2)

For an example, see TCGetPGrp (436).

TTYName

Declaration:
Function TTYName (var f) : String;
Description:
Returns the name of the terminal pointed to by f. f must be a terminal. f can be of type:
  1. longint for file handles;
  2. Text for text variables such as input etc.
Errors:
Returns an empty string in case of an error. Linuxerror may be set to indicate what error occurred, but this is uncertain.
See also:
IsATTY (404),IOCtl (403)

TellDir

Declaration:
Function TellDir (p:pdir) : longint;
Description:
TellDir returns the current location in the directory structure pointed to by p. It returns -1 on failure.
Errors:
Errors are returned in LinuxError.
See also:
CloseDir (366), ReadDir (419), SeekDir (422), OpenDir (416), telldir (3)

For an example, see OpenDir (416).

Umask

Declaration:
Function Umask (Mask : Integer) : Integer;
Description:
Change the file creation mask for the current user to Mask. The current mask is returned.
Errors:
None
See also:
Chmod (362), Umask (2)

Listing: linuxex/ex27.pp


Program Example27;

{ Program to demonstrate the Umask function. }

Uses linux;

begin
  Writeln ('Old Umask was : ',Umask(Octal(111)));
  WRiteln ('New Umask is  : ',Octal(111));
end.

Uname

Declaration:
Procedure Uname (var unamerec:utsname);
Description:
Uname gets the name and configuration of the current LINUX kernel, and returns it in unamerec.
Errors:
LinuxError is used to report errors.
See also:
GetHostName (397), GetDomainName (392), uname (2)

UnLink

Declaration:
Function UnLink (Var Path) : Boolean;
Description:
UnLink decreases the link count on file Path. Path can be of type PathStr or PChar. If the link count is zero, the file is removed from the disk. The function returns True if the call was succesfull, False if the call failed.
Errors:
Errors are returned in LinuxError.
sys__eaccess
You have no write access right in the directory containing Path, or you have no search permission in one of the directory components of Path.
sys__eperm
The directory containing pathname has the sticky-bit set and the process’s effective uid is neither the uid of the file to be deleted nor that of the directory containing it.
sys__enoent
A component of the path doesn’t exist.
sys__enotdir
A directory component of the path is not a directory.
sys__eisdir
Path refers to a directory.
sys__enomem
Insufficient kernel memory.
sys__erofs
Path is on a read-only filesystem.
See also:
Link (409), SymLink (431), Unlink (2)

For an example, see Link (409).

Utime

Declaration:
Function Utime (path : pathstr; utim : utimbuf) : Boolean;
Description:
Utime sets the access and modification times of a file. the utimbuf record contains 2 fields, actime, and modtime, both of type Longint. They should be filled with an epoch-like time, specifying, respectively, the last access time, and the last modification time. For some filesystem (most notably, FAT), these times are the same.
Errors:
Errors are returned in LinuxError.
sys__eaccess
One of the directories in Path has no search (=execute) permission.
sys__enoent
A directory entry in Path does not exist or is a symbolic link pointing to a non-existent directory.

Other errors may occur, but aren’t documented.

See also:
GetEpochTime (395), Chown (361), Access (355), utime (() 2)

Listing: linuxex/ex25.pp


Program Example25;

{ Program to demonstrate the UTime function. }

Uses linux;

Var utim : utimbuf;
    year,month,day,hour,minute,second : Word;

begin
  { Set access and modification time of executable source }
  GetTime (hour,minute,second);
  GetDate (year,month,day);
  utim.actime:=LocalToEpoch(year,month,day,hour,minute,second);
  utim.modtime:=utim.actime;
  if not Utime('ex25.pp',utim) then
    writeln ('Call to UTime failed !')
  else
    begin
    Write ('Set access and modification times to : ');
    Write (Hour:2,':',minute:2,':',second,', ');
    Writeln (Day:2,'/',month:2,'/',year:4);
    end;
end.

WaitPid

Declaration:
Function WaitPid (Pid : longint; Status : pointer; Options : Longint) : Longint;
Description:
WaitPid waits for a child process with process ID Pid to exit. The value of Pid can be one of the following:
Pid ¡ -1
Causes WaitPid to wait for any child process whose process group ID equals the absolute value of pid.
Pid = -1
Causes WaitPid to wait for any child process.
Pid = 0
Causes WaitPid to wait for any child process whose process group ID equals the one of the calling process.
Pid ¿ 0
Causes WaitPid to wait for the child whose process ID equals the value of Pid.

The Options parameter can be used to specify further how WaitPid behaves:

WNOHANG
Causes Waitpid to return immediately if no child has exited.
WUNTRACED
Causes WaitPid to return also for children which are stopped, but whose status has not yet been reported.
__WCLONE
Causes WaitPid also to wait for threads created by the Clone (364) call.

Upon return, it returns the exit status of the process, or -1 in case of failure.

Errors:
Errors are returned in LinuxError.
See also:
Fork (390), Execve (375), waitpid (2)

For an example, see Fork (390).

WritePort

Declaration:
Procedure WritePort (Port : Longint; Value : Byte); Procedure WritePort (Port : Longint; Value : Word); Procedure WritePort (Port : Longint; Value : Longint);
Description:
WritePort writes Value - 1 byte, Word or longint - to port Port.

Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call.

Errors:
In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur.
See also:
IOperm (403), WritePortB (442), WritePortL (442), WritePortW (443), ReadPortB (421), ReadPortL (421), ReadPortW (421)

WritePortB

Declaration:
Procedure WritePortB (Port : Longint; Value : Byte); Procedure WritePortB (Port : Longint; Var Buf; Count: longint);
Description:
The first form of WritePortB writes 1 byte to port Port. The second form writes Count bytes from Buf to port Port.

Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call.

Errors:
In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur.
See also:
IOperm (403), WritePort (441), WritePortL (442), WritePortW (443), ReadPortB (421), ReadPortL (421), ReadPortW (421)

WritePortL

Declaration:
Procedure WritePortL (Port : Longint; Value : Longint); Procedure WritePortL (Port : Longint; Var Buf; Count: longint);
Description:
The first form of WritePortB writes 1 byte to port Port. The second form writes Count bytes from Buf to port Port.

Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call.

Errors:
In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur.
See also:
IOperm (403), WritePort (441), WritePortB (442), WritePortW (443), ReadPortB (421), ReadPortL (421), ReadPortW (421)

WritePortW

Declaration:
Procedure WritePortW (Port : Longint; Var Buf; Count: longint); Procedure WritePortW (Port : Longint; Value : Word);
Description:
The first form of WritePortB writes 1 byte to port Port. The second form writes Count bytes from Buf to port Port.

Note: You need permission to write to a port. This permission can be set with root permission with the IOperm call.

Errors:
In case of an error (not enough permissions to write to this port), runtime 216 (Access Violation) will occur.
See also:
IOperm (403), WritePort (441), WritePortL (442), WritePortB (442), ReadPortB (421), ReadPortL (421), ReadPortW (421)