Subsections

- 1 Type, Variable and Constant declarations
  - 1 Types
  - 2 Variables
  - 3 Constants
- 2 Function list by category
  - 1 File Input/Output routines
  - 2 General File handling routines
  - 3 Pipes, FIFOs and streams
  - 4 Directory handling routines
  - 5 Process handling
  - 6 Signals
  - 7 System information
  - 8 Terminal functions
  - 9 Port input/output
  - 10 Utility routines
- 3 Functions and procedures
  - 1 Access
  - 2 Alarm
  - 3 AssignPipe
  - 4 AssignStream
  - 5 BaseName
  - 6 CFMakeRaw
  - 7 CFSetISpeed
  - 8 CFSetOSpeed
  - 9 Chown
  - 10 Chmod
  - 11 Clone
  - 12 CloseDir
  - 13 CreateShellArgV
  - 14 DirName
  - 15 Dup
  - 16 Dup2
  - 17 EpochToLocal
  - 18 Execl
  - 19 Execle
  - 20 Execlp
  - 21 Execv
  - 22 Execve
  - 23 Execvp
  - 24 FD_ZERO
  - 25 FD_Clr
  - 26 FD_IsSet
  - 27 FD_Set
  - 28 fdClose
  - 29 fdFlush
  - 30 fdOpen
  - 31 fdRead
  - 32 fdSeek
  - 33 fdTruncate
  - 34 fdWrite
  - 35 FExpand
  - 36 FLock
  - 37 FNMatch
  - 38 FSearch
  - 39 FSplit
  - 40 FSStat
  - 41 FStat
  - 42 Fcntl
  - 43 Fcntl
  - 44 Fork
  - 45 FRename
  - 46 GetDate
  - 47 GetDateTime
  - 48 GetDomainName
  - 49 GetEGid
  - 50 GetEUid
  - 51 GetEnv
  - 52 GetEpochTime
  - 53 GetFS
  - 54 GetGid
  - 55 GetHostName
  - 56 GetLocalTimezone
  - 57 GetPid
  - 58 GetPPid
  - 59 GetPriority
  - 60 GetTime
  - 61 GetTimeOfDay
  - 62 GetTimeOfDay
  - 63 GetTimezoneFile
  - 64 GetUid
  - 65 Glob
  - 66 GlobFree
  - 67 IOCtl
  - 68 IOperm
  - 69 IsATTY
  - 70 S_ISBLK
  - 71 S_ISCHR
  - 72 S_ISDIR
  - 73 S_ISFIFO
  - 74 S_ISLNK
  - 75 S_ISREG
  - 76 S_ISSOCK
  - 77 Kill
  - 78 LStat
  - 79 Link
  - 80 LocalToEpoch
  - 81 MkFifo
  - 82 MMap
  - 83 MUnMap
  - 84 Nice
  - 85 Octal
  - 86 OpenDir
  - 87 pause
  - 88 PClose
  - 89 POpen
  - 90 ReadDir
  - 91 ReadLink
  - 92 ReadPort
  - 93 ReadPortB
  - 94 ReadPortL
  - 95 ReadPortW
  - 96 ReadTimezoneFile
  - 97 SeekDir
  - 98 Select
  - 99 SelectText
  - 100 SetPriority
  - 101 Shell
  - 102 SigAction
  - 103 SigPending
  - 104 SigProcMask
  - 105 SigRaise
  - 106 SigSuspend
  - 107 Signal
  - 108 StringToPPchar
  - 109 SymLink
  - 110 SysInfo
  - 111 TCDrain
  - 112 TCFlow
  - 113 TCFlush
  - 114 TCGetAttr
  - 115 TCGetPGrp
  - 116 TCSendBreak
  - 117 TCSetAttr
  - 118 TCSetPGrp
  - 119 TTYName
  - 120 TellDir
  - 121 Umask
  - 122 Uname
  - 123 UnLink
  - 124 Utime
  - 125 WaitPid
  - 126 WritePort
  - 127 WritePortB
  - 128 WritePortL
  - 129 WritePortW

#
12 The LINUX unit.

linuxex This chapter describes the LINUX unit for Free Pascal. The unit was written by Michaël van Canneyt. It works only on the Linux operating system. This chapter is divided in 3 sections:

- The first section lists all constants, types and variables, as listed in the interface section of the LINUX unit.
- The second section gives and overview of all available functions, grouped by category.
- The third section describes all procedures and functions in the LINUX unit.

# 1 Type, Variable and Constant declarations

##
1 Types

PGlob and TGlob are 2 types used in the Glob function:

    PGlob = ^TGlob;
    TGlob = record
      Name : PChar;
      Next : PGlob;
      end;

The following types are used in the signal-processing procedures.

    tfpreg = record
      significand: array[0..3] of word;
      exponent: word;
    end;

    pfpstate = ^tfpstate;
    tfpstate = record
      cw, sw, tag, ipoff, cssel, dataoff, datasel: cardinal;
      st: array[0..7] of tfpreg;
      status: cardinal;
    end;

    PSigContextRec = ^SigContextRec;
    SigContextRec = record
      gs, __gsh: word;
      fs, __fsh: word;
      es, __esh: word;
      ds, __dsh: word;
      edi: cardinal;
      esi: cardinal;
      ebp: cardinal;
      esp: cardinal;
      ebx: cardinal;
      edx: cardinal;
      ecx: cardinal;
      eax: cardinal;
      trapno: cardinal;
      err: cardinal;
      eip: cardinal;
      cs, __csh: word;
      eflags: cardinal;
      esp_at_signal: cardinal;
      ss, __ssh: word;
      fpstate: pfpstate;
      oldmask: cardinal;
      cr2: cardinal;
      end;

The above records contain information about the processor state and process state at the moment a signal is sent to your program.

The records below are used in catching signals.

    TSigAction = procedure(Sig: Longint; SigContext: SigContextRec);cdecl;
    SignalHandler   = Procedure ( Sig : Integer);cdecl;

    PSignalHandler  = SignalHandler;
    SignalRestorer  = Procedure;cdecl;
    PSignalrestorer = SignalRestorer;
    SigActionRec = packed record
      Handler  : record
        case byte of
          0: (Sh: SignalHandler);
          1: (Sa: TSigAction);
        end;
      Sa_Mask     : SigSet;
      Sa_Flags    : Longint;
      Sa_restorer : SignalRestorer; { Obsolete - Don't use }
    end;
      PSigActionRec = ^SigActionRec;

Stat is used to store information about a file. It is defined in the syscalls unit.

      stat = record
         dev    : word;
         pad1   : word;
         ino    : longint;
         mode   : word;
         nlink  : word;
         uid    : word;
         gid    : word;
         rdev   : word;
         pad2   : word;
         size   : longint;
         blksze : Longint;
         blocks : Longint;
         atime  : Longint;
         unused1 : longint;
         mtime   : Longint;
         unused2 : longint;
         ctime   : Longint;
         unused3 : longint;
         unused4 : longint;
         unused5 : longint;
         end;

Statfs is used to store information about a filesystem. It is defined in the syscalls unit.

       statfs = record
         fstype   : longint;
         bsize    : longint;
         blocks   : longint;
         bfree    : longint;
         bavail   : longint;
         files    : longint;
         ffree    : longint;
         fsid     : longint;
         namelen  : longint;
         spare    : array [0..6] of longint;
         end

`Dir and PDir` are used in the OpenDir and ReadDir functions.

      TDir =record
        fd     : integer;
        loc    : longint;
        size   : integer;
        buf    : pdirent;
        nextoff: longint;
        dd_max : integer;
        lock   : pointer;
      end;
      PDir =^TDir;

`Dirent, PDirent` are used in the ReadDir function to return files in a directory.

     PDirent = ^Dirent;
     Dirent = Record
       ino,
       off    : longint;
       reclen : word;
       name   : string[255]
     end;

Termio and Termios are used with iotcl() calls for terminal handling.

    Const  NCCS = 19;
           NCC = 8;

    Type termio = record
    	c_iflag,		{ input mode flags }
    	c_oflag,		{ output mode flags }
    	c_cflag,		{ control mode flags }
    	c_lflag : Word;		{ local mode flags }
    	c_line : Word;		{ line discipline - careful, only High byte in use}
    	c_cc : array [0..NCC-1] of char;	{ control characters }
    end;
    termios = record
      c_iflag,              { input mode flags }
      c_oflag,              { output mode flags }
      c_cflag,              { control mode flags }
      c_lflag : Cardinal;	{ local mode flags }
      c_line : char;          { line discipline }
      c_cc : array [0..NCCS-1] of char;      { control characters }
    end;

`Utimbuf` is used in the Utime call to set access and modificaton time of a file.

    utimbuf = record
      actime,modtime : Longint;
      end;

For the Select call, the following 4 types are needed:

    FDSet = Array [0..31] of longint;
    PFDSet = ^FDSet;
    TimeVal = Record
       sec,usec : Longint;
    end;
    PTimeVal = ^TimeVal;

The Uname function uses the `utsname` to return information about the current kernel :

    utsname =record
      sysname,nodename,release,
      version,machine,domainname : Array[0..64] of char;
    end;

Its elements are null-terminated C style strings, you cannot access them directly !

## 2 Variables

`Linuxerror` is the variable in which the procedures in the linux unit report errors.

    LinuxError : Longint;

`StdErr` Is a `Text` variable, corresponding to Standard Error or diagnostic output. It is connected to file descriptor 2. It can be freely used, and will be closed on exit.

    StdErr : Text;

## 3 Constants

Constants for setting/getting process priorities :

          Prio_Process = 0;
          Prio_PGrp    = 1;
          Prio_User    = 2;

For testing access rights:

          R_OK = 4;
          W_OK = 2;
          X_OK = 1;
          F_OK = 0;

For signal handling functions :

          SA_NOCLDSTOP = 1;
          SA_SHIRQ	   = $04000000;
          SA_STACK	   = $08000000;
          SA_RESTART   = $10000000;
          SA_INTERRUPT = $20000000;
          SA_NOMASK	   = $40000000;
          SA_ONESHOT   = $80000000;

          SIG_BLOCK	  = 0;
          SIG_UNBLOCK = 1;
          SIG_SETMASK = 2;
          SIG_DFL = 0 ;
          SIG_IGN = 1 ;
          SIG_ERR = -1;

          SIGHUP		= 1;
          SIGINT		= 2;
          SIGQUIT		= 3;
          SIGILL		= 4;
          SIGTRAP		= 5;
          SIGABRT		= 6;
          SIGIOT		= 6;
          SIGBUS		= 7;
          SIGFPE		= 8;
          SIGKILL		= 9;
          SIGUSR1		= 10;
          SIGSEGV		= 11;
          SIGUSR2		= 12;
          SIGPIPE		= 13;
          SIGALRM		= 14;
          SIGTERM		= 15;
          SIGSTKFLT		= 16;
          SIGCHLD		= 17;
          SIGCONT		= 18;
          SIGSTOP		= 19;
          SIGTSTP		= 20;
          SIGTTIN		= 21;
          SIGTTOU		= 22;
          SIGURG		= 23;
          SIGXCPU		= 24;
          SIGXFSZ		= 25;
          SIGVTALRM		= 26;
          SIGPROF		= 27;
          SIGWINCH		= 28;
          SIGIO		= 29;
          SIGPOLL		= SIGIO;
          SIGPWR		= 30;
          SIGUNUSED		= 31;

For file control mechanism :

          F_GetFd  = 1;
          F_SetFd  = 2;
          F_GetFl  = 3;
          F_SetFl  = 4;
          F_GetLk  = 5;
          F_SetLk  = 6;
          F_SetLkW = 7;
          F_GetOwn = 8;
          F_SetOwn = 9;

For Terminal handling :

       TCGETS	= $5401 ;
       TCSETS	= $5402 ;
       TCSETSW	= $5403 ;
       TCSETSF	= $5404 ;
       TCGETA	= $5405 ;
       TCSETA	= $5406 ;
       TCSETAW	= $5407 ;
       TCSETAF	= $5408 ;
       TCSBRK	= $5409 ;
       TCXONC	= $540A ;
       TCFLSH	= $540B ;
       TIOCEXCL	= $540C ;
       TIOCNXCL	= $540D ;
       TIOCSCTTY	= $540E ;
       TIOCGPGRP	= $540F ;
       TIOCSPGRP	= $5410 ;
       TIOCOUTQ	= $5411 ;
       TIOCSTI	= $5412 ;
       TIOCGWINSZ	= $5413 ;
       TIOCSWINSZ	= $5414 ;
       TIOCMGET	= $5415 ;
       TIOCMBIS	= $5416 ;
       TIOCMBIC	= $5417 ;
       TIOCMSET	= $5418 ;
       TIOCGSOFTCAR	= $5419 ;
       TIOCSSOFTCAR	= $541A ;
       FIONREAD	= $541B ;
       TIOCINQ	= FIONREAD;
       TIOCLINUX	= $541C ;
       TIOCCONS	= $541D ;
       TIOCGSERIAL	= $541E ;
       TIOCSSERIAL	= $541F ;
       TIOCPKT	= $5420 ;
       FIONBIO	= $5421 ;
       TIOCNOTTY	= $5422 ;
       TIOCSETD	= $5423 ;
       TIOCGETD	= $5424 ;
       TCSBRKP		= $5425	 ;
       TIOCTTYGSTRUCT	= $5426  ;
       FIONCLEX	= $5450  ;
       FIOCLEX		= $5451 ;
       FIOASYNC	= $5452 ;
       TIOCSERCONFIG	= $5453 ;
       TIOCSERGWILD	= $5454 ;
       TIOCSERSWILD	= $5455 ;
       TIOCGLCKTRMIOS	= $5456 ;
       TIOCSLCKTRMIOS	= $5457 ;
       TIOCSERGSTRUCT	= $5458  ;
       TIOCSERGETLSR   = $5459  ;
       TIOCSERGETMULTI = $545A  ;
       TIOCSERSETMULTI = $545B  ;
       TIOCMIWAIT	= $545C	;
       TIOCGICOUNT	= $545D	;
       TIOCPKT_DATA		= 0;
       TIOCPKT_FLUSHREAD	= 1;
       TIOCPKT_FLUSHWRITE	= 2;
       TIOCPKT_STOP		= 4;
       TIOCPKT_START	= 8;
       TIOCPKT_NOSTOP	= 16;
       TIOCPKT_DOSTOP	= 32;

Other than that, all constants for setting the speed and control flags of a terminal line, as described in the `termios` (2) man page, are defined in the linux unit. It would take too much place to list them here. To check the `mode` field of a `stat` record, you ca use the following constants :

      { Constants to check stat.mode }
      STAT_IFMT   = $f000; {00170000}
      STAT_IFSOCK = $c000; {0140000}
      STAT_IFLNK  = $a000; {0120000}
      STAT_IFREG  = $8000; {0100000}
      STAT_IFBLK  = $6000; {0060000}
      STAT_IFDIR  = $4000; {0040000}
      STAT_IFCHR  = $2000; {0020000}
      STAT_IFIFO  = $1000; {0010000}
      STAT_ISUID  = $0800; {0004000}
      STAT_ISGID  = $0400; {0002000}
      STAT_ISVTX  = $0200; {0001000}
      { Constants to check permissions }
      STAT_IRWXO = $7;
      STAT_IROTH = $4;
      STAT_IWOTH = $2;
      STAT_IXOTH = $1;
      STAT_IRWXG = STAT_IRWXO shl 3;
      STAT_IRGRP = STAT_IROTH shl 3;
      STAT_IWGRP = STAT_IWOTH shl 3;
      STAT_IXGRP = STAT_IXOTH shl 3;
      STAT_IRWXU = STAT_IRWXO shl 6;
      STAT_IRUSR = STAT_IROTH shl 6;
      STAT_IWUSR = STAT_IWOTH shl 6;
      STAT_IXUSR = STAT_IXOTH shl 6;

You can test the type of a filesystem returned by a FSStat call with the following constants:

      fs_old_ext2 = $ef51;
      fs_ext2     = $ef53;
      fs_ext      = $137d;
      fs_iso      = $9660;
      fs_minix    = $137f;
      fs_minix_30 = $138f;
      fs_minux_V2 = $2468;
      fs_msdos    = $4d44;
      fs_nfs      = $6969;
      fs_proc     = $9fa0;
      fs_xia      = $012FD16D;

the FLock call uses the following mode constants :

      LOCK_SH = 1;
      LOCK_EX = 2;
      LOCK_UN = 8;
      LOCK_NB = 4;

The MMap function uses the following constants to specify access to mapped memory:

      PROT_READ  = $1;   { page can be read }
      PROT_WRITE = $2;   { page can be written }
      PROT_EXEC  = $4;   { page can be executed }
      PROT_NONE  = $0;   { page can not be accessed }

and the following constants to specify the type of mapping.

      MAP_SHARED    = $1;  { Share changes }
      MAP_PRIVATE   = $2;  { Changes are private }
      MAP_TYPE      = $f;  { Mask for type of mapping }
      MAP_FIXED     = $10; { Interpret addr exactly }
      MAP_ANONYMOUS = $20; { don't use a file }

# 2 Function list by category

What follows is a listing of the available functions, grouped by category. For each function there is a reference to the page where you can find the function.

## 1 File Input/Output routines

Functions for handling file input/output. Dup Duplicate a file handle]

Dup2 Copy one file handle to another
Fcntl General file control
fdClose Close file descriptor
fdFlush Flush file descriptor
fdOpen Open new file descriptor
fdRead Read from file descriptor
fdSeek Position in file
fdTruncate Truncate file
fdWrite Write to file descriptor
GetFS Get file descriptor of pascal file
Select Wait for input from file descriptor
SelectText Wait for input from pascal file

## 2 General File handling routines

Functions for handling files on disk. Access Check access rights on file]

BaseName Return name part of file
Chown Change owner of file
Chmod Change access rights on file
DirName Return directory part of file
LFsplit Split filename in parts
FExpand Return full-grown filename
FLock Set lock on a file
FNMatch Match filename to searchpattern
FSearch Search for a file in a path
FSStat Return filesystem information
FStat Return file information
FRename Rename file
LStat Return information on a link
Link Create a link
ReadLink Read contents of a symbolic link
SymLink Create a symbolic link
Umask Set the file creation mask
UnLink Remove a file
Utime Change file timestamps

## 3 Pipes, FIFOs and streams

Functions for creating and managing pipes. AssignPipe Create a pipe]

AssignStream Create pipes to program's input and output
MkFifo Make a fifo
PClose Close a pipe
POpen Open a pipe for to program's input or output

## 4 Directory handling routines

Functions for reading and searching directories. CloseDir Close directory handle]

Glob Return files matching a search expression
GlobFree Free result of Glob
OpenDir Open directory for reading
ReadDir Read directory entry
SeekDir Seek directory
TellDir Seek directory

## 5 Process handling

Functions for managing processes and programs. Clone Create a thread]

Execl Execute process with command-line list
Execle Execute process with command-line list and environment
Execlp Search in path and execute process with command list
Execv Execute process
Execve Execute process with environment
Execvp Search in path and execute process
Fork Spawn child process
GetEGid Get effective group id
GetEnv Get environment variable
GetEUid Get effective user id
GetGid Get group id
GetPid Get process id
GetPPid Get parent process id
GetPriority Get process priority
GetUid Get user id
Nice Change priority of process
SetPriority Change priority of process
Shell Execute shell command
WaitPid Wait for child process to terminate

## 6 Signals

Functions for managing and responding to signals. Alarm Send alarm signal to self]

Kill Send arbitrary signal to process
pause Wait for signal to arrive
SigAction Set signal action
Signal Set signal action
SigPending See if signals are waiting
SigProcMask Set signal processing mask
SigRaise Send signal to self
SigSuspend Sets signal mask and waits for signal

## 7 System information

Functions for retrieving system information such as date and time. GetDate Return system date]

GetDateTime Return system date and time
GetDomainName Return system domain name
GetEpochTime Return epoch time
GetHostName Return system host name
GetLocalTimezone Return system timezone
GetTime Return system time
GetTimeOfDay Return system time
GetTimezoneFile Return name of timezone file
ReadTimezoneFile Read timezone file contents
SysInfo Return general system information
Uname Return system information

## 8 Terminal functions

Functions for controlling the terminal to which the process is connected.

CFMakeRaw Set terminal to raw mode]

CFSetISpeed Set terminal reading speed
CFSetOSpeed Set terminal writing speed
IOCtl General IO control call
IsATTY See if filedescriptor is a terminal
TCDrain Wait till all output was written
TCFlow Suspend transmission or receipt of data
TCFlush Discard data written to terminal
TCGetAttr Get terminal attributes
TCGetPGrp Return PID of foreground process
TCSendBreak Send data for specific time
TCSetAttr Set terminal attributes
TCSetPGrp Set foreground process
TTYName Name of tty file

## 9 Port input/output

Functions for reading and writing to the hardware ports. IOperm Set permissions for port access]

ReadPort Read data from port
ReadPortB Read 1 byte from port
ReadPortL Read 4 bytes from port
ReadPortW Read 2 bytes from port
WritePort Write data to port
WritePortB Write 1 byte to port
WritePortL Write 4 bytes to port
WritePortW Write 2 bytes to port

## 10 Utility routines

Auxiliary functions that are useful in connection with the other functions. CreateShellArgV Create an array of pchars from string]

EpochToLocal Convert epoch time to local time
FDClr Clear item of select filedescriptors
FDIsSet Check item of select filedescriptors
FDSet Set item of select filedescriptors
FDZero Clear all items in select filedecriptors
LocalToEpoch Convert local time to epoch time
MMap Map a file into memory
MUnMap Unmap previously mapped memory file
Octal Convert octal to digital
ISBLK Check file mode for block device
ISCHR Check file mode for character device
ISDIR Check file mode for directory
ISFIFO Check file mode for FIFO
ISLNK Check file mode for symboloc link
ISREG Check file mode for regular file
ISSOCK Check file mode for socket
StringToPPchar Create an array of pchars from string

# 3 Functions and procedures

##
1 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, Chmod, `Access` (2)

Example

      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.

##
2 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

Example

      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.

##
3 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, MkFifo, `pipe` (2)

Example

      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.

##
4 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, POpen,`pipe` (2)

Example

      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.

##
5 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, FExpand, `Basename` (1)

Example

      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.

##
6 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, CFSetISpeed, `termios` (2)

For an example, see TCGetAttr.

##
7 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, CFMakeRaw, `termios` (2)

##
8 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, CFMakeRaw, `termios` (2)

##
9 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, Access, `Chown` (() 2)

Example

      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.

##
10 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, Access, `Chmod` (() 2), Octal

Example

      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.

##
11 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 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, `clone` (2)

Example

      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.

##
12 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, ReadDir, SeekDir, TellDir, `closedir` (3)

For an example, see OpenDir.

##
13 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

Example

      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.

##
14 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, FExpand, `Dirname` (1)

Example

      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.

##
15 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, `Dup` (2)

Example

      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.

##
16 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, `Dup2` (2)

Example

      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.

##
17 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, LocalToEpoch, GetTime,GetDate

Example

      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.

##
18 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, Execv, Execvp, Execle, Execlp, Fork, `execvp` (3)

Example

      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.

##
19 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, Execv, Execvp, Execl, Execlp, Fork, `execvp` (3)

Example

      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.

##
20 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, Execv, Execvp, Execle, Execl, Fork, `execvp` (3)

Example

      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.

##
21 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, Execvp, Execle, Execl, Execlp, Fork, `execv` (3)

Example

      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.

##
22 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, Execv, Execvp Execle, Execl, Execlp, Fork, `execve` (2)

Example

      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.

##
23 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, Execv, Execle, Execl, Execlp, Fork, `execvp` (3)

Example

      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.

##
24 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, SelectText, GetFS, FD_Clr, FD_Set, FD_IsSet

For an example, see Select.

##
25 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, SelectText, GetFS, FD_ZERO, FD_Set, FD_IsSet

For an example, see Select.

##
26 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, SelectText, GetFS, FD_ZERO, FD_Clr, FD_Set

For an example, see Select.

##
27 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, SelectText, GetFS,FD_ZERO, FD_Clr, FD_IsSet

For an example, see Select.

##
28 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, fdRead, fdWrite,fdTruncate, fdFlush, seefFdSeek

For an example, see fdOpen.

##
29 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, fdClose, fdRead,fdWrite, fdTruncate, fdSeek

For an example, see fdRead.

##
30 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 be`OR`-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, fdRead, fdWrite,fdTruncate, fdFlush, fdSeek

Example

      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.

##
31 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, fdClose, fdWrite,fdTruncate, fdFlush, fdSeek

Example

      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.

##
32 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, fdWrite, fdClose, fdRead,fdTruncate, fdFlush

For an example, see fdOpen.

##
33 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, fdClose, fdRead,fdWrite,fdFlush, fdSeek

##
34 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, fdClose, fdRead,fdTruncate, fdSeek, fdFlush

##
35 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,DirName

Example

      Program Example45;

      { Program to demonstrate the FExpand function. }

      Uses linux;

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

##
36 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, `flock` (2)

##
37 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, FExpand

Example

      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.

##
38 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, DirName, FExpand, FNMatch

Example

      Program Example46;

      { Program to demonstrate the FSearch function. }

      Uses linux,strings;

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

##
39 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

Example

      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.

##
40 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, LStat, `statfs` (2)

Example

      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.

##
41 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, LStat, `stat` (2)

Example

      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.

##
42 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, `Fcntl` (2)

##
43 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, `Fcntl` (2) , seefFLock

##
44 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).

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, Clone, `fork` (2)

##
45 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

##
46 GetDate

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

Example

      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.

##
47 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 and `GetTime` calls.
Errors
  None
See also
  GetEpochTime, GetTime, EpochToLocal, GetDate

Example

      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.

##
48 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,seemGetdomainname2

Example

      Program Example39;

      { Program to demonstrate the GetDomainName function. }

      Uses linux;

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

##
49 GetEGid

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

Example

      Program Example18;

      { Program to demonstrate the GetGid and GetEGid functions. }

      Uses linux;

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

##
50 GetEUid

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

Example

      Program Example17;

      { Program to demonstrate the GetUid and GetEUid functions. }

      Uses linux;

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

##
51 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)

Example

      Program Example41;

      { Program to demonstrate the GetEnv function. }

      Uses linux;

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

##
52 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, GetTime, `time` (2)

Example

      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.

##
53 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 call or so.
Errors
  In case the file was not opened, then -1 is returned.
See also
  Select

Example

      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.

##
54 GetGid

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

Example

      Program Example18;

      { Program to demonstrate the GetGid and GetEGid functions. }

      Uses linux;

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

##
55 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,seemGethostname2

Example

      Program Example40;

      { Program to demonstrate the GetHostName function. }

      Uses linux;

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

##
56 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, ReadTimezoneFile

##
57 GetPid

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

Example

      Program Example16;

      { Program to demonstrate the GetPid, GetPPid function. }

      Uses linux;

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

##
58 GetPPid

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

Example

      Program Example16;

      { Program to demonstrate the GetPid, GetPPid function. }

      Uses linux;

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

##
59 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, Nice, `Getpriority` (2)

For an example, see Nice.

##
60 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, GetDate, GetDateTime, EpochToLocal

Example

      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.

##
61 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.

Errors
  None.
See also
  GetTime, GetTimeOfDay

##
62 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.

Errors
  None.
See also
  GetTimeOfDay, GetTime

##
63 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

##
64 GetUid

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

Example

      Program Example17;

      { Program to demonstrate the GetUid and GetEUid functions. }

      Uses linux;

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

##
65 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, `Glob` (3)

Example

      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.

##
66 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

For an example, see Glob.

##
67 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)

Example

      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.

##
68 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:
  - This works ONLY as root.
  - Only the first `0x03ff` ports can be set.
  - When doing a Fork, the permissions are reset. When doing a Execve they are kept.

Errors
  Errors are returned in `LinuxError`
See also
  `ioperm` (2)

##
69 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,TTYName

##
70 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, S_ISLNK, S_ISREG, S_ISDIR, S_ISCHR, S_ISFIFO, S_ISSOCK

See also
  ISLNK.

##
71 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, S_ISLNK, S_ISREG, S_ISDIR, S_ISBLK, S_ISFIFO, S_ISSOCK

See also
  ISLNK.

##
72 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, S_ISLNK, S_ISREG, S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK

See also
  ISLNK.

##
73 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, S_ISLNK, S_ISREG, S_ISDIR, S_ISCHR, S_ISBLK, S_ISSOCK

See also
  ISLNK.

##
74 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, S_ISREG, S_ISDIR, S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK

See also

Example

      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.

##
75 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, S_ISLNK, S_ISDIR, S_ISCHR, S_ISBLK, S_ISFIFO, S_ISSOCK

See also
  ISLNK.

##
76 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, S_ISLNK, S_ISREG, S_ISDIR, S_ISCHR, S_ISBLK, S_ISFIFO

See also
  ISLNK.

##
77 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, Signal, `Kill` (2)

##
78 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, FSStat, `stat` (2)

Example

      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.

##
79 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, UnLink, `Link` (2)

Example

      Program Example21;

      { Program to demonstrate the Link 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 Link ('test.txt','new.txt') then
          writeln ('Error when linking !');
        { Removing test.txt still leaves new.txt }
        If not Unlink ('test.txt') then
          Writeln ('Error when unlinking !');
        Assign (f,'new.txt');
        Reset (F);
        While not EOF(f) do
          begin
          Readln(F,S);
          Writeln ('> ',s);
          end;
       Close (f);
       { Remove new.txt also }
       If not Unlink ('new.txt') then
         Writeln ('Error when unlinking !');
      end.

##
80 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, EpochToLocal, GetTime,GetDate

Example

      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.

##
81 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, MkFifo, `mkfifo` (4)

##
82 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, `mmap` (2)

Example

      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.

##
83 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.

  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 for possible error values.
See also
  MMap, `munmap` (2)

For an example, see MMap.

##
84 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, SetPriority, `Nice` (2)

Example

      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.

##
85 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 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.

Example

      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.

##
86 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, ReadDir, SeekDir, TellDir, `opendir` (3)

Example

      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.

##
87 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.

##
88 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

For an example, see POpen

##
89 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. 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, `popen` (3) , PClose

Example

      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.

##
90 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, OpenDir, SeekDir, TellDir, `readdir` (3)

For an example, see OpenDir.

##
91 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

Example

      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.

##
92 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 call.

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

  IOperm, ReadPortB, ReadPortW, ReadPortL,WritePort, WritePortB, WritePortL, WritePortW

##
93 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 call.

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

See also
  IOperm, ReadPort, ReadPortW, ReadPortL,WritePort, WritePortB, WritePortL, WritePortW

##
94 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 call.

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

##
95 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 call.

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

##
96 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, GetLocalTimezone

##
97 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, ReadDir, OpenDir, TellDir, `seekdir` (3)

For an example, see OpenDir.

##
98 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, FD_Clr, FD_Set, FD_IsSet 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, GetFS, FD_ZERO, FD_Clr, FD_Set, FD_IsSet

Example

      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.

##
99 SelectText

Declaration
  `Function SelectText ( var T : Text; TimeOut :PTime) : Longint;`
Description
  SelectText executes the Select 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. `SYS_EBADF` can also mean that the file wasn't opened.
See also
  Select, GetFS

##
100 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, Nice, `Setpriority` (2)

For an example, see Nice.

##
101 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 or Execve calls.

Errors
  Errors are reported in LinuxError.
See also
  POpen, Fork, Execve, `system` (3)

Example

      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.

##
102 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, SigPending, SigSuspend, Kill, `Sigaction` (2)

Example

      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.

##
103 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, SigProcMask, SigSuspend, Signal, Kill, `Sigpending` (2)

##
104 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, SigPending, SigSuspend, Kill, `Sigprocmask` (2)

##
105 SigRaise

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

Example

      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.

##
106 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, SigProcMask, SigPending, Signal, Kill, `SigSuspend` (2)

##
107 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,Kill, `Signal` (2)

Example

      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.

##
108 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, Execve, Execv

Example

      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.

##
109 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, UnLink, ReadLink, `Symlink` (2)

Example

      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.

##
110 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

Example

      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.

##
111 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)

##
112 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)

##
113 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)

##
114 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, `termios` (2)

Example

      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.

##
115 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)

##
116 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)

##
117 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, `termios` (2)

For an example, see TCGetAttr.

##
118 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, `termios` (2)

For an example, see TCGetPGrp.

##
119 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,IOCtl

##
120 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, ReadDir, SeekDir, OpenDir, `telldir` (3)

For an example, see OpenDir.

##
121 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, `Umask` (2)

Example

      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.

##
122 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, GetDomainName, `uname` (2)

##
123 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, SymLink, `Unlink` (2)

For an example, see Link.

##
124 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, Chown, Access, `utime` (() 2)

Example

      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.

##
125 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 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, Execve, `waitpid` (2)

For an example, see Fork.

##
126 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, WritePortB, WritePortL, WritePortW, ReadPortB, ReadPortL, ReadPortW

##
127 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, WritePort, WritePortL, WritePortW, ReadPortB, ReadPortL, ReadPortW

##
128 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, WritePort, WritePortB, WritePortW, ReadPortB, ReadPortL, ReadPortW

##
129 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, WritePort, WritePortL, WritePortB, ReadPortB, ReadPortL, ReadPortW