unit stdio;

{$mode objfpc}
interface
(* A streammarker remembers a position in a buffer. *)

uses linux,sockets;

const
  EOF=-1;         (* признак конца файла для stdio *)
  
  WCOREFLAG=$80;  (* флаг сброса дампа памяти *)
  
  (* Размер буфера для чтения и записи *)
  BUFSIZ=8192;

  NULL=nil;      

  _IOFBF=0;  (* setvbuf should set fully buffered *)
  _IOLBF=1;  (* setvbuf should set line buffered *)
  _IONBF=2;  (* setvbuf should set unbuffered *)

  MAX_INPUT=255;  (* size of the type-ahead buffer *)
  
  _SIGSET_NWORDS=1024 div (8 * sizeof (longint)); (* sizeof(sigset_t) *)
  
  (* флаги для pathconf/fpathconf *)

  (* returns  the maximum number of links to the file.  If filedes or
   * path refer to a directory, then the value applies to  the  whole
   * directory.
   *)
  _PC_LINK_MAX=0;
  (* returns  the  maximum  length  of  a formatted input line, where
   * filedes or path must refer to  a  terminal.
   *)
  _PC_MAX_CANON=1;
  (* returns  the  maximum  length of an input line, where filedes or
   * path must refer to  a  terminal.
   *)
  _PC_MAX_INPUT=2;
  (* returns  the  maximum length of a filename in the directory path
   * or filedes.  the process is allowed to create.
   *)
  _PC_NAME_MAX=3;
  (* returns  the  maximum length of a relative pathname when path or
   * filedes is the current  working  directory.
   *)
  _PC_PATH_MAX=4;
  (* returns the size of the pipe buffer, where filedes must refer to
   * a pipe or FIFO and path must refer to a FIFO.
   *)
  _PC_PIPE_BUF=5;
  (* returns  nonzero  if  the  chown(2) call may not be used on this
   * file.  If filedes or  path  refer  to  a  directory,  then  this
   * applies to all files in that directory.
   *)
  _PC_CHOWN_RESTRICTED=6;
  (* returns   nonzero   if   accessing   filenames    longer    than
   * _POSIX_NAME_MAX  generates an error.
   *)
  _PC_NO_TRUNC=7;
  (* returns nonzero if special character processing can be disabled,
   * where filedes or path must refer to a terminal.
   *)
  _PC_VDISABLE=8;
  _PC_SYNC_IO=9;
  _PC_ASYNC_IO=10;
  _PC_PRIO_IO=11;
  _PC_SOCK_MAXBUF=12;
  _PC_FILESIZEBITS=13;
  _PC_REC_INCR_XFER_SIZE=14;
  _PC_REC_MAX_XFER_SIZE=15;
  _PC_REC_MIN_XFER_SIZE=16;
  _PC_REC_XFER_ALIGN=17;
  _PC_ALLOC_SIZE_MIN=18;
  _PC_SYMLINK_MAX=19;

  (* For posix fcntl() and `l_type' field of a `struct flock' for lockf().  *)
  F_RDLCK=0;       (* Read lock.  *)
  F_WRLCK=1;       (* Write lock.  *)
  F_UNLCK=2;       (* Remove lock.  *)

  F_DUPFD=0;       (* Duplicate fildes *)

  (* Constants for ulimit *)
  UL_GETFSIZE=1;      (* возвращает установленное ограничение на размер 
                         файла (в блоках по 512 байт) *)
  UL_SETFSIZE=2;      (* устанавливает предельный размер файла *)
  __UL_GETMAXBRK=3;   (* возвращает максимально возможный адрес сегмента данных *)
  __UL_GETOPENMAX=4;  (* возвращает максимальное количество файлов, которое 
                         процесс может открыть *)

  FD_SETSIZE=64;
  
  (* Macros used as `request' argument to `ioctl'.  *)
  __SID=byte('S') shl 8;
  I_NREAD     =__SID or 1;  (* Counts the number of data bytes in the data
                               block in the first message.  *)
  I_PUSH      =__SID or 2;  (* Push STREAMS module onto top of the current
                               STREAM, just below the STREAM head.  *)
  I_POP       =__SID or 3;  (* Remove STREAMS module from just below the
                               STREAM head.  *)
  I_LOOK      =__SID or 4;  (* Retrieve the name of the module just below
                               the STREAM head and place it in a character 
                               string.  *)
  I_FLUSH     =__SID or 5;  (* Flush all input and/or output.  *)
  I_SRDOPT    =__SID or 6;  (* Sets the read mode.  *)
  I_GRDOPT    =__SID or 7;  (* Returns the current read mode setting.  *)
  I_STR       =__SID or 8;  (* Construct an internal STREAMS `ioctl'
                               message and send that message downstream. *)
  I_SETSIG    =__SID or 9;  (* Inform the STREAM head that the process
                               wants the SIGPOLL signal issued.  *)
  I_GETSIG    =__SID or 10; (* Return the events for which the calling
                               process is currently registered to be sent
                               a SIGPOLL signal.  *)
  I_FIND      =__SID or 11; (* Compares the names of all modules currently
                               present in the STREAM to the name pointed to
                               by `arg'.  *)
  I_LINK      =__SID or 12; (* Connect two STREAMs.  *)
  I_UNLINK    =__SID or 13; (* Disconnects the two STREAMs.  *)
  I_PEEK      =__SID or 15; (* Allows a process to retrieve the information
                               in the first message on the STREAM head read
                               queue without taking the message off the
                               queue.  *)
  I_FDINSERT  =__SID or 16; (* Create a message from the specified                                                                                
                               buffer(s), adds information about another                                                                                                                                                                               
                               STREAM, and send the message downstream.  *)
  I_SENDFD    =__SID or 17; (* Requests the STREAM associated with `fildes'
                               to send a message, containing a file
                               pointer, to the STREAM head at the other end
                               of a STREAMS pipe.  *)
  I_RECVFD    =__SID or 14; (* Non-EFT definition.  *)
  I_SWROPT    =__SID or 19; (* Set the write mode.  *)
  I_GWROPT    =__SID or 20; (* Return the current write mode setting.  *)
  I_LIST      =__SID or 21; (* List all the module names on the STREAM, up
                               to and including the topmost driver name. *)
  I_PLINK     =__SID or 22; (* Connect two STREAMs with a persistent
                                link.  *)
  I_PUNLINK   =__SID or 23; (* Disconnect the two STREAMs that were
                               connected with a persistent link.  *)
  I_FLUSHBAND =__SID or 28; (* Flush only band specified.  *)
  I_CKBAND    =__SID or 29; (* Check if the message of a given priority
                               band exists on the STREAM head read
                               queue.  *)
  I_GETBAND   =__SID or 30; (* Return the priority band of the first
                               message on the STREAM head read queue.  *)
  I_ATMARK    =__SID or 31; (* See if the current message on the STREAM
                               head read queue is "marked" by some module
                               downstream.  *)
  I_SETCLTIME =__SID or 32; (* Set the time the STREAM head will delay when
                               a STREAM is closing and there is data on
                               the write queues.  *)
  I_GETCLTIME =__SID or 33; (* Get current value for closing timeout.  *)
  I_CANPUT    =__SID or 34; (* Check if a certain band is writable.  *)

  (* для интерфейса сокетов *)  
  INADDR_ANY=0;
  { Maximum queue length specificable by listen.   }
  SOMAXCONN = 5;
  { Flags we can use with send/ and recv.  }
  { process out-of-band data  }
  MSG_OOB = $1;
  { peek at incoming message  }
  MSG_PEEK = $2;
  { send without using routing tables  }
  MSG_DONTROUTE = $4;
  { Setsockoptions(2) level. Thanks to BSD these must match IPPROTO_xxx  }
  SOL_IP = 0;
  SOL_IPX = 256;
  SOL_AX25 = 257;
  SOL_ATALK = 258;
  SOL_NETROM = 259;
  SOL_TCP = 6;
  SOL_UDP = 17;
  { IP options  }
  IPTOS_LOWDELAY = $10;
  IPTOS_THROUGHPUT = $08;
  IPTOS_RELIABILITY = $04;
  { These need to appear somewhere around here  }
  IP_DEFAULT_MULTICAST_TTL = 1;
  IP_DEFAULT_MULTICAST_LOOP = 1;
  IP_MAX_MEMBERSHIPS = 20;
  { IP options for use with WinSock  }
  IP_OPTIONS = 1;
  IP_MULTICAST_IF = 2;
  IP_MULTICAST_TTL = 3;
  IP_MULTICAST_LOOP = 4;
  IP_ADD_MEMBERSHIP = 5;
  IP_DROP_MEMBERSHIP = 6;
  IP_TTL = 7;
  IP_TOS = 8;
  IP_DONTFRAGMENT = 9;
  { IPX options  }
  IPX_TYPE = 1;
  { TCP options }
  TCP_NODELAY = $0001;
  TCP_MAXSEG = 2;
  { The various priorities.  }
  SOPRI_INTERACTIVE = 0;
  SOPRI_NORMAL = 1;
  SOPRI_BACKGROUND = 2;


  (* управление терминалом *)
  TCOOFF = 0;
  TCOON = 1;
  TCIOFF = 2;
  TCION = 3;
  TCGETA = 5;
  TCSETA = 6;
  TCSETAW = 7;
  TCSETAF = 8;
  TCIFLUSH = 0;
  TCOFLUSH = 1;
  TCIOFLUSH = 2;
  TCFLSH = 3;
  TCSAFLUSH = 1;
  TCSANOW = 2;
  TCSADRAIN = 3;
  TCSADFLUSH = 4;
  TIOCPKT = 6;
  TIOCPKT_DATA = 0;
  TIOCPKT_FLUSHREAD = 1;
  TIOCPKT_FLUSHWRITE = 2;
  TIOCPKT_STOP = 4;
  TIOCPKT_START = 8;
  TIOCPKT_NOSTOP = 16;
  TIOCPKT_DOSTOP = 32;
  { To be compatible with socket version  }
  FIONBIO = $8004667e;
  { iflag bits  }
  IGNBRK = $00001;
  BRKINT = $00002;
  IGNPAR = $00004;
  IMAXBEL = $00008;
  INPCK = $00010;
  ISTRIP = $00020;
  INLCR = $00040;
  IGNCR = $00080;
  ICRNL = $00100;
  IXON = $00400;
  IXOFF = $01000;
  IUCLC = $04000;
  IXANY = $08000;
  PARMRK = $10000;
  { oflag bits  }
  OPOST = $00001;
  OLCUC = $00002;
  OCRNL = $00004;
  ONLCR = $00008;
  ONOCR = $00010;
  ONLRET = $00020;
  OFILL = $00040;
  CRDLY = $00180;
  CR0 = $00000;
  CR1 = $00080;
  CR2 = $00100;
  CR3 = $00180;
  NLDLY = $00200;
  NL0 = $00000;
  NL1 = $00200;
  BSDLY = $00400;
  BS0 = $00000;
  BS1 = $00400;
  TABDLY = $01800;
  TAB0 = $00000;
  TAB1 = $00800;
  TAB2 = $01000;
  TAB3 = $01800;
  XTABS = $01800;
  VTDLY = $02000;
  VT0 = $00000;
  VT1 = $02000;
  FFDLY = $04000;
  FF0 = $00000;
  FF1 = $04000;
  OFDEL = $08000;
  { cflag bits  }
  { Baud rate values.  These must fit in speed_t, which is unsigned
  char.  See also the extended baud rates below.  These baud rates
  set an additional bit.  }
  CBAUD = $0100f;
  B0 = $00000;
  B50 = $00001;
  B75 = $00002;
  B110 = $00003;
  B134 = $00004;
  B150 = $00005;
  B200 = $00006;
  B300 = $00007;
  B600 = $00008;
  B1200 = $00009;
  B1800 = $0000a;
  B2400 = $0000b;
  B4800 = $0000c;
  B9600 = $0000d;
  B19200 = $0000e;
  B38400 = $0000f;
  CSIZE = $00030;
  CS5 = $00000;
  CS6 = $00010;
  CS7 = $00020;
  CS8 = $00030;
  CSTOPB = $00040;
  CREAD = $00080;
  PARENB = $00100;
  PARODD = $00200;
  HUPCL = $00400;
  CLOCAL = $00800;
  CBAUDEX = $0100f;
  B57600 = $01001;
  B115200 = $01002;
  B128000 = $01003;
  B256000 = $01003;
  CRTSXOFF = $04000;
  CRTSCTS = $08000;
  { lflag bits  }
  ISIG = $0001;
  ICANON = $0002;
  ECHO = $0004;
  ECHOE = $0008;
  ECHOK = $0010;
  ECHONL = $0020;
  NOFLSH = $0040;
  TOSTOP = $0080;
  IEXTEN = $0100;
  FLUSHO = $0200;
  ECHOKE = $0400;
  ECHOCTL = $0800;
  VDISCARD = 1;
  VEOL = 2;
  VEOL2 = 3;
  VEOF = 4;
  VERASE = 5;
  VINTR = 6;
  VKILL = 7;
  VLNEXT = 8;
  VMIN = 9;
  VQUIT = 10;
  VREPRINT = 11;
  VSTART = 12;
  VSTOP = 13;
  VSUSP = 14;
  VSWTC = 15;
  VTIME = 16;
  VWERASE = 17;
  CNUL = 0;
  CDEL = $0007f;
  CESC = byte('\');
  CINTR = byte('C') and $1f;
  CQUIT = $0001c;
  CERASE = byte('H') and $1f;
  CKILL = byte('U') and $1f;
  CEOT = byte('D') and $1f;
  CEOL = 0;
  CEOL2 = 0;
  CEOF = byte('D') and $1f;
  CSTART = byte('Q') and $1f;
  CSTOP = byte('S') and $1f;
  CSWTCH = $0001a;
  NSWTCH = 0;
  CSUSP = byte('Z') and $1f;
  CDSUSP = byte('Y') and $1f;
  CRPRNT = byte('R') and $1f;
  CFLUSH = byte('O') and $1f;
  CWERASE = byte('W') and $1f;
  CLNEXT = byte('V') and $1f;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

 
type PFILE=^TFILE;

_IO_marker=record
  next:^_IO_marker;
  sbuf:PFILE;
  _pos:integer;
end;

P_IO_marker=^_IO_marker;

ppchar=^pchar;
pinteger=^integer;
plongint=^longint;

sigset_t=record
  __val:array [0.._SIGSET_NWORDS-1] of longint;
end;

psigset_t=^sigset_t;

__jmp_buf=array [0..5] of longint;
__jmp_buf_tag=record
  __jmpbuf:__jmp_buf;               (* Calling environment.  *)
  __mask_was_saved:longint;         (* Saved the signal mask?  *)
  __saved_mask:sigset_t;              (* Saved signal mask.  *)
end;
jmp_buf=array [0..0] of __jmp_buf_tag;
sigjmp_buf=jmp_buf;

flockrec=record
  l_type:word;     (* Type of lock: F_RDLCK, F_WRLCK, or F_UNLCK.  *)
  l_whence:word;   (* Where `l_start' is relative to (like `lseek').  *)
  l_start:longint;    (* Offset where the lock begins.  *)
  l_len:longint;      (* Size of the locked area; zero means until EOF.  *)
  l_pid:longint;      (* Process holding the lock.  *)
end;

(* для интерфейса сокетов *)
in_addr=record
  s_addr:cardinal;
end;
pin_addr=^in_addr;
in_addr_t=cardinal;

(* для работы со временем *)
tm=record
  tm_sec:longint;         (* seconds *)
  tm_min:longint;         (* minutes *)
  tm_hour:longint;        (* hours *)
  tm_mday:longint;        (* day of the month *)
  tm_mon:longint;         (* month *)
  tm_year:longint;        (* year *)
  tm_wday:longint;        (* day of the week *)
  tm_yday:longint;        (* day in the year *)
  tm_isdst:longint;       (* daylight saving time *)
end;
ptm=^tm;



TFILE=record
  _flags:integer;		(* High-order word is _IO_MAGIC; rest is flags. *)

  (* The following pointers correspond to the C++ streambuf protocol. *)
  (* Note:  Tk uses the _IO_read_ptr and _IO_read_end fields directly. *)
  _IO_read_ptr:pchar;	(* Current read pointer *)
  _IO_read_end:pchar;	(* End of get area. *)
  _IO_read_base:pchar;	(* Start of putback+get area. *)
  _IO_write_base:pchar;	(* Start of put area. *)
  _IO_write_ptr:pchar;	(* Current put pointer. *)
  _IO_write_end:pchar;	(* End of put area. *)
  _IO_buf_base:pchar;	(* Start of reserve area. *)
  _IO_buf_end:pchar;	(* End of reserve area. *)
  (* The following fields are used to support backing up and undo. *)
  _IO_save_base:pchar; (* Pointer to start of non-current get area. *)
  _IO_backup_base:pchar;  (* Pointer to first valid character of backup area *)
  _IO_save_end:pchar; (* Pointer to end of non-current get area. *)

  _markers:P_IO_marker;

  _chain:^TFILE;

  _fileno:integer;
  _blksize:integer;
  _old_offset:longint; (* This used to be _offset but it's too small.  *)

  _cur_column:word;
  _vtable_offset:byte;
  _shortbuf:array[1..1]of char;

  _lock:pointer;
end;

var
  stdin,stdout:pfile;

function tmpfile:pfile;cdecl;external 'c';

(* Generate a temporary filename.  *)
function tmpnam(__s:pchar):pchar;cdecl;external 'c';

(* Close STREAM.  *)
function fclose(__stream:pfile):integer;cdecl;external 'c';

(* Flush STREAM, or all streams if STREAM is NULL.  *)
function fflush (__stream:pfile):integer;cdecl;external 'c';

(* Close all streams.  *)
function fcloseall:integer;cdecl;external 'c';

(* Open a file and create a new stream for it.  *)
function fopen(fname:pchar;mode:pchar):pfile;cdecl;external 'c';

(* Open a file by fd and create a new stream for it.  *)
function fdopen(fildes:longint;mode:pchar):pfile;cdecl;external 'c';
 
(* Open a file, replacing an existing stream with it. *)
function freopen (_filename:pchar;__modes:pchar;__stream:pfile):pfile;cdecl;external 'c';

(* Create a new stream that refers to a memory buffer.  *)
function fmemopen(__s:pointer;__len:longint;__modes:pchar):pfile;cdecl;external 'c';

(* Open a stream that writes into a malloc'd buffer that is expanded as
   necessary.  *BUFLOC and *SIZELOC are updated with the buffer's location
   and the number of characters written on fflush or fclose.  *)
function open_memstream(__bufloc:ppchar;__sizeloc:plongint):pfile;cdecl;external 'c';

(* If BUF is NULL, make STREAM unbuffered.
   Else make it use buffer BUF, of size BUFSIZ.  *)
procedure setbuf(__stream:pfile;__buf:pchar);cdecl;external 'c';

(* Make STREAM use buffering mode MODE.
   If BUF is not NULL, use N bytes of it for buffering;
   else allocate an internal buffer N bytes long.  *)
function setvbuf(__stream:pfile;__buf:pchar;
                 __modes:longint;__n:longint):integer;cdecl;external 'c';

(* If BUF is NULL, make STREAM unbuffered.
   Else make it use SIZE bytes of BUF for buffering.  *)
procedure setbuffer(__stream:pfile;__buf:pchar;
		    __size:longint);cdecl;external 'c';

(* Make STREAM line-buffered.  *)
procedure setlinebuf(__stream:pfile);cdecl;external 'c';

(* Write formatted output to STREAM.  *)
function fprintf(__stream:pfile;fm:pchar;args:array of const):integer;cdecl;external 'c';

(* Write formatted output to stdout.  *)
function printf(fm:pchar;args:array of const):integer;cdecl;external 'c';

(* Write formatted output to S.  *)
function sprintf(__s:pchar;fm:pchar;args:array of const):integer;cdecl;external 'c';

(* Read formatted input from STREAM.  *)
function fscanf(__stream:pfile;fm:pchar;args:array of const):integer;cdecl;external 'c';

(* Read formatted input from stdin.  *)
function scanf(fm:pchar;args:array of const):integer;cdecl;external 'c';

(* Read formatted input from S.  *)
function sscanf(s:pchar;fm:pchar;args:array of const):integer;cdecl;external 'c';

(* Read a character from STREAM.  *)
function fgetc(__stream:pfile):integer;cdecl;external 'c';
function getc(__stream:pfile):integer;cdecl;external 'c';

(* Read a character from stdin.  *)
function getchar:integer;cdecl;external 'c';

(* These are defined in POSIX.1:1996.  *)
function getc_unlocked(__stream:pfile):integer;cdecl;external 'c';
function getchar_unlocked:integer;cdecl;external 'c';

(* Faster version when locking is not necessary.  *)
function fgetc_unlocked(__stream:pfile):integer;cdecl;external 'c';

(* Write a character to STREAM.  *)
function fputc(__c:integer;__stream:pfile):integer;cdecl;external 'c';
function putc(__c:integer;__stream:pfile):integer;cdecl;external 'c';

(* Write a character to stdout.  *)
function putchar(__c:integer):integer;cdecl;external 'c';

(* Faster version when locking is not necessary.  *)
function fputc_unlocked(__c:integer;__stream:pfile):integer;cdecl;external 'c';

(* These are defined in POSIX.1:1996.  *)
function putc_unlocked(__c:integer;__stream:pfile):integer;cdecl;external 'c';
function putchar_unlocked(__c:integer):integer;cdecl;external 'c';

(* Get a word (int) from STREAM.  *)
function getw(__stream:pfile):integer;cdecl;external 'c';

(* Write a word (int) to STREAM.  *)
function putw(__w:integer;__stream:pfile):integer;cdecl;external 'c';

(* Get a newline-terminated string of finite length from STREAM.  *)
function fgets(__s:pchar;__n:integer;__stream:pfile):pchar;cdecl;external 'c';

(* This function does the same as `fgets' but does not lock the stream.  *)
function fgets_unlocked(__s:pchar;__n:integer;__stream:pfile):pchar;cdecl;external 'c';

(* Get a newline-terminated string from stdin, removing the newline.
   DO NOT USE THIS FUNCTION!!  There is no limit on how much it will read.  *)
function gets(__s:pchar):pchar;cdecl;external 'c';

(* Read up to (and including) a DELIMITER from STREAM into *LINEPTR
   (and null-terminate it). *LINEPTR is a pointer returned from malloc (or
   NULL), pointing to *N characters of space.  It is realloc'd as
   necessary.  Returns the number of characters read (not including the
   null terminator), or -1 on error or EOF.  *)
function __getdelim(__lineptr:ppchar;__n:plongint;__delimiter:integer;
			       __stream:pfile):integer;cdecl;external 'c';
function getdelim(__lineptr:ppchar;__n:plongint;__delimiter:integer;
			       __stream:pfile):integer;cdecl;external 'c';

(* Like `getdelim', but reads up to a newline.  *)
function getline(__lineptr:ppchar;__n:plongint;
			       __stream:pfile):integer;cdecl;external 'c';

(* Write a string to STREAM.  *)
function fputs(__s:pchar;__stream:pfile):integer;cdecl;external 'c';

(* This function does the same as `fputs' but does not lock the stream.  *)
function fputs_unlocked(__s:pchar;__stream:pfile):integer;cdecl;external 'c';

(* Write a string, followed by a newline, to stdout.  *)
function puts(__s:pchar):integer;cdecl;external 'c';

(* Push a character back onto the input buffer of STREAM.  *)
function ungetc(__c:integer;__stream:pfile):integer;cdecl;external 'c';

(* Read chunks of generic data from STREAM.  *)
function fread(__ptr:pointer;__size, n:longint;
		     __stream:pfile):longint;cdecl;external 'c';
		     
(* Write chunks of generic data to STREAM.  *)
function fwrite(__ptr:pointer;__size, n:longint;
		     __stream:pfile):longint;cdecl;external 'c';

(* Faster versions when locking is not necessary.  *)
function fread_unlocked(__ptr:pointer;__size, n:longint;
		     __stream:pfile):longint;cdecl;external 'c';
function fwrite_unlocked(__ptr:pointer;__size, n:longint;
		     __stream:pfile):longint;cdecl;external 'c';

(* Seek to a certain position on STREAM.  *)
function fseek(__stream:pfile;__off:longint;__whence:integer):longint;cdecl;external 'c';

(* Return the current position of STREAM.  *)
function ftell(__stream:pfile):longint;cdecl;external 'c';

(* Rewind to the beginning of STREAM.  *)
procedure rewind(__stream:pfile);cdecl;external 'c';

(* Clear the error and EOF indicators for STREAM.  *)
procedure clearerr(__stream:pfile);cdecl;external 'c';

(* Return the EOF indicator for STREAM.  *)
function feof(__stream:pfile):integer;cdecl;external 'c';

(* Return the error indicator for STREAM.  *)
function ferror(__stream:pfile):integer;cdecl;external 'c';

(* Faster versions when locking is not required.  *)
procedure clearerr_unlocked(__stream:pfile);cdecl;external 'c';
function feof_unlocked(__stream:pfile):integer;cdecl;external 'c';
function ferror_unlocked(__stream:pfile):integer;cdecl;external 'c';

(* Print a message describing the meaning of the value of errno.  *)
procedure perror(__s:pchar);cdecl;external 'c';

(* Return the system file descriptor for STREAM.  *)
function fileno(__stream:pfile):longint;cdecl;external 'c';

(* Faster version when locking is not required.  *)
function fileno_unlocked(__stream:pfile):integer;cdecl;external 'c';

(* Create a new stream connected to a pipe running the given command.  *)
function pipeopen(__command, __modes:pchar):pfile;cdecl;external 'c' name 'popen';

(* Close a stream opened by popen and return the status of its child.  *)
function pipeclose (__stream:pfile):integer;cdecl;external 'c' name 'pclose';

(* Return the name of the controlling terminal.  *)
function ctermid(__s:pchar):pchar;cdecl;external 'c';

(* Return the name of the current user.  *)
function cuserid(__s:pchar):pchar;cdecl;external 'c';

(* Acquire ownership of STREAM.  *)
procedure flockfile(__stream:pfile);cdecl;external 'c';

(* Try to acquire ownership of STREAM but do not block if it is not
   possible.  *)
function ftrylockfile(__stream:pfile):integer;cdecl;external 'c';

(* Relinquish the ownership granted for STREAM.  *)
procedure funlockfile(__stream:pfile);cdecl;external 'c';

(* создание файла *)
function fdCreat(PathName:Pchar;mode:longint):longint;cdecl;external 'c' name 'creat';

(* "перемотка" указателя на первый элемент каталога *)
procedure rewinddir(dp:pdir);cdecl;external 'c';

(* ожидание завершения процесса *)
function wait(__stat_loc:pinteger):longint;cdecl;external 'c';

(* функции для создания нового процесса с переменным числом параметров *)
function linuxexecl(path:pchar;arg0:pchar;args:array of const):integer;cdecl;external 'c' name 'execl';
function linuxexeclp(filename:pchar;arg0:pchar;args:array of const):integer;cdecl;external 'c' name 'execlp';

(* функции для определения состояния завершения процесса *)
function WEXITSTATUS(status:integer):integer;
function WSTOPSIG(status:integer):integer;
function WTERMSIG(status:integer):integer;

function WCOREDUMP(status:integer):boolean;
function WIFEXITED(status:integer):boolean;
function WIFSIGNALED(status:integer):boolean;
function WIFSTOPPED(status:integer):boolean;

(* приостанавливает текущий процесс на заданное количество секунд *)
function sleep(seconds:word):word;cdecl;external 'c';

(* удаляет все сигналы из набора сигналов  *)
function sigemptyset(__set:psigset_t):integer;cdecl;external 'c';

(* устанавливает все сигналы в наборе сигналов  *)
function sigfillset(__set:psigset_t):integer;cdecl;external 'c';

(* добавляет сигнал SIGNO в набор сигналов *)
function sigaddset(__set:psigset_t;__signo:integer):integer;cdecl;external 'c';

(* удаляет сигнал SIGNO из набора сигналов *)
function sigdelset(__set:psigset_t;__signo:integer):integer;cdecl;external 'c';

(* возвращает истину, если SIGNO в наборе, и ложь в противном случае *)
function sigismember(__set:psigset_t;__signo:integer):boolean;cdecl;external 'c';

(* возвращает истинное значение, если набор сигналов не пуст *)
function sigisemptyset(__set:psigset_t):boolean;cdecl;external 'c';

(* создает новый набор сигналов из двух входных с помощью логического "И" *)
function sigandset(__set, __left, __right:psigset_t):integer;cdecl;external 'c';

(* создает новый набор сигналов из двух входных с помощью логического "ИЛИ" *)
function sigorset(__set, __left, __right:psigset_t):integer;cdecl;external 'c';

(* набор функций для нелокальных переходов *)

(* Store the calling environment in ENV, also saving the signal mask.
   Return 0.  *)
function setjmp(var __env:jmp_buf):integer;cdecl;external 'c';

(* Store the calling environment in ENV, not saving the signal mask.
   Return 0.  *)
function _setjmp(var __env:jmp_buf):integer;cdecl;external 'c';

(* Store the calling environment in ENV, also saving the
   signal mask if SAVEMASK is nonzero.  Return 0.  *)
function sigsetjmp(var __env:jmp_buf;__savemask:longint):integer;cdecl;external 'c' name '__sigsetjmp';

(* Jump to the environment saved in ENV, making the
   `setjmp' call there return VAL, or 1 if VAL is 0.  *)
procedure longjmp(var __env:jmp_buf;__val:integer);cdecl;external 'c';

(* Jump to the environment saved in ENV, making the
   sigsetjmp call there return VAL, or 1 if VAL is 0.
   Restore the signal mask if that sigsetjmp call saved it.
   This is just an alias `longjmp'.  *)
procedure siglongjmp(var __env:jmp_buf;__val:integer);cdecl;external 'c';

(* fpathconf, pathconf - get configuration values for files *)
function fpathconf(filedes,name:longint):longint;cdecl;external 'c';
function pathconf(path:pchar;name:longint):longint;cdecl;external 'c';
function sysconf(name:integer):longint;cdecl;external 'c';

(* setpgid, getpgid, setpgrp, getpgrp - set/get process group *)
function setpgid(pid, pgid:longint):longint;cdecl;external 'c';
function getpgid(pid:longint):longint;cdecl;external 'c';
function setpgrp:longint;cdecl;external 'c';
function getpgrp:longint;cdecl;external 'c';
function getsid(pid:longint):longint;cdecl;external 'c';
function setsid:longint;cdecl;external 'c';

(* grantpt - grant access to the slave pseudotty*)
function grantpt(fd:longint):longint;cdecl;external 'c';

(* unlockpt - unlock a pseudotty master/slave pair*)
function unlockpt(fd:longint):longint;cdecl;external 'c';

(* ptsname - get the name of the slave pseudotty*)
function ptsname(fd:longint):pchar;cdecl;external 'c';

(* inet_aton() converts the Internet host address  cp  from  the  standard                            
   numbers-and-dots  notation into binary data and stores it in the structure 
   that inp points to. inet_aton returns nonzero if  the  address  is                                          
   valid, zero if not.*)
function inet_aton(cp:pchar; inp:pin_addr):longint;cdecl;external 'c';

(* The  inet_addr()  function  converts  the Internet host address cp from        
   numbers-and-dots notation into binary data in network byte  order.   If               
   the input is invalid, INADDR_NONE (usually -1) is returned.  This is an                      
   obsolete interface to inet_aton, described  immediately  above;  it  is                             
   obsolete because -1 is a valid address (255.255.255.255), and inet_aton                                    
   provides a cleaner way to indicate error return. *)
function inet_addr(cp:pchar):in_addr_t;cdecl;external 'c';

(* The inet_network() function extracts the network number  in  host  byte
   order  from  the address cp in numbers-and-dots notation.  If the input
   is invalid, -1 is returned. *)
function inet_network(cp:pchar):in_addr_t;cdecl;external 'c';

(* The inet_ntoa() function converts the Internet host address in given in
   network  byte  order to a string in standard numbers-and-dots notation.
   The string is returned in a statically allocated buffer,  which  subse-
   quent calls will overwrite. *)
function inet_ntoa(n:in_addr):pchar;cdecl;external 'c';

(* The  inet_makeaddr() function makes an Internet host address in network
   byte order by combining the network number net with the  local  address
   host in network net, both in local host byte order. *)
function inet_makeaddr(net, host:longint):in_addr;cdecl;external 'c';

(* The  inet_lnaof()  function  returns the local host address part of the
   Internet address in.  The local host address is returned in local  host
   byte order. *)
function inet_lnaof(n:in_addr):in_addr_t;cdecl;external 'c';
       
(* The inet_netof() function returns the network number part of the Inter-
   net Address in.  The network number is  returned  in  local  host  byte
   order. *)
function inet_netof(n:in_addr):in_addr_t;cdecl;external 'c';
            
(* sendto - отправить сообщение в сокет.
   send, sendto, и sendmsg используются для пересылки сообщений на  другой
   сокет.    send  можно  использовать,  только  если  сокет  находится  в
   соединенном состоянии, тогда как sendto и sendmsg можно использовать  в
   любое время. *)
function sendto(sock:longint;var addr;addrlen,flags:longint;
                var sato:tsockaddr;tolen:longint):longint;cdecl;external 'c';
                
(* recvfrom используется для получения сообщений из сокета, и может 
   использоваться для получения данных, независимо от того, является ли 
   сокет ориентированным на соединения или нет. *)
function recvfrom(sock:longint;var addr;addrlen,flags:longint;
                  var from:tsockaddr;var fromlen:longint):longint;cdecl;external 'c';

(* character classification routines *)
function isalnum(c:integer):boolean;cdecl;external 'c';
function isalpha(c:integer):boolean;cdecl;external 'c';
function isascii(c:integer):boolean;cdecl;external 'c';
function isblank(c:integer):boolean;cdecl;external 'c';
function iscntrl(c:integer):boolean;cdecl;external 'c';
function isdigit(c:integer):boolean;cdecl;external 'c';
function isgraph(c:integer):boolean;cdecl;external 'c';
function islower(c:integer):boolean;cdecl;external 'c';
function isprint(c:integer):boolean;cdecl;external 'c';
function ispunct(c:integer):boolean;cdecl;external 'c';
function isupper(c:integer):boolean;cdecl;external 'c';
function isxdigit(c:integer):boolean;cdecl;external 'c';
function isspace(c:integer):boolean;
function tolower(c:integer):integer;cdecl;external 'c';
function _tolower(c:integer):integer;cdecl;external 'c';
function toupper(c:integer):integer;cdecl;external 'c';
function _toupper(c:integer):integer;cdecl;external 'c';
function toascii(c:integer):integer;cdecl;external 'c';

(* transform date and time to broken-down time or ASCII *)

(* The ctime(), gmtime() and localtime() functions all take an argument of
   data  type  time_t which represents calendar time.  When interpreted as
   an absolute time value, it represents the  number  of  seconds  elapsed
   since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC). *)
function ctime(var t:longint):pchar;cdecl;external 'c';
function ctime_r(var timep:longint;buf:pchar):pchar;cdecl;external 'c';
function gmtime(var timep:longint):ptm;cdecl;external 'c';
function gmtime_r(var timep:longint; result:ptm):ptm;cdecl;external 'c';
function localtime(var timep:longint):ptm;cdecl;external 'c';
function localtime_r(var timep:longint; result:ptm):ptm;cdecl;external 'c';

(* The asctime() and mktime() functions both take an argument representing
   broken-down time which is a representation separated into year,  month,
   day, etc. *)
function asctime(const t:ptm):pchar;cdecl;external 'c';
function asctime_r(const t:ptm;buf:pchar):pchar;cdecl;external 'c';
function mktime(t:ptm):longint;cdecl;external 'c';
function difftime(time1, time2:longint):double;cdecl;external 'c';

(* функции для работы с памятью *)
function calloc(nmemb, size:longint):pointer;cdecl;external 'c';
function malloc(size:longint):pointer;cdecl;external 'c';
procedure free(ptr:pointer);cdecl;external 'c';
function realloc(ptr:pointer; size:longint):pointer;cdecl;external 'c';
 
(* функции для работы с каталогами *)
function mkdir(pathname:pchar;mode:integer):integer;cdecl;external 'c';
function rmdir(pathname:pchar):integer;cdecl;external 'c';
function chdir(path:pchar):integer;cdecl;external 'c';
function getcwd(name:pchar; size:longint):pchar;cdecl;external 'c';

(* работа с буферами *)
procedure sync;cdecl;external 'c';
function fsync(filedes:integer):integer;cdecl;external 'c';

(* выполнение команды shell'а *)
function runshell(__commandline:pchar):longint;cdecl;external 'c' name 'system';

(* уничтожение вызвавшего процесса *)
procedure _exit(status:longint);cdecl;external 'c';

(* изменение или расширение окружения *)
function putenv(str:pchar):longint;cdecl;external 'c';

(* смена корневого каталога *)
function chroot(path:pchar):longint;cdecl;external 'c';

(* установка реальных и действующих идентификаторов пользователя и группы *)
function setuid(uid:longint):longint;cdecl;external 'c';
function setgid(gid:longint):longint;cdecl;external 'c';

(* узнать или изменить ограничения процесса *)
function ulimit(cmd:longint;args:array of const):longint;cdecl;external 'c';

(* аварийное завершение процесса *)
function abort:longint;cdecl;external 'c';

(* Получить скорость ввода *)
function cfgetispeed(var tdes:TermIOS):longint;cdecl;external 'c';

(* Получить скорость вывода *)
function cfgetospeed(var tdes:TermIOS):longint;cdecl;external 'c';

(* используется для посылки сигнала прерывания сеанса связи *)
Function tcsendbrk(ttyfd, duration:longint):longint;cdecl;external 'c';

(* функции для работы с памятью *)
function memset(buf:pointer; character:longint; size:longint):pointer;cdecl;external 'c';
function memcpy(buf1:pointer; const buf2:pointer; size:longint):pointer;cdecl;external 'c';
function memmove(buf1:pointer; const buf2:pointer; size:longint):pointer;cdecl;external 'c';
function memcmp(const buf1, buf2:pointer; size:longint):longint;cdecl;external 'c';
function memchr(const buf:pointer; character:longint; size:longint):pointer;cdecl;external 'c';


(* функции для работы со строками *)
function strpbrk(const s1, s2:pchar):pchar;cdecl;external 'c';
function strspn(const s1, s2:pchar):longint;cdecl;external 'c';
function strcspn(const s1, s2:pchar):longint;cdecl;external 'c';
function strtok(s1:pchar; const s2:pchar):pchar;cdecl;external 'c';

function strtol(const str:pchar; endptr:ppchar; base:longint):longint;cdecl;external 'c';
function atoi(const str:pchar):longint;cdecl;external 'c';
function atol(const str:pchar):longint;cdecl;external 'c';
function strtod(const str:pchar; endptr:ppchar):double;cdecl;external 'c';
function atof(const str:pchar):double;cdecl;external 'c';


                                    
implementation

(* If WIFEXITED(STATUS), the low-order 8 bits of the status.  *)
function WEXITSTATUS(status:integer):integer;
begin
  WEXITSTATUS:=(status and $ff00) shr 8;
end;

(* If WIFSTOPPED(STATUS), the signal that stopped the child.  *)
function WSTOPSIG(status:integer):integer;
begin
  WSTOPSIG:=WEXITSTATUS(status);
end;

(* If WIFSIGNALED(STATUS), the terminating signal.  *)
function WTERMSIG(status:integer):integer;
begin
  WTERMSIG:=status and $7f;
end;

(* Nonzero if STATUS indicates the child dumped core.  *)
function WCOREDUMP(status:integer):boolean;
begin
  WCOREDUMP:=(status and WCOREFLAG) = 0;
end;


(* Nonzero if STATUS indicates normal termination.  *)
function WIFEXITED(status:integer):boolean;
begin
  WIFEXITED:=(status and $7f) = 0;
end;

(* If WIFSIGNALED(STATUS), the terminating signal.  *)
function WIFSIGNALED(status:integer):boolean;
begin
  WIFSIGNALED:=(not WIFSTOPPED(status)) and (not WIFEXITED(status));
end;

(* Nonzero if STATUS indicates the child is stopped.  *)
function WIFSTOPPED(status:integer):boolean;
begin
  WIFSTOPPED:=(status and $ff) = $7f;
end;

(* test on space character: space, CR, LF, Tab, VTab, FF *)
function isspace(c:integer):boolean;
begin
  isspace:=c in [$9,$20,$a,$b,$c,$d];
end;


begin
  stdin:=fdopen(0,'r');
  stdout:=fdopen(1,'w');
end.
