10. I/O
10.1. File system manipulation
- Method
access
intaccess(stringpath,string|voidmode)- Description
access() checks if the calling process can access the file
path. Symbolic links are dereferenced.- Parameter
mode The
modespecifies the accessibility checks to be performed, and is either not specified or empty, in which case access() just tests if the file exists, or one or more of the characters"rwx".r, w, and x test whether the file exists and grants read, write, and execute permissions, respectively.
The check is done using the calling process's real UID and GID, rather than the effective IDs as is done when actually attempting an operation (e.g., open(2)) on the file. This allows set-user-ID programs to easily determine the invoking user's authority.
If the calling process is privileged (i.e., its real UID is zero), then an X_OK check is successful for a regular file if execute permission is enabled for any of the file owner, group, or other.
- Returns
1When the file is accessible using the given permissions.
0When the file is not accessible, in which case
errnois set to one of the following values:EACCESSAccess denied.
ELOOPToo many symbolic links.
ENAMETOOLONGThe path is too long.
ENOENTThe file does not exist.
ENOTDIROne of the directories used in
pathis not, in fact, a directory.EROFSThe filesystem is read only and write access was requested.
Other errors can occur, but are not directly related to the requested path, such as
ENOMEM, etc.- See also
errno(),Stdio.File
- Method
cd
intcd(strings)- Description
Change the current directory for the whole Pike process.
- Returns
Returns
1for success,0(zero) otherwise.- See also
getcwd()
- Method
get_dir
array(string) get_dir(void|stringdirname)- Description
Returns an array of all filenames in the directory
dirname, or0(zero) if the directory does not exist. When nodirnameis given, current work directory is used.- See also
mkdir(),cd()
- Method
mkdir
intmkdir(stringdirname,void|intmode)- Description
Create a directory.
If
modeis specified, it's will be used for the new directory after being&'ed with the current umask (on OS'es that support this).- Returns
Returns
0(zero) on failure,1otherwise.- See also
rm(),cd(),Stdio.mkdirhier()
- Method
cp
intcp(stringfrom,stringto)- Description
Copies the file
fromto the new positionto. This is an alias forStdio.cp.
- Method
mv
intmv(stringfrom,stringto)- Description
Rename or move a file or directory.
If the destination already exists, it will be replaced. Replacement often only works if
tois of the same type asfrom, i.e. a file can only be replaced by another file and so on. Also, a directory will commonly be replaced only if it's empty.On some OSs this function can't move directories, only rename them.
- Returns
Returns
0(zero) on failure,1otherwise. Callerrno()to get more error info on failure.- See also
rm()
- Method
rm
intrm(stringf)- Description
Remove a file or directory.
- Returns
Returns
0(zero) on failure,1otherwise.- Note
May fail with
errno()set toSystem.EISDIRorSystem.ENOTDIRif the file has changed to a directory during the call or the reverse.- See also
Stdio.File()->unlinkat(),mkdir(),Stdio.recursive_rm()
- Method
file_truncate
intfile_truncate(stringfile,intlength)- Description
Truncates the file
fileto the length specified inlength.- Returns
Returns 1 if ok, 0 if failed.
10.2. Path manipulation
- Method
basename
stringbasename(stringpath)- Description
Returns the last segment of a path.
- See also
dirname(),explode_path()
- Method
dirname
stringdirname(stringpath)- Description
Returns all but the last segment of a path. Some example inputs and outputs:
Expression Value dirname("/a/b") "/a" dirname("/a/") "/a" dirname("/a") "/" dirname("/") "/" dirname("") "" - See also
basename(),explode_path()
- Method
combine_path
Method combine_path_unix
Method combine_path_nt
Method combine_path_amigaos stringcombine_path(stringpath,string...paths)stringcombine_path_unix(stringpath,string...paths)stringcombine_path_nt(stringpath,string...paths)stringcombine_path_amigaos(stringpath,string...paths)- Description
Concatenate a number of paths to a straightforward path without any
"//","/.."or"/.". If any path argument is absolute then the result is absolute and the preceding arguments are ignored. If the result is relative then it might have leading".."components. If the last nonempty argument ends with a directory separator then the result ends with that too. If all components in a relative path disappear due to subsequent".."components then the result is".".combine_path_unix()concatenates in UNIX style, which also is appropriate for e.g. URL:s ("/" separates path components and absolute paths start with "/").combine_path_nt()concatenates according to NT filesystem conventions ("/" and "\" separates path components and there might be a drive letter in front of absolute paths).combine_path_amigaos()concatenates according to AmigaOS filesystem conventions.combine_path()is equivalent tocombine_path_unix()on UNIX-like operating systems, and equivalent tocombine_path_nt()on NT-like operating systems, and equivalent tocombine_path_amigaos()on AmigaOS-like operating systems.- See also
getcwd(),Stdio.append_path()
- Method
explode_path
array(string) explode_path(stringp)- Description
Split a path
pinto its components.This function divides a path into its components. This might seem like it could be done by dividing the string on <tt>"/"</tt>, but that will not work on some operating systems. To turn the components back into a path again, use
combine_path().
10.3. Status
- Method
file_stat
Stdio.Statfile_stat(stringpath,void|boolsymlink)- Description
Stat a file.
If the argument
symlinkis1symlinks will not be followed.- Returns
If the path specified by
pathdoesn't exist0(zero) will be returned.Otherwise an object describing the properties of
pathwill be returned.- Note
In Pike 7.0 and earlier this function returned an array with 7 elements. The old behaviour can be simulated with the following function:
array(int) file_stat(string path,void|int(0..1) symlink){ File.Stat st = predef::file_stat(path, symlink);if(!st)return 0;return(array(int))st;}- See also
Stdio.Stat,Stdio.File->stat()
- Method
filesystem_stat
mapping(string:int) filesystem_stat(stringpath)- Description
Returns a mapping describing the properties of the filesystem containing the path specified by
path.- Returns
If a filesystem cannot be determined
0(zero) will be returned.Otherwise a mapping(string:int) with the following fields will be returned:
"blocksize":intSize in bytes of the filesystem blocks.
"blocks":intSize of the entire filesystem in blocks.
"bfree":intNumber of free blocks in the filesystem.
"bavail":intNumber of available blocks in the filesystem. This is usually somewhat less than the
"bfree"value, and can usually be adjusted with eg tunefs(1M)."files":intTotal number of files (aka inodes) allowed by this filesystem.
"ffree":intNumber of free files in the filesystem.
"favail":intNumber of available files in the filesystem. This is usually the same as the
"ffree"value, and can usually be adjusted with eg tunefs(1M)."fsname":stringName assigned to the filesystem. This item is not available on all systems.
"fstype":stringType of filesystem (eg
"nfs"). This item is not available on all systems. For some more uncommon filesystems this may be an integer representing the magic number for the filesystem type (cf statfs(2) on eg Linux systems).- Note
Please note that not all members are present on all OSs.
- See also
file_stat()
Class _Stdio.Stat
- Description
This object is used to represent file status information from e.g.
file_stat().It contains the following items usually found in a C struct stat:
- mode
File mode (see mknod(2)).
- size
File size in bytes.
- uid
User ID of the file's owner.
- gid
Group ID of the file's owner.
- atime
Time of last access in seconds since 00:00:00 UTC, 1970-01-01.
- mtime
Time of last data modification.
- ctime
Time of last file status change.
- atime_nsec
Time of last access in nanoseconds, added to atime to get sub-second time
- mtime_nsec
Time of last modification in nanoseconds, added to mtime to get sub-second time
- ctime_nsec
Time of last file status change in nanoseconds, added to ctime to get sub-second time
- ino
Inode number.
- nlink
Number of links.
- dev
ID of the device containing a directory entry for this file.
- rdev
ID of the device.
It also contains some items that correspond to the C IS* macros:
- isreg
Set if the file is a regular file.
- isdir
Set if the file is a directory.
- islnk
Set if the file is a symbolic link. Note that symbolic links are normally followed by the stat functions, so this might only be set if you turn that off, e.g. by giving a nonzero second argument to
file_stat().- isfifo
Set if the file is a FIFO (aka named pipe).
- issock
Set if the file is a socket.
- ischr
Set if the file is a character device.
- isblk
Set if the file is a block device.
There are also some items that provide alternative representations of the above:
- type
The type as a string, can be any of
"reg","dir","lnk","fifo","sock","chr","blk", and"unknown".- mode_string
The file mode encoded as a string in ls -l style, e.g.
"drwxr-xr-x".
Note that some items might not exist or have meaningful values on some platforms.
Additionally, the object may be initialized from or casted to an
arrayon the form of a 'traditional' LPC stat-array, and it's also possible to index the object directly with integers as if it were such an array. The stat-array has this format:Array int0File mode, same as mode.
int1If zero or greater, the file is a regular file and this is its size in bytes. If less than zero it gives the type: -2=directory, -3=symlink and -4=device.
int2Time of last access, same as atime.
int3Time of last data modification, same as mtime.
int4Time of last file status change, same as ctime.
int5User ID of the file's owner, same as uid.
int6Group ID of the file's owner, same as gid.
It's possible to modify the stat struct by assigning values to the items. They essentially work as variables, although some of them affect others, e.g. setting
isdirclearsisregand settingmode_stringchanges many of the other items.
- Method
_equal
boolequal(_Stdio.Statfrom,mixedother)- Description
Compare this object with another
Statobject.- Returns
Returns
1ifotheris aStatobject with the same content, and0(zero) otherwise.
- Method
cast
(mapping(string:int))_Stdio.Stat()
(array)_Stdio.Stat()- Description
Convert the stat object to a mapping or array.
- Method
create
_Stdio.Stat_Stdio.Stat(void|object|arraystat)- Description
A new
Stdio.Statobject can be initialized in two ways:statis an object, typically anotherStdio.Stat. The stat info is copied from the object by getting the values ofmode,size,atime,mtime,ctime,uid,gid,dev,ino,nlink, andrdev.statis a seven element array on the 'traditional' LPC stat-array form (see the class doc).
10.4. Error handling
- Method
errno
System.Errnoerrno()- Description
This function returns the system error from the last file operation.
- Note
Note that you should normally use
Stdio.File->errno()instead.- See also
Stdio.File->errno(),strerror(),System.Errno
- Method
strerror
stringstrerror(System.Errnoerrno)- Description
This function returns a description of an error code. The error code is usually obtained from eg
Stdio.File->errno().- Note
On some platforms the string returned can be somewhat nondescriptive.
- See also
System.Errno,errno(),Stdio.File->errno()
10.5. Files and sockets
Class Stdio.File
- Annotations
@Pike.Annotations.Implements(NonblockingStream)@Pike.Annotations.Implements(BlockFile)- Description
This is the basic I/O object, it provides socket and pipe communication as well as file access. It does not buffer reads and writes by default, and provides no line-by-line reading, that is done with
Stdio.FILEobject.- Note
The file or stream will normally be closed when this object is destructed (unless there are more objects that refer to the same file through use of
assignordup). Objects do not contain cyclic references in themselves, so they will be destructed timely when they run out of references.- See also
Stdio.FILE
- Method
assign
intassign(File|Fdo)- Description
This function takes a clone of Stdio.File and assigns all variables of this file from it. It can be used together with
dup()to move files around.- See also
dup()
- Method
async_connect
intasync_connect(string(7bit)host,int|string(7bit)port,function(int,__unknown__... :void)callback,mixed...args)- Description
Open a TCP/IP connection asynchronously.
This function is similar to
connect(), but works asynchronously.- Parameter
host Hostname or IP to connect to.
- Parameter
port Port number or service name to connect to.
- Parameter
callback Function to be called on completion. The first argument will be
1if a connection was successfully established, and0(zero) on failure. The rest of the arguments tocallbackare passed verbatim fromargs.- Parameter
args Extra arguments to pass to
callback.- Returns
Returns
0on failure to open a socket, and1ifcallbackwill be used.- Note
The socket may be opened with
open_socket()ahead of the call to this function, but it is not required.- Note
This object is put in callback mode by this function. For
callbackto be called, the backend must be active. See e.g.set_read_callbackfor more details about backends and callback mode.- Note
The socket will be in nonblocking state if the connection is successful, and any callbacks will be cleared.
- See also
connect(),open_socket(),set_nonblocking()
- Method
async_connect
variantConcurrent.Future(<this_program>) async_connect(string(7bit)host,int|string(7bit)port)- Description
Opens a TCP connection asynchronously using a Concurrent Future object.
- Parameter
host Hostname or IP to connect to.
- Parameter
port Port number or service name to connect to.
- Returns
Returns a
Concurrent.Futurethat resolves into the connection object at success.
- Method
close
intclose()intclose(string(7bit)direction)- Description
Close the file. Optionally, specify "r", "w" or "rw" to close just the read, just the write or both read and write directions of the file respectively.
An exception is thrown if an I/O error occurs.
- Returns
Nonzero is returned if the file wasn't open in the specified direction, zero otherwise.
- Note
This function will not call the close_callback.
- See also
open,open_socket
- Method
connect
variantintconnect(string(7bit)host,int(0..)|string(7bit)port)variantintconnect(string(7bit)host,int(0..)|string(7bit)port,string(7bit)client,int(0..)|string(7bit)client_port)variantstringconnect(string(7bit)host,int(0..)|string(7bit)port,string(8bit)data)variantstring|zeroconnect(string(7bit)host,int(0..)|string(7bit)port,int(0)|string(7bit)client,int(0..)|string(7bit)client_port,string(8bit)data)- Description
Open a TCP/IP connection to the specified destination.
In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.
The
hostargument is the hostname or IP number of the remote machine.A local IP and port can be explicitly bound by specifying
clientandclient_port.If the
dataargument is included the socket will use TCP_FAST_OPEN if posible. In this mode the the function will return the part of the data that has not been sent to the remote server yet instead of 1 (you will have to usewriteto send this data).Note that TCP_FAST_OPEN requires server support, the connection might fail even though the remote server exists. It might be advisable to retry without TCP_FAST_OPEN (and remember this fact)
- Returns
This function returns
1or the remainingdatafor success,0otherwise.- Note
To use nonblocking mode,
open_socket()andset_nonblocking()(or equivalent) need to be called before this function.- Note
In nonblocking mode
0(zero) may be returned anderrno()set toEWOULDBLOCKorWSAEWOULDBLOCK.This should not be regarded as a connection failure. In nonblocking mode you need to wait for a write or close callback before you know if the connection failed or not.
- See also
query_address(),async_connect(),connect_unix(),open_socket(),::connect()
- Method
connect_unix
intconnect_unix(string(8bit)path)- Description
Open a UNIX domain socket connection to the specified destination.
- Returns
Returns
1on success, and0on failure.- Note
Nonblocking mode is not supported while connecting
- Method
create
Stdio.FileStdio.File()Stdio.FileStdio.File(string(8bit)filename)Stdio.FileStdio.File(string(8bit)filename,string(7bit)mode)Stdio.FileStdio.File(string(8bit)filename,string(7bit)mode,intmask)Stdio.FileStdio.File(string(8bit)descriptorname)Stdio.FileStdio.File(intfd)Stdio.FileStdio.File(intfd,string(7bit)mode)- Description
There are four basic ways to create a Stdio.File object. The first is calling it without any arguments, in which case the you'd have to call
open(),connect()or some other method which connects the File object with a stream.The second way is calling it with a
filenameand openmode. This is the same thing as cloning and then callingopen(), except shorter and faster.The third way is to call it with
descriptornameof"stdin","stdout"or"stderr". This will open the specified standard stream.For the advanced users, you can use the file descriptors of the systems (note: emulated by pike on some systems - like NT). This is only useful for streaming purposes on unix systems. This is not recommended at all if you don't know what you're into. Default
modefor this is"rw".- Note
Open mode will be filtered through the system UMASK. You might need to use
chmod()later.- See also
open(),connect(),Stdio.FILE,
- Method
dup
Filedup()- Description
This function returns a clone of Stdio.File with all variables copied from this file.
- Note
All variables, even id, are copied.
- See also
assign()
- Method
errno
interrno()- Description
Returns the error code for the last command on this file. Error code is normally cleared when a command is successful.
- Method
line_iterator
String.SplitIterator|LineIteratorline_iterator(int|voidtrim)- Description
Returns an iterator that will loop over the lines in this file. If trim is true, all '\r' characters will be removed from the input.
- Method
open
intopen(string(8bit)filename,string(7bit)mode)intopen(string(8bit)filename,string(7bit)mode,intmask)- Description
Open a file for read, write or append. The parameter
modeshould contain one or more of the following letters:"r"Open file for reading.
"w"Open file for writing.
"a"Open file for append (use with
"w")."t"Truncate file at open (use with
"w")."c"Create file if it doesn't exist (use with
"w")."x"Fail if file already exists (use with
"c").modeshould always contain at least one of the letters"r"or"w".The parameter
maskis protection bits to use if the file is created. Default is0666(read+write for all in octal notation).- Returns
This function returns
1for success,0otherwise.- See also
close(),create()
- Method
open_socket
intopen_socket(int|string(8bit)|voidport,string(7bit)|voidaddress,int|string(8bit)|voidfamily_hint)- Description
This makes this file into a socket ready for connections. The reason for this function is so that you can set the socket to nonblocking or blocking (default is blocking) before you call
connect().- Parameter
port If you give a port number to this function, the socket will be bound to this port locally before connecting anywhere. This is only useful for some silly protocols like FTP. The port can also be specified as a string, giving the name of the service associated with the port. Pass -1 to not specify a port (eg to bind only to an address).
- Parameter
address You may specify an address to bind to if your machine has many IP numbers.
- Parameter
family_hint A protocol family for the socket can be specified. If no family is specified, one which is appropriate for the address is automatically selected. Thus, there is normally no need to specify it. If you do not want to specify a bind address, you can provide the address as a hint here instead, to allow the automatic selection to work anyway.
- Returns
This function returns 1 for success, 0 otherwise.
- See also
connect(),set_nonblocking(),set_blocking()
- Method
openat
Fileopenat(string(8bit)filename)Fileopenat(string(8bit)filename,string(7bit)mode)Fileopenat(string(8bit)filename,string(7bit)mode,intmask)- Description
Open a file relative to an open directory.
- See also
File.statat(),File.unlinkat()
- Method
openpt
intopenpt(string(7bit)mode)- Description
Open the master end of a pseudo-terminal pair. The parameter
modeshould contain one or more of the following letters:"r"Open terminal for reading.
"w"Open terminal for writing.
modeshould always contain at least one of the letters"r"or"w".- See also
grantpt()
- Method
pipe
File|zeropipe(void|intrequired_properties)- Description
This function creates a pipe between the object it was called in and an object that is returned.
- Parameter
required_properties Binary or (
predef::`|()) of requiredPROP_properties.PROP_IPCThe resulting pipe may be used for inter process communication.
PROP_NONBLOCKThe resulting pipe supports nonblocking I/O.
PROP_SHUTDOWNThe resulting pipe supports shutting down transmission in either direction (see
close()).PROP_BUFFEREDThe resulting pipe is buffered (usually 4KB).
PROP_BIDIRECTIONALThe resulting pipe is bi-directional.
PROP_SEND_FDThe resulting pipe might support sending of file descriptors (see
send_fd()andreceive_fd()for details).PROP_TTYThe resulting pipe is a pseudo-tty.
PROP_REVERSEThe resulting pipe supports communication "backwards" (but not necessarily "forwards", see
PROP_BIDIRECTIONAL).The default is
PROP_NONBLOCK|PROP_BIDIRECTIONAL.If
PROP_BIDIRECTIONALisn't specified, the read-end is this object, and the write-end is the returned object (unlessPROP_REVERSEhas been specified, in which case it is the other way around).The two ends of a bi-directional pipe are indistinguishable.
For
PROP_TTYthe returned object is the slave (unlessPROP_REVERSEhas been specified).If the File object this function is called in was open to begin with, it will be closed before the pipe is created.
- Note
Calling this function with an argument of 0 is not the same as calling it with no arguments.
- See also
Process.create_process(),send_fd(),receive_fd(),PROP_IPC,PROP_NONBLOCK,PROP_SEND_FD,PROP_SHUTDOWN,PROP_BUFFERED,PROP_REVERSE,PROP_BIDIRECTIONAL,PROP_TTY
- Method
query_buffer_mode
array(Stdio.Buffer|int(0)) query_buffer_mode()- Description
Get the active input and output buffers that have been set with
set_buffer_mode()(if any).- Returns
Returns an array with two elements:
Array Stdio.Buffer0The current input buffer.
Stdio.Buffer1The current output buffer.
- See also
set_buffer_mode()
- Method
query_read_callback
Method query_write_callback
Method query_read_oob_callback
Method query_write_oob_callback
Method query_close_callback
Method query_callbacks read_callback_tquery_read_callback()write_callback_tquery_write_callback()read_oob_callback_tquery_read_oob_callback()write_oob_callback_tquery_write_oob_callback()close_callback_tquery_close_callback()array(function(mixed,void|string(8bit):int)|zero) query_callbacks()- Description
These functions return the currently installed callbacks for the respective events.
query_callbacksreturns the callbacks in the same order asset_callbacksandset_nonblockingexpect them.- See also
set_nonblocking(),set_read_callback,set_write_callback,set_read_oob_callback,set_write_oob_callback,set_close_callback,set_callbacks
- Method
query_id
mixedquery_id()- Description
This function returns the id that has been set with
set_id().- See also
set_id()
- Method
read
string(8bit)|zeroread(int|voidnbytes,bool|voidnot_all)- Description
Read (optionally buffered) data from a file or a stream.
Proxy function for
Fd::read(), that adds support for the buffering configured byset_buffer_mode()- See also
read_function(),write(),Fd::read()
- Method
read_function
function(:string(8bit)|zero) read_function(intnbytes)- Description
Returns a function that when called will call
readwith nbytes as argument. Can be used to get various callback functions, eg for the fourth argument toString.SplitIterator.
- Method
set_blocking
voidset_blocking()- Description
This function clears all callbacks and sets a stream to blocking mode. i.e. reading, writing and closing will wait until data has been transferred before returning.
- Note
The callbacks are cleared and blocking mode is set in one atomic operation, so no callback gets called in between if the backend is running in another thread.
Even so, if the stream is in callback mode (i.e. if any callbacks are installed) then only the backend thread can use this function reliably; it might otherwise already be running in a callback which is about to call e.g.
writewhen the stream becomes blocking.- See also
set_nonblocking(),set_nonblocking_keep_callbacks(),set_blocking_keep_callbacks()
- Method
set_nonblocking_keep_callbacks
Method set_blocking_keep_callbacks voidset_nonblocking_keep_callbacks()voidset_blocking_keep_callbacks()- Description
Toggle between blocking and nonblocking, without changing the callbacks.
- See also
set_nonblocking(),set_blocking()
- Method
set_buffer_mode
voidset_buffer_mode(Stdio.Buffer|int(0)in,Stdio.Buffer|int(0)out)- Description
Toggle the file to Buffer mode.
In this mode reading and writing will be done via Buffer objects, in the directions you included buffers.
- Parameter
in Input buffer. If this buffer is non-empty, its contents will be returned after any already received data.
- Parameter
out Output buffer. If this buffer is non-empty, its contents will be sent after any data already queued for sending.
- Note
Normally you call
writeto re-trigger the write callback if you do not output anything in it (which will stop it from re-occuring again).This will work with buffered output mode as well, but simply adding more data to the output buffer will work as well.
- See also
query_buffer_mode()
- Method
set_callbacks
voidset_callbacks(read_callback_t|voidread_cb,write_callback_t|voidwrite_cb,close_callback_t|voidclose_cb,read_oob_callback_t|voidread_oob_cb,write_oob_callback_t|voidwrite_oob_cb)- Description
Installs all the specified callbacks at once. Use
UNDEFINEDto keep the current setting for a callback.Like
set_nonblocking, the callbacks are installed atomically. As opposed toset_nonblocking, this function does not do anything with the stream, and it doesn't even have to be open.- See also
set_read_callback,set_write_callback,set_read_oob_callback,set_write_oob_callback,set_close_callback,query_callbacks
- Method
set_read_callback
Method set_write_callback
Method set_read_oob_callback
Method set_write_oob_callback
Method set_close_callback
Method set_fs_event_callback voidset_read_callback(function(mixed,string(8bit):int)|zeroread_cb)voidset_read_callback(function(mixed,Buffer:int)|zeroread_cb)voidset_write_callback(function(mixed:int)|zerowrite_cb)voidset_write_callback(function(mixed,Buffer:int)|zerowrite_cb)voidset_read_oob_callback(function(mixed,string(8bit):int)|zeroread_oob_cb)voidset_write_oob_callback(function(mixed:int)|zerowrite_oob_cb)voidset_close_callback(function(mixed:int)|zeroclose_cb)voidset_fs_event_callback(function(mixed,int:int)|zerofs_event_cb,intevent_mask)- Description
These functions set the various callbacks, which will be called when various events occur on the stream. A zero as argument will remove the callback.
A
Pike.Backendobject is responsible for calling the callbacks. It requires a thread to be waiting in it to execute the calls. That means that only one of the callbacks will be running at a time, so you don't need mutexes between them.Unless you've specified otherwise with the
set_backendfunction, the default backendPike.DefaultBackendwill be used. It's normally activated by returning-1from the main function and will then execute in the main thread.When data arrives on the stream,
read_cbwill be called with some or all of that data as the second argument.If the file is in buffer mode, the second argument will be a Buffer.
This will always be the same buffer, so data you do not use in one read callback can be simply left in the buffer, when new data arrives it will be appended
When the stream has buffer space over for writing,
write_cbwill be called so that you can write more data to it.This callback is also called after the remote end of a socket connection has closed the write direction. An attempt to write data to it in that case will generate a
System.EPIPEerrno. If the remote end has closed both directions simultaneously (the usual case), Pike will first attempt to callclose_cb, then this callback (unlessclose_cbhas closed the stream).If the file is in buffer mode, the second argument will be a Buffer.
You should add data to write to this buffer.
When out-of-band data arrives on the stream,
read_oob_cbwill be called with some or all of that data as the second argument.When the stream allows out-of-band data to be sent,
write_oob_cbwill be called so that you can write more out-of-band data to it.If the OS doesn't separate the write events for normal and out-of-band data, Pike will try to call
write_oob_cbfirst. If it doesn't write anything, thenwrite_cbwill be tried. This also means thatwrite_oob_cbmight get called when the remote end of a connection has closed the write direction.When an error or an end-of-stream in the read direction occurs,
close_cbwill be called.errnowill return the error, or zero in the case of an end-of-stream.The name of this callback is rather unfortunate since it really has nothing to do with a close: The stream is still open when
close_cbis called (you might not be able to read and/or write to it, but you can still use things likequery_address, and the underlying file descriptor is still allocated). Also, this callback will not be called for a local close, neither by a call tocloseor by destructing this object.Also,
close_cbwill not be called if a remote close only occurs in the write direction; that is handled bywrite_cb(or possiblywrite_oob_cb).Events to
read_cbandclose_cbwill be automatically deregistered if an end-of-stream occurs, and all events in the case of an error. I.e. there won't be any more calls to the callbacks unless they are reinstalled. This doesn't affect the callback settings -query_read_callbacket al will still return the installed callbacks.
If the stream is a socket performing a nonblocking connect (see
open_socketandconnect), a connection failure will callclose_cb, and a successful connect will call eitherread_cborwrite_cbas above.All callbacks will receive the id set by
set_idas first argument.If a callback returns
-1, no other callback or call out will be called by the backend in that round. I.e. the caller of the backend will get control back right away. For the default backend that means it will immediately start another round and check files and call outs anew.- Parameter
event_mask An event mask specifing bitwise OR of one or more event types to monitor, selected from
Stdio.NOTE_WRITEand friends.- Note
These functions do not set the file nonblocking.
- Note
Callbacks are also set by
set_callbacksandset_nonblocking().- Note
After a callback has been called, it's disabled until it has accessed the stream accordingly, i.e. the
write_cbcallback is disabled after it's been called until something has been written withwrite, and thewrite_oob_cbcallback is likewise disabled until something has been written withwrite_oob. Since the data already has been read when the read callbacks are called, this effect is not noticeable for them.- Note
Installing callbacks means that you will start doing I/O on the stream from the thread running the backend. If you are running these set functions from another thread you must be prepared that the callbacks can be called immediately by the backend thread, so it might not be safe to continue using the stream in this thread.
Because of that, it's useful to talk about "callback mode" when any callback is installed. In callback mode the stream should be seen as "bound" to the backend thread. For instance, it's only the backend thread that reliably can end callback mode before the stream is "handed over" to another thread.
- Note
Callback mode has nothing to do with nonblocking mode - although the two often are used together they don't have to be.
- Note
The file object will stay referenced from the backend object as long as there are callbacks that can receive events.
- Bugs
Setting a close callback without a read callback currently only works when there's no risk of getting more data on the stream. Otherwise the close callback will be silently deregistered if data arrives.
- Note
fs_event callbacks only trigger on systems that support these events. Currently, this includes systems that use kqueue, such as Mac OS X, and various flavours of BSD.
- See also
set_callbacks,set_nonblocking(),set_id(),set_backend,query_read_callback,query_write_callback,query_read_oob_callback,query_write_oob_callback,query_close_callback
- Method
set_id
voidset_id(mixedid)- Description
This function sets the id of this file. The id is mainly used as an identifier that is sent as the first argument to all callbacks. The default id is
0(zero). Another possible use of the id is to hold all data related to this file in a mapping or array.- See also
query_id()
- Method
set_nonblocking
voidset_nonblocking(read_callback_tread_callback,write_callback_twrite_callback,close_callback_tclose_callback)voidset_nonblocking(read_callback_tread_callback,write_callback_twrite_callback,close_callback_tclose_callback,read_oob_callback_tread_oob_callback,write_oob_callback_twrite_oob_callback)voidset_nonblocking()- Description
This function sets a stream to nonblocking mode and installs the specified callbacks. See the
set_*_callbackfunctions for details about them. If no arguments are given, the callbacks will be cleared.- Note
As opposed to calling the set callback functions separately, this function will set all the callbacks and nonblocking mode atomically so that no callback gets called in between. That avoids races in case the backend is executed by another thread.
- Note
Out-of-band data was not be supported on Pike 0.5 and earlier, and not on Pike 0.6 through 7.4 if they were compiled with the option '--without-oob'.
- See also
set_blocking(),set_callbacks,set_read_callback(),set_write_callback(),set_read_oob_callback(),set_write_oob_callback(),set_close_callback()set_nonblocking_keep_callbacks(),set_blocking_keep_callbacks()
Class Stdio.FILE
- Annotations
@Pike.Annotations.Implements(NonblockingStream)- Description
Stdio.FILEis a buffered version ofStdio.File, it inheritsStdio.Fileand has most of the functionality ofStdio.File. However, it has an input buffer that allows line-by-line input.It also has support for automatic charset conversion for both input and output (see
Stdio.FILE()->set_charset()).- Note
The output part of
Stdio.FILEis currently not buffered.
- Method
_get_iterator
Stdio.FILEa;
foreach( a; index; value ) orprotectedobject_get_iterator()- Description
Returns an iterator that will loop over the lines in this file.
- See also
line_iterator()
- Method
getchar
localintgetchar()- Description
This function returns one character from the input stream.
- Returns
Returns the ISO-10646 (Unicode) value of the character.
- Note
Returns an
intand not astringof length 1.
- Method
gets
string|zerogets(bool|voidnot_all)- Description
Read one line of input with support for input conversion.
- Parameter
not_all Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.
- Returns
This function returns the line read if successful, and
0if no more lines are available.- See also
ngets(),read(),line_iterator(),set_charset()
- Method
line_iterator
String.SplitIterator|LineIteratorline_iterator(int|voidtrim)- Description
Returns an iterator that will loop over the lines in this file. If
trimis true, all '\r' characters will be removed from the input.- Note
It's not supported to call this method more than once unless a call to
seekis done in advance. Also note that it's not possible to intermingle calls toread,getsor other functions that read data with the line iterator, it will produce unexpected results since the internal buffer in the iterator will not contain sequential file-data in those cases.- See also
_get_iterator()
- Method
ngets
array(string)|zerongets(void|int(1..)n,bool|voidnot_all)- Description
Get
nlines.- Parameter
n Number of lines to get, or all remaining if zero.
- Parameter
not_all Set this parameter to ignore partial lines at EOF. This is useful for eg monitoring a growing logfile.
- Method
openat
FILEopenat(string(8bit)filename)FILEopenat(string(8bit)filename,string(7bit)mode)FILEopenat(string(8bit)filename,string(7bit)mode,intmask)- Description
Same as
Stdio.File()->openat(), but returns anStdio.FILEobject.- See also
Stdio.File()->openat()
- Method
pipe
FILEpipe(void|intflags)- Description
Same as
Stdio.File()->pipe(), but returns anStdio.FILEobject.- See also
Stdio.File()->pipe()
- Method
printf
intprintf(stringformat,mixed...data)- Description
This function does approximately the same as:
.write(sprintf(format,@data))- See also
write(),sprintf()
- Method
read
stringread(int|voidbytes,void|boolnow)- Description
Read
bytes(wide-) characters with buffering and support for input conversion.- See also
Stdio.File()->read(),set_charset(),unread()
- Method
set_charset
voidset_charset(string(8bit)|voidcharset)- Description
Sets the input and output charset of this file to the specified
charset. Ifcharsetis 0 or not specified the environment is used to try to detect a suitable charset.The default charset if this function is not called is "ISO-8859-1".
- FIXME
Consider using one of ISO-IR-196 ("\e%G" - switch to UTF-8 with return) or ISO-IR-190 ("\e%/G" - switch to UTF-8 level 1 no return) or ISO-IR-191 ("\e%/H" - switch to UTF-8 level 2 no return) or ISO-IR-192 ("\e%/I" - switch to UTF-8 level 3 no return) or ISO-IR-193 ("\e%/J" - switch to UTF-16 level 1 no return) or ISO-IR-194 ("\e%/K" - switch to UTF-16 level 2 no return) or ISO-IR-195 ("\e%/L" - switch to UTF-16 level 3 no return) or ISO-IR-162 ("\e%/@" - switch to UCS-2 level 1) or ISO-IR-163 ("\e%/A" - switch to UCS-4 level 1) or ISO-IR-174 ("\e%/C" - switch to UCS-2 level 2) or ISO-IR-175 ("\e%/D" - switch to UCS-4 level 2) or ISO-IR-176 ("\e%/E" - switch to UCS-2 level 3) or ISO-IR-177 ("\e%/F" - switch to UCS-4 level 3) or ISO-IR-178 ("\e%B" - switch to UTF-1) automatically to encode wide strings.
- Method
ungets
voidungets(strings)- Description
This function puts a line back in the input buffer. The line can then be read with eg
read(),gets()orgetchar().- Note
The string is autoterminated by an extra line-feed.
- See also
read(),gets(),getchar(),unread()
- Method
unread
voidunread(strings)- Description
This function puts a string back in the input buffer. The string can then be read with eg
read(),gets()orgetchar().- See also
read(),gets(),getchar(),ungets()
10.6. Ports and UDP
Class Stdio.Port
- Description
Handles listening to socket ports. Whenever you need a bound socket that is open and listens for connections you should use this program.
- Method
accept
File|zeroaccept()- Description
This function completes a connection made from a remote machine to this port. It returns a two-way stream in the form of a clone of
Stdio.File. The new file is by initially set to blocking mode.- See also
Stdio.File,fd_factory()
- Method
create
Stdio.PortStdio.Port()Stdio.PortStdio.Port(int|stringport)Stdio.PortStdio.Port(int|stringport,function(:void)accept_callback)Stdio.PortStdio.Port(int|stringport,function(:void)accept_callback,stringip)Stdio.PortStdio.Port("stdin")Stdio.PortStdio.Port("stdin",function(:void)accept_callback)- Description
If the first argument is other than
"stdin"the arguments will be passed tobind().When create is called with
"stdin"as the first argument, a socket is created out of the file descriptor0. This is only useful if it actually is a socket to begin with, and is equivalent to creating a port and initializing it withlisten_fd(0).- See also
bind
Class Stdio.UDP
- Description
UDP (User Datagram Protocol) handling.
- Method
set_nonblocking
UDPset_nonblocking()UDPset_nonblocking(void|function(mapping(string:int|string),mixed... :void)read_cb,mixed...extra_args)- Description
Set this object to nonblocking mode.
If
read_cbandextra_argsare specified, they will be passed on toset_read_callback().- Returns
The called object.
- Method
set_read_callback
UDPset_read_callback(function(mapping(string:int|string),mixed... :void)|zeroread_cb,mixed...extra_args)- Description
The
read_cbfunction will receive a mapping similar to the mapping returned byread():"data":stringReceived data.
"ip":stringData was sent from this IP.
"port":intData was sent from this port.
- Returns
The called object.
- See also
read()
10.7. Terminal I/O
Module Stdio.Terminfo
- Method
getFallbackTerm
protectedTermcapgetFallbackTerm(stringterm)- Description
Returns an object describing the fallback terminal for the terminal
term. This is usually equivalent toStdio.Terminfo.getTerm("dumb").- See also
Stdio.Terminfo.getTerm
- Method
getTerm
TermcapgetTerm(string|voidterm)- Description
Returns an object describing the terminal term. If term is not specified, it will default to
getenv("TERM")or if that fails to "dumb".Lookup of terminal information will first be done in the systems terminfo database, and if that fails in the termcap database. If neither database exists, a hardcoded entry for "dumb" will be used.
- See also
Stdio.Terminfo.getTerminfo, Stdio.Terminfo.getTermcap, Stdio.getFallbackTerm
- Method
getTermcap
TermcapgetTermcap(stringterm)- Description
Returns the terminal description object for
termfrom the systems termcap database. Returns 0 if not found.- See also
Stdio.Terminfo.getTerm, Stdio.Terminfo.getTerminfo
- Method
getTerminfo
TerminfogetTerminfo(stringterm)- Description
Returns the terminal description object for
termfrom the systems terminfo database. Returns 0 if not found.- See also
Stdio.Terminfo.getTerm, Stdio.Terminfo.getTermcap
- Method
is_tty
intis_tty()- Description
Returns 1 if
Stdio.stdinis connected to an interactive terminal that can handle backspacing, carriage return without linefeed, and the like.
Class Stdio.Terminfo.MetaTerminfoDB
- Description
TerminfoDBthat merges several directorys.
- Method
create
Stdio.Terminfo.MetaTerminfoDBStdio.Terminfo.MetaTerminfoDB(array(TerminfoDB|string)|voiddbs)- Description
Create a new Meta
TerminfoDB.- Parameter
dbs Array with elements in priority order. Elements may be either
TerminfoDBAn active
TerminfoDB.stringA directory that may exist and contain a terminfo database.
- Returns
If the resulting set of
TerminfoDB's is empty, the object will be destructed.
Class Stdio.Terminfo.TermMachine
- Description
Base class for outputting terminal codes.
Class Stdio.Terminfo.Termcap
- Description
Termcap terminal description object.
- Method
create
Stdio.Terminfo.TermcapStdio.Terminfo.Termcap(stringcap,TermcapDB|voidtcdb,int|voidmaxrecurse)
Class Stdio.Terminfo.TermcapDB
- Description
Termcap database
Class Stdio.Terminfo.Terminfo
- Description
Terminfo terminal description object
Class Stdio.Terminfo.TerminfoDB
- Description
Terminfo database for a single directory.
- Method
getFallbackTerm
Class Stdio.Readline
- Description
Terminal-aware line-based input.
- Example
// Get a Readline object connected to Stdio.stdin/Stdio.stdout. Stdio.Readline readline = Stdio.Readline();
// Enable history. string|zero history_dump = Stdio.read_file(history_file); if (history_dump) { readline->enable_history(history_dump/"\n"); } else { readline->enable_history(512); // 512 lines of history. }
// Add a completion handler. readline->get_input_controller()->bind("\t", handle_completions);
// Output some message. readline->message("Welcome to some application.\n");
// Set a prompt. readline->set_prompt("> ");
// Read some input. string command = readline->read();
// Save the history. Stdio.write_file(history_file, readline->get_history()->encode());
- See also
enable_history(),get_history(),get_input_controller(),message(),read(),set_prompt()
- Method
create
Stdio.ReadlineStdio.Readline(object|voidinfd,object|string|voidinterm,object|voidoutfd,object|string|voidoutterm)- Description
Creates a Readline object, that takes input from
infdand has output onoutfd.- Parameter
infd Defaults to
Stdio.stdin.- Parameter
interm Defaults to
Stdio.Terminfo.getTerm().- Parameter
outfd Defaults to
infd, unlessinfdis 0, in which caseoutfddefaults toStdio.stdout.- Parameter
outterm Defaults to
interm.
- Method
delta_history
voiddelta_history(intd)- Description
Changes the line to a line from the history
dsteps from the current entry (0 being the current line, negative values older, and positive values newer).- Note
Only effective if you have a history object.
- Method
edit
string|zeroedit(stringdata,string|voidlocal_prompt,array(string)|voidattrs)- Description
Read a line of data from the input.
- Parameter
data Initial/default value that the user may edit.
- Parameter
local_prompt Alternative prompt. Defaults to the prompt set by
set_prompt().- Parameter
attrs Alternative prompt attributes. Defaults to the attributes set by
set_prompt().- See also
read()
- Method
enable_history
voidenable_history(array(string)|History|inthist)- Description
Enable/disable history.
- Parameter
hist zeroDisable history.
int(1..)Enable history of max
histlines. If history is already enabled it is kept and the maximum number of lines adjusted.array(string)Set the history to this array of lines. The maximum number of lines is set to 512.
HistoryUse this
Historyobject.
- Method
get_input_controller
InputControllerget_input_controller()- Description
get current input control object
- Returns
Terminal input controller object
- Method
get_output_controller
OutputControllerget_output_controller()- Description
get current output control object
- Returns
Terminal output controller object
- Method
read
stringread(string|voidprompt,array(string)|voidattrs)- Description
Read a line of data from the input.
- Parameter
prompt Alternative prompt. Defaults to the prompt set by
set_prompt().- Parameter
attrs Alternative prompt attributes. Defaults to the attributes set by
set_prompt().This function is essentially a short hand for
edit("", prompt, attrs).- See also
edit()
- Method
set_blocking
voidset_blocking()- Description
Disable nonblocking mode.
This is equivalent to calling
set_nonblocking(0).- See also
set_nonblocking()
- Method
set_echo
voidset_echo(intonoff)- Description
Set text echo on or off.
- Parameter
onoff 1 for echo, 0 for no echo.
- Method
set_nonblocking
voidset_nonblocking(function(string|zero:void)|zerof)- Description
Set a function to be called every time a line is completed.
- Parameter
f Function to call when a line is completed, or
0(zero) to disable. It will be called with a string when a line is completed, and0(zero) wheneof()is called.- See also
set_blocking(),read()
- Method
set_prompt
stringset_prompt(stringnewp,array(string)|voidnewattrs)- Description
Set the prompt string.
- Parameter
newp New prompt string
- Parameter
newattrs Terminal attributes
- Method
write
voidwrite(stringmsg,void|intword_wrap)- Description
Print a message to the output device with optional word wrap.
- See also
message()
Class Stdio.Readline.DefaultEditKeys
Class Stdio.Readline.History
- Method
pop
boolpop(string|voidtext)- Description
Pop the last string off the history, discarding it. If text is provided, will only pop that string. Returns 1 if a string was removed, 0 if not.
- Method
pop
Class Stdio.Readline.InputController
- FIXME
Ought to have support for charset conversion.
- Method
create
Stdio.Readline.InputControllerStdio.Readline.InputController(object|void_infd,object|string|void_term)
Class Stdio.Readline.OutputController
- FIXME
Ought to have support for charset conversion.
- Method
check_columns
intcheck_columns()- Description
Check and return the terminal width.
- Note
In Pike 7.4 and earlier this function returned
void.- See also
get_number_of_columns
- Method
create
Stdio.Readline.OutputControllerStdio.Readline.OutputController(.File|void_outfd,.Terminfo.Termcap|string|void_term)
- Method
get_number_of_columns
intget_number_of_columns()- Description
Returns the width of the terminal.
- Note
Does not check the width of the terminal.
- See also
check_columns
10.8. Other
Module Stdio
- Typedef
close_callback_t
localtypedeffunction(mixed|void:int)|zeroStdio.close_callback_t- Description
The type for close callback functions.
- Typedef
fs_event_callback_t
localtypedeffunction(mixed|void,int:int)|zeroStdio.fs_event_callback_t- Description
The type for fs_event callback function functions.
- Typedef
read_callback_t
localtypedeffunction(mixed|void,string:int|void)|function(mixed|void,Buffer:int|void)|function(mixed|void:int|void)|zeroStdio.read_callback_t- Description
The various read_callback signatures.
The string (or void) version is used when buffer mode (see
set_buffer_mode) has not been enabled for reading.The
Bufferversion is used when aBufferhas been enabled for reading.In both cases the data is the newly arrived data, but in buffered mode data you did not fully read in the last read callback is kept in the buffer.
- Typedef
read_oob_callback_t
localtypedeffunction(mixed|void,string|void:int)|zeroStdio.read_oob_callback_t- Description
The type for read out of band callback functions.
- Typedef
write_callback_t
localtypedeffunction(mixed|void:int|void)|function(mixed|void,Buffer:int|void)|zeroStdio.write_callback_t- Description
The various write_callback signatures.
The void version is used when buffer mode (see
set_buffer_mode) has not been enabled for writing.The
Bufferversion is used when aBufferhas been enabled for writing, add data to that buffer to send it.
- Typedef
write_oob_callback_t
localtypedeffunction(mixed|void:int)|zeroStdio.write_oob_callback_t- Description
The type for write out of band callback functions.
- Constant
DATA_CHUNK_SIZE
finalconstantintStdio.DATA_CHUNK_SIZE- Description
Size used in various places to divide incoming or outgoing data into chunks.
- Constant
TCSADRAIN
constantstringStdio.TCSADRAIN- Description
Argument to
Stdio.File()->tcsetattr().Change after all output has been written.
- Constant
TCSAFLUSH
constantstringStdio.TCSAFLUSH- Description
Argument to
Stdio.File()->tcsetattr().Change after all output has been written, and empty the input buffers.
- Constant
TCSANOW
constantstringStdio.TCSANOW- Description
Argument to
Stdio.File()->tcsetattr().Change immediately.
- Variable
stderr
FILEStdio.stderr- Description
An instance of FILE("stderr"), the standard error stream. Use this when you want to output error messages.
- See also
predef::werror()
- Variable
stdin
FILEStdio.stdin- Description
An instance of FILE("stdin"), the standard input stream. Use this when you want to read anything from the standard input. This example will read lines from standard input for as long as there are more lines to read. Each line will then be written to stdout together with the line number. We could use
Stdio.stdout.write()instead of justwrite(), since they are the same function.- Example
int main() { int line; while(string s=Stdio.stdin.gets()) write("%5d: %s\n", line++, s); }
- Variable
stdout
FILEStdio.stdout- Description
An instance of FILE("stdout"), the standatd output stream. Use this when you want to write anything to the standard output.
- See also
predef::write()
- Method
append_file
intappend_file(stringfilename,stringstr,int|voidaccess)- Description
Append the string
stronto the filefilename.For a description of
access, seeStdio.File->open().- Throws
Throws an error if
filenamecouldn't be opened for writing.- Returns
Returns the number of bytes written, i.e.
sizeof(str).- See also
write_file(),read_bytes(),Stdio.File()->open()
- Method
append_path
Method append_path_unix
Method append_path_nt stringappend_path(stringabsolute,string...relative)stringappend_path_unix(stringabsolute,string...relative)stringappend_path_nt(stringabsolute,string...relative)- Description
Append
relativepaths to anabsolutepath and remove any"//","../"or"/."to produce a straightforward absolute path as a result."../"is ignorded in the relative paths if it makes the created path begin with something else than the absolute path (or so far created path).append_path_nt()fixes drive letter issues inrelativeby removing the colon separator":"if it exists (k:/fnord appends as k/fnord)append_path_nt()also makes sure that UNC path(s) inrelativeis appended correctly by removing any"\\"or"//"from the beginning.append_path()is equivalent toappend_path_unix()on UNIX-like operating systems, and equivalent toappend_path_nt()on NT-like operating systems.- See also
combine_path()
- Method
async_cp
voidasync_cp(stringfrom,stringto,function(int,mixed... :void)callback,mixed...args)- Description
Copy a file asynchronously.
This function is similar to
cp(), but works asynchronously.- Parameter
from Name of file to copy.
- Parameter
to Name of file to create or replace with a copy of
from.- Parameter
callback Function to be called on completion. The first argument will be
1on success, and0(zero) otherwise. The rest of the arguments tocallbackare passed verbatim fromargs.- Parameter
args Extra arguments to pass to
callback.- Note
For
callbackto be called, the backend must be active (iemain()must have returned-1, orPike.DefaultBackendget called in some other way). The actual copying may start before the backend has activated.- Bugs
Currently the file sizes are not compared, so the destination file (
to) may be truncated.- See also
cp(),sendfile()
- Method
convert_modestring2int
intconvert_modestring2int(string(7bit)mode_string)- Description
Convert the mode_string string as returned by Stdio.Stat object to int suitable for chmod
- Parameter
mode_string The string as return from Stdio.Stat()->mode_string
- Returns
An int matching the permission of the mode_string string suitable for chmod
- Method
cp
intcp(stringfrom,stringto)- Description
Copies the file
fromto the new positionto. If there is no system function for cp, a new file will be created and the old one copied manually in chunks ofDATA_CHUNK_SIZEbytes.This function can also copy directories recursively.
- Returns
0 on error, 1 on success
- Note
This function keeps file and directory mode bits, unlike in Pike 7.6 and earlier.
- Method
exist
intexist(string(8bit)path,bool|voiddo_not_follow_symlinks)- Description
Check if a
pathexists.- Parameter
path Filesystem path to check.
- Parameter
do_not_follow_symlinks Return
1also for broken symlinks.- Returns
Returns true if the given path exists (is a directory or file), otherwise false.
- Note
May fail with eg
errno()EFBIG if the file exists, but the filesystem doesn't support the file size.- See also
is_dir(),is_file(),is_link(),file_stat()
- Method
file_equal
intfile_equal(stringfile_1,stringfile_2)- Description
Returns nonzero if the given paths are files with identical content, returns zero otherwise. Zero is also returned for any sort of I/O error.
- Method
file_open_places
array(string)|zerofile_open_places(stringfile)- Description
Return an array of
describe_backtrace()results for the places that currently have aFile()orFILE()object open for the pathfile.- Note
Only available when the Pike runtime has been started with -DTRACK_OPEN_FILES.
- See also
report_file_open_places()
- Method
file_size
intfile_size(stringfilename,bool|voiddo_not_follow_symlinks)- Description
Give the size of a file.
- Parameter
filename Path to file to check.
- Parameter
do_not_follow_symlinks Set this to
1to inhibit following of symlinks.- Returns
Returns one of:
(0..)A non-negative value is the length (aka size) of the regular file.
-1A size of
-1indicates that the file either does not exist, or that it is not readable by you.-2Size
-2indicates that it is a directory.-3-3means that it is a symlink. Note that this is only returned for broken symlinks unlessdo_not_follow_symlinksis1.-4filenameis a device node.- See also
file_stat(),write_file(),read_bytes()
- Method
is_dir
intis_dir(stringpath,bool|voidno_symlinks)- Description
Check if a
pathis a directory.- Parameter
path Path to check.
- Parameter
no_symlinks Return
0also ifpathis a symlink to a directory.- Returns
Returns true if the given path is a directory, otherwise false.
- See also
exist(),is_file(),is_link(),file_stat()
- Method
is_file
intis_file(stringpath,bool|voidno_symlinks)- Description
Check if a
pathis a regular file.- Parameter
path Path to check.
- Parameter
no_symlinks Return
0also ifpathis a symlink to a regular file.- Returns
Returns true if the given path is a regular file, otherwise false.
- See also
exist(),is_dir(),is_link(),file_stat()
- Method
is_link
intis_link(stringpath)- Description
Check if a
pathis a symbolic link.- Returns
Returns true if the given path is a symbolic link, otherwise false.
- See also
exist(),is_dir(),is_file(),file_stat()
- Method
mkdirhier
intmkdirhier(stringpathname,void|intmode)- Description
Creates zero or more directories to ensure that the given
pathnameis a directory.If a
modeis given, it's used for the new directories after being &'ed with the current umask (on OS'es that support this).- Returns
Returns zero on failure and nonzero on success.
- See also
mkdir()
- Method
perror
voidperror(strings)- Description
This function prints a message to stderr along with a description of what went wrong if available. It uses the system errno to find out what went wrong, so it is only applicable to IO errors.
- See also
werror()
- Method
read_bytes
stringread_bytes(stringfilename,intstart,intlen)stringread_bytes(stringfilename,intstart)stringread_bytes(stringfilename)- Description
Read
lennumber of bytes from a regular filefilenamestarting at bytestart, and return it as a string.If
lenis omitted, the rest of the file will be returned.If
startis also omitted, the entire file will be returned.- Throws
Throws an error on any I/O error except when the file doesn't exist.
- Returns
Returns
0(zero) if the file doesn't exist or ifstartis beyond the end of it.Returns a string with the requested data otherwise.
- See also
read_file,write_file(),append_file()
- Method
read_file
stringread_file(stringfilename)stringread_file(stringfilename,intstart,intlen)- Description
Read
lenlines from a regular filefilenameafter skippingstartlines and return those lines as a string. If bothstartandlenare omitted the whole file is read.- Throws
Throws an error on any I/O error except when the file doesn't exist.
- Returns
Returns
0(zero) if the file doesn't exist or ifstartis beyond the end of it.Returns a string with the requested data otherwise.
- See also
read_bytes(),write_file()
- Method
recursive_mv
intrecursive_mv(stringfrom,stringto)- Description
Copy a file or a directory tree by copying and then removing. Mode bits are preserved in the copy. It's not the fastest but works on every OS and works well across different file systems.
- Returns
Returns 0 on failure, nonzero otherwise.
- See also
recursive_rmcp
- Method
recursive_rm
intrecursive_rm(stringpath)- Description
Remove a file or a directory tree.
- Returns
Returns 0 on failure, nonzero otherwise.
- See also
rm
- Method
report_file_open_places
voidreport_file_open_places(stringfile)- Description
Print a list of
describe_backtrace()results for the places that currently have aFile()orFILE()object open for the pathfiletostderr.- Note
Only available when the Pike runtime has been started with -DTRACK_OPEN_FILES.
- See also
file_open_places()
- Method
sendfile
objectsendfile(array(string)headers,Filefrom,intoffset,intlen,array(string)trailers,Fileto)objectsendfile(array(string)headers,Filefrom,intoffset,intlen,array(string)trailers,Fileto,function(int,mixed... :void)callback,mixed...args)- Description
Sends
headersfollowed bylenbytes starting atoffsetfrom the filefromfollowed bytrailersto the fileto. When completedcallbackwill be called with the total number of bytes sent as the first argument, followed byargs.Any of
headers,fromandtrailersmay be left out by setting them to0.Setting
offsetto-1means send from the current position infrom.Setting
lento-1means send untilfrom's end of file is reached.- Note
The sending is performed asynchronously, and may complete both before and after the function returns.
For
callbackto be called, the backend must be active (iemain()must have returned-1, orPike.DefaultBackendget called in some other way).In some cases, the backend must also be active for any sending to be performed at all.
In Pike 7.4.496, Pike 7.6.120 and Pike 7.7 and later the backend associated with
towill be used rather than the default backend. Note that you usually will wantfromto have the same backend asto.- Note
The low-level sending may be performed with blocking I/O calls, and thus trigger the process being killed with SIGPIPE when the peer closes the other end. Add a call to
signal()to avoid this.- Bugs
FIXME: Support for timeouts?
- See also
Stdio.File->set_nonblocking()
- Method
simplify_path
stringsimplify_path(stringpath)- Description
Returns a canonic representation of
path(without /./, /../, // and similar path segments).
- Method
werror
voidwerror(strings)- Description
Write a message to stderr. Stderr is normally the console, even if the process output has been redirected to a file or pipe.
- Note
This function is identical to
predef::werror().- See also
predef::werror()
- Method
write_file
intwrite_file(stringfilename,stringstr,int|voidaccess)- Description
Write the string
stronto the filefilename. Any existing data in the file is overwritten.For a description of
access, seeStdio.File()->open().- Throws
Throws an error if
filenamecouldn't be opened for writing.- Returns
Returns the number of bytes written, i.e.
sizeof(str).- See also
append_file(),read_bytes(),Stdio.File()->open()
Class Stdio.BlockFile (< StringType >)
- Annotations
@Pike.Annotations.Implements(InputBlockFile)@Pike.Annotations.Implements(Stream)- Description
The Stdio.BlockFile API.
This class exists purely for typing reasons.
Use in types in place of
Stdio.Filewhere only blocking I/O is done with the object.- See also
Stream,NonblockingStream,InputBlockStream,File,FILE
Class Stdio.FakeFile
- Annotations
@Pike.Annotations.Implements(Stdio.BlockFile)@Pike.Annotations.Implements(Stdio.NonblockingStream)- Description
A string wrapper that pretends to be a
Stdio.Fileobject in addition to some features of aStdio.FILEobject.
- Constant
is_fake_file
constantintStdio.FakeFile.is_fake_file- Description
This constant can be used to distinguish a FakeFile object from a real
Stdio.Fileobject.
- Method
_sizeof
int(0..)sizeof(Stdio.FakeFilearg)- Description
Sizeof on a FakeFile returns the size of its contents.
- Method
cast
(int)Stdio.FakeFile()
(float)Stdio.FakeFile()
(string)Stdio.FakeFile()
(array)Stdio.FakeFile()
(mapping)Stdio.FakeFile()
(multiset)Stdio.FakeFile()- Description
A FakeFile can be casted to a string.
- Method
create
Stdio.FakeFileStdio.FakeFile(stringdata,void|stringtype,void|intpointer)- See also
Stdio.File()->create()
- Method
line_iterator
String.SplitIteratorline_iterator(int|voidtrim)- See also
Stdio.File()->line_iterator()
- Method
query_address
string|zeroquery_address(void|boolis_local)- Description
Always returns 0.
- See also
Stdio.File()->query_address()
- Method
query_close_callback
function(:void)|zeroquery_close_callback()- See also
Stdio.File()->query_close_callback
- Method
query_read_callback
function(:void)|zeroquery_read_callback()- See also
Stdio.File()->query_read_callback
- Method
query_read_oob_callback
function(:void)|zeroquery_read_oob_callback()- See also
Stdio.File()->query_read_oob_callback
- Method
query_write_callback
function(:void)|zeroquery_write_callback()- See also
Stdio.File()->query_write_callback
- Method
query_write_oob_callback
function(:void)|zeroquery_write_oob_callback()- See also
Stdio.File()->query_write_oob_callback
- Method
set_blocking_keep_callbacks
voidset_blocking_keep_callbacks()- See also
Stdio.File()->set_blocking_keep_callbacks
- Method
set_close_callback
voidset_close_callback(Stdio.close_callback_tcb)- See also
Stdio.File()->set_close_callback
- Method
set_nonblocking
voidset_nonblocking(Stdio.read_callback_trcb,Stdio.write_callback_twcb,Stdio.close_callback_tccb,void|Stdio.read_oob_callback_trocb,void|Stdio.write_oob_callback_twocb)- See also
Stdio.File()->set_blocking
- Method
set_nonblocking_keep_callbacks
voidset_nonblocking_keep_callbacks()- See also
Stdio.File()->set_blocking_keep_callbacks
- Method
set_read_callback
voidset_read_callback(Stdio.read_callback_tcb)- See also
Stdio.File()->set_read_callback
- Method
set_read_oob_callback
voidset_read_oob_callback(Stdio.read_oob_callback_tcb)- See also
Stdio.File()->set_read_oob_callback
- Method
set_write_callback
voidset_write_callback(Stdio.write_callback_tcb)- See also
Stdio.File()->set_write_callback
- Method
set_write_oob_callback
voidset_write_oob_callback(Stdio.write_oob_callback_tcb)- See also
Stdio.File()->set_write_oob_callback
Class Stdio.FakePipe
- Description
This module emulates a bidirectional pipe/socket without using any actual file descriptors.
Class Stdio.FakePipe.InternalSocket
- Description
Class that implements one end of an emulated bi-directional pipe/socket.
- Variable
_other
Variable _read_buffer
Variable _write_buffer
Variable mux
Variable cond protectedthis_program|zeroStdio.FakePipe.InternalSocket._otherStdio.Buffer|zeroStdio.FakePipe.InternalSocket._read_bufferStdio.Buffer|zeroStdio.FakePipe.InternalSocket._write_bufferprotectedThread.MutexStdio.FakePipe.InternalSocket.muxprotectedThread.ConditionStdio.FakePipe.InternalSocket.cond
- Variable
other
this_programStdio.FakePipe.InternalSocket.other- Description
The other end of the emulated pipe/socket.
- Note
Read only.
- Method
__create__
protectedlocalvoid__create__(this_program|zero_other,Stdio.Buffer|zero_read_buffer,Stdio.Buffer|zero_write_buffer,Thread.Mutexmux,Thread.Conditioncond)
- Method
create
Stdio.FakePipe.InternalSocketStdio.FakePipe.InternalSocket(this_program|zero_other,Stdio.Buffer|zero_read_buffer,Stdio.Buffer|zero_write_buffer,Thread.Mutexmux,Thread.Conditioncond)
- Method
set_callbacks
voidset_callbacks(function(:void)rcb,function(:void)wcb,function(:void)ccb)
- Method
set_nonblocking
voidset_nonblocking(function(:void)rcb,function(:void)wcb,function(:void)ccb)
Class Stdio.FileLockKey
- Description
Holds the state of a lock returned from
Fd()->lock()orFd()->try_lock().- See also
Fd()->lock(),Fd()->try_lock()
Class Stdio.InputBlockFile (< StringType >)
- Annotations
@Pike.Annotations.Implements(InputStream)- Description
The Stdio.InputBlockFile API.
This class exists purely for typing reasons.
Use in types in place of
Stdio.Filewhere only blocking I/O in the read direction is done with the object.- See also
InputStream,NonblockingInputStream,BlockFile,File,FILE
Class Stdio.InputStream (< StringType >)
- Description
The Stdio.InputStream API.
This class exists purely for typing reasons.
Use in types in place of
Stdio.Filewhere only blocking stream-oriented I/O in the read direction is done with the object.This class lists the minimum functionality guaranteed to exist in all Stream objects that are opened for reading.
- See also
Stream,NonblockingInputStream,InputBlockFile,File,FILE
- Method
read_function
function(:StringType|zero) read_function(intnbytes)- Description
Returns a function that when called will call
readwith nbytes as argument. Can be used to get various callback functions, eg for the fourth argument toString.SplitIterator.
Class Stdio.LineIterator
- Description
Splits on lines, does only handle 8-bit characters.
Class Stdio.NonblockingInputStream (< StringType >)
- Annotations
@Pike.Annotations.Implements(InputStream)- Description
The Stdio.NonblockingInputStream API.
This class exists purely for typing reasons.
Use in types in place of
Stdio.Filewhere nonblocking and/or blocking stream-oriented I/O is done with the object.- See also
InputStream,NonblockingStream,InputBlockFile,File,FILE
- Method
set_read_callback
Method set_close_callback
Method set_fs_event_callback voidset_read_callback(read_callback_tf)voidset_close_callback(close_callback_tf)optionalvoidset_fs_event_callback(fs_event_callback_tf,intevent_mask)
- Method
set_nonblocking
voidset_nonblocking(read_callback_ta,write_callback_tb,close_callback_tc,read_oob_callback_t|voidd,write_oob_callback_t|voide)
Class Stdio.NonblockingOutputStreamMixin (< StringType >)
- Description
Mixin for converting a
NonblockingInputStreaminto aNonblockingStream.This class exists purely for typing reasons.
- Note
Typically you will not want to use this class directly, but instead use one of the classes that inherits it.
- See also
NonblockingInputStream,NonblockingStream
Class Stdio.NonblockingStream (< StringType >)
- Annotations
@Pike.Annotations.Implements(Stream)- Description
The Stdio.NonblockingStream API.
This class exists purely for typing reasons.
Use in types in place of
Stdio.Filewhere nonblocking and/or blocking stream-oriented I/O is done with the object.- See also
Stream,NonblockingInputStream,BlockFile,File,FILE
- Inherit
NonblockingInputStream
inherit NonblockingInputStream(<StringType>) : NonblockingInputStream
Class Stdio.OutputStreamMixin (< StringType >)
- Description
Mixin for converting an
InputStreaminto aStream.This class exists purely for typing reasons.
- Note
Typically you will not want to use this class directly, but instead use one of the classes that inherits it.
- See also
InputStream,Stream,BlockFile
Class Stdio.Stream (< StringType >)
- Annotations
@Pike.Annotations.Implements(InputStream)- Description
The Stdio.Stream API.
This class exists purely for typing reasons.
Use in types in place of
Stdio.Filewhere only blocking stream-oriented I/O is done with the object.This class lists the minimum functionality guaranteed to exist in all Stream objects.
- See also
InputStream,NonblockingStream,BlockFile,File,FILE
Module Stdio.Pipe
Class Stdio.Pipe.Base
- Description
This module provides a generic data processing non-blocking pipe interface. Set it to a pool of dedicated backends to use more than one CPU core (use one thread per backend). Use it in conjunction with the Shuffler to scale to an unlimited number of CPU cores.
- Method
create
Stdio.Pipe.BaseStdio.Pipe.Base(Gz.deflate|voidengine)- Description
Note that the Gz.deflate engine provided needs to be preconfigured using negative compression levels.
- Method
set_nonblocking
finalvoidset_nonblocking(function(:void)rcb,function(:void)wcb,function(:void)ccb)
Class Stdio.Pipe.Gunzip
- Description
This module provides a gzip-uncompressing non-blocking pipe interface.
Class Stdio.Pipe.Gzip
- Description
This module provides a gzip-compressing non-blocking pipe interface. Set it to a pool of dedicated backends to use more than one CPU core to compress data (use one thread per backend). Use it in conjunction with the Shuffler to scale to an unlimited number of CPU cores.
- Typedef
close_callback_t
Module _Stdio
- Description
Low-level I/O.
This is usually NOT the module you want. Try
Stdioinstead.- See also
Stdio
- Constant
IPPROTO_IP
constant_Stdio.IPPROTO_IP- Description
Used in
Fd()->setsockopt()to set IP-level options
- Constant
IPPROTO_TCP
constant_Stdio.IPPROTO_TCP- Description
Used in
Fd()->setsockopt()to set TCP-level options
- Constant
NOTE_ATTRIB
constantint_Stdio.NOTE_ATTRIB- Description
Used with
Stdio.File()->set_fs_event_callback()to monitor for attribute changes on a file.- Note
Available on systems that use kqueue.
- Constant
NOTE_DELETE
constantint_Stdio.NOTE_DELETE- Description
Used with
Stdio.File()->set_fs_event_callback()to monitor for deletion of a file.- Note
Available on systems that use kqueue.
- Constant
NOTE_EXTEND
constantint_Stdio.NOTE_EXTEND- Description
Used with
Stdio.File()->set_fs_event_callback()to monitor for extension events on a file.- Note
Available on systems that use kqueue.
- Constant
NOTE_LINK
constantint_Stdio.NOTE_LINK- Description
Used with
Stdio.File()->set_fs_event_callback()to monitor for changes to a file's link count.- Note
Available on systems that use kqueue.
- Constant
NOTE_RENAME
constantint_Stdio.NOTE_RENAME- Description
Used with
Stdio.File()->set_fs_event_callback()to monitor for move or rename events on a file.- Note
Available on systems that use kqueue.
- Constant
NOTE_REVOKE
constantint_Stdio.NOTE_REVOKE- Description
Used with
Stdio.File()->set_fs_event_callback()to monitor for access revokation (unmount, etc).- Note
Available on systems that use kqueue.
- Constant
NOTE_WRITE
constantint_Stdio.NOTE_WRITE- Description
Used with
Stdio.File()->set_fs_event_callback()to monitor for writes to a file.- Note
Available on systems that use kqueue.
- Constant
PROP_BIDIRECTIONAL
constantint_Stdio.PROP_BIDIRECTIONAL- Description
The file is bi-directional.
- See also
Stdio.File()->pipe()
- Constant
PROP_BUFFERED
constantint_Stdio.PROP_BUFFERED- Description
The file is buffered (usually 4KB).
- See also
Stdio.File()->pipe()
- Constant
PROP_IPC
constantint_Stdio.PROP_IPC- Description
The file may be used for inter process communication.
- See also
Stdio.File()->pipe()
- Constant
PROP_NONBLOCK
constantint_Stdio.PROP_NONBLOCK- Description
The file supports nonblocking I/O.
- See also
Stdio.File()->pipe()
- Constant
PROP_REVERSE
constantint_Stdio.PROP_REVERSE- Description
Request reversed operation.
Used as argument to
Stdio.File()->pipe(), whenPROP_BIDIRECTIONALhasn't been specified, to request the direction of the resulting pipe to reversed.- See also
Stdio.File()->pipe()
- Constant
PROP_SEND_FD
constantint_Stdio.PROP_SEND_FD- Description
The
Stdio.Fileobject might support theStdio.File()->send_fd()operation.- See also
Stdio.File()->pipe(),Stdio.File()->send_fd(),Stdio.File()->receive_fd()
- Constant
PROP_SHUTDOWN
constantint_Stdio.PROP_SHUTDOWN- Description
The file supports shutting down transmission in either direction.
- See also
Stdio.File()->close(),Stdio.File()->pipe()
- Constant
PROP_TTY
constantint_Stdio.PROP_TTY- Description
The
Stdio.Fileobject supports tty operations.- Note
This constant is only present on platforms where pseudo tty (aka pty) operations are available, and may thus be used to detect whether such operations should be attempted.
- See also
Stdio.File()->pipe()
- Constant
SEEK_CUR
constantint_Stdio.SEEK_CUR- Description
Used in
Fd()->seek()to specify an absolute offset from the beginning of the file.
- Constant
SEEK_DATA
constantint_Stdio.SEEK_DATA- Description
Used in
Fd()->seek()to specify an offset past the specified absolute offset that contains data (ie is not a hole). Seeking past the end of the file is not supported.
- Constant
SEEK_END
constantint_Stdio.SEEK_END- Description
Used in
Fd()->seek()to specify an offset relative to the end of the file.
- Constant
SEEK_HOLE
constantint_Stdio.SEEK_HOLE- Description
Used in
Fd()->seek()to specify an offset past the specified absolute offset that is a hole. There is an implicit hole at the end of the file. Seeking past the end of the file is not supported.
- Constant
SEEK_SET
constantint_Stdio.SEEK_SET- Description
Used in
Fd()->seek()to specify an offset relative to the current offset.
- Constant
SOL_SOCKET
constant_Stdio.SOL_SOCKET- Description
Used in
Fd()->setsockopt()to set socket-level options
- Constant
SO_KEEPALIVE
constant_Stdio.SO_KEEPALIVE- Description
Used in
Fd()->setsockopt()to control TCP/IP keep-alive packets.
- Constant
TCP_NODELAY
constant_Stdio.TCP_NODELAY- Description
Used in
Fd()->setsockopt()to control Nagle's Algorithm.
- Constant
XATTR_CREATE
constant_Stdio.XATTR_CREATE- Description
Used by
setxattrfunction and method to signify a pure create, which will fail if the attribute already exists.
- Constant
XATTR_REPLACE
constant_Stdio.XATTR_REPLACE- Description
Used by
setxattrfunction and method to signify a replace, which will fail the the attribute does not already exists.
- Constant
__HAVE_CONCURRENT_CLOSE__
constant_Stdio.__HAVE_CONCURRENT_CLOSE__- Description
Support concurrent closing of files while other blocking operations (eg
Stdio.File->read()orStdio.File()->write()) are active in other threads. This is typically used to implement timeout recovery.- Note
Support for concurrent closing of files is present in Pike 8.0.1950, Pike 9.0.11 and later on most non-NT platforms.
- See also
Stdio.File()->close()
- Constant
__HAVE_OOB__
constant_Stdio.__HAVE_OOB__- Description
Exists and has the value 1 if OOB operations are available.
- Note
In Pike 7.5 and later OOB operations are always present.
- Constant
__HAVE_POKE__
constant_Stdio.__HAVE_POKE__- Description
Indicates that this version of Pike has
Stdio.File()->poke().
- Constant
__HAVE_SEND_FD__
constant_Stdio.__HAVE_SEND_FD__- Description
Support for sending of file descriptors over
Stdio.File()->pipe()objects withPROP_SEND_FDcapability is supported.- See also
Stdio.File()->send_fd(),Stdio.File()->receive_fd(),Stdio.File()->read(),Stdio.File()->write(),Stdio.File()->pipe()
- Constant
__OOB__
constant_Stdio.__OOB__- Description
Implementation level of nonblocking I/O OOB support.
0Nonblocking OOB support is not supported.
1Nonblocking OOB works a little.
2Nonblocking OOB almost works.
3Nonblocking OOB works as intended.
-1Unknown level of nonblocking OOB support.
This constant only exists when OOB operations are available, i.e. when
__HAVE_OOB__is 1.
- Method
get_all_active_fd
array(int) get_all_active_fd()- Description
Returns the id of all the active file descriptors.
- Method
gethostip
mapping(string:mapping) gethostip()- Description
Returns the IP addresses of the host.
- Returns
Returns a mapping that maps interface name to a mapping with more information about that interface. That information mapping looks as follows.
"ips":array(string)A list of all IP addresses bound to this interface.
- Method
getprotobyname
intgetprotobyname(string(8bit)name)- Description
Returns the protocol number of the protocol
name. This calls the POSIX function getprotobyname. If the protocol cannot be found an error is thrown.
Enum _Stdio.FileModeFlags
- Description
File mode flags returned by
Fd()->mode().
- Constant
FILE_CREATE
constantint_Stdio.FILE_CREATE- Description
Create a new file if it didn't exist earlier.
- Constant
FILE_NONBLOCKING
constantint_Stdio.FILE_NONBLOCKING- Description
File opened in nonblocking mode.
Enum _Stdio.FilePropertyFlags
- Description
File properties for use with eg
Fd()->pipe(), and returned by egFd()->mode().
- Constant
PROP_BIDIRECTIONAL
constantint_Stdio.PROP_BIDIRECTIONAL- Description
File supports both sending and receiving.
- Constant
PROP_IPC
constantint_Stdio.PROP_IPC- Description
File can be used for interprocess communication.
- Constant
PROP_NONBLOCK
constantint_Stdio.PROP_NONBLOCK- Description
File supports nonblocking operation.
- Constant
PROP_SEND_FD
constantint_Stdio.PROP_SEND_FD- Description
File is capable of sending open file descriptors.
- Constant
PROP_SHUTDOWN
constantint_Stdio.PROP_SHUTDOWN- Description
File supports unidirectional close.
Class _Stdio.Buffer
- Description
A buffer to use as input or buffering when doing I/O. It is similar to
String.Buffer, but can only contain 8bit data and is designed for protocol parsing. It is optimized for reading from the beginning and adding to the end, and will try to minimise the amount of data copying that is done.The class maintains two separate offsets, one for reading and one for writing. The functions that add data all do so at the write offset (the end of the buffer), and reading is done from the read offset (the start of the buffer).
The class can also be used to directly read from and write to filedescriptors if so desired. This eliminates at least one memory copy.
- Note
The "avoid copy" part means that a Buffer will never shrink unless you call the
trimfunction.
- Typedef
AddArgument
privatetypedefBufferObject|string(8bit)|int(8bit)|array_Stdio.Buffer.AddArgument
- Typedef
BufferObject
privatetypedefSystem.Memory|Stdio.Buffer|String.Buffer_Stdio.Buffer.BufferObject
- Method
__set_on_write
void__set_on_write(function(:void)write_callback)- Description
This tells the buffer to trigger the write callback for the specified file descriptor when data is added to the buffer.
- Note
This is used internally by
Stdio.FileandSSL.Fileto handle nonblocking buffered mode, and is not necessarily intended to be used directly by anything but implementations of File or Stream like programs. Do not use this yourself on buffers with Files or Streams in buffer modes.
- Method
_encode
Method _decode string(8bit)encode_value(_Stdio.Bufferdata)_Stdio.Bufferdecode_value(string(8bit)data)- Description
Encode and decode Stdio.Buffer objects. Only the buffer data is kept, no other state is saved.
- Method
_search
int(-1..)search(_Stdio.Bufferfrom,int(8bit)character,int|voidstart,int(0..)|voidend)- Description
Search forward from the indicated
startposition for the specifiedcharacter.- Parameter
character Character to search for.
- Parameter
start Start position relative to the current read position of the buffer.
Negative
startvalues are supported and indicate positions prior to the current read position.- Parameter
end Don't search past this position of the buffer.
- Returns
Returns the first found position of
characterrelative to the current read position of the buffer on success, andUNDEFINEDon not found. The read position is not advanced.- See also
read_cstring(),search(),lfun::_search()
- Method
_search
int(-1..)search(_Stdio.Bufferfrom,string(8bit)substring,int|voidstart,int|voidend)- Description
Search forward from the indicated
startposition for the specifiedsubstring.- Parameter
substring Substring to search for.
- Parameter
start Start position relative to the current read position of the buffer.
Negative
startvalues are supported and indicate positions prior to the current read position.- Parameter
end Don't search past this position of the buffer.
- Returns
Returns the first found position of
substringrelative to the current read position of the buffer on success, andUNDEFINEDon not found. The read position is not advanced.- See also
read_cstring(),search(),lfun::_search()
- Method
_sizeof
intsizeof(_Stdio.Bufferarg)- Description
Returns the buffer size, in bytes. This is how much you can read from the buffer until it runs out of data.
- Method
`[..]
string(8bit)res =_Stdio.Buffer()[start..end]- Description
Range operator.
- Returns
Returns a string of the characters at offset
lowthroughhigh. Returns the empty string if no data is available in the range.
- Method
`[]
int(-1..255)res =_Stdio.Buffer()[off]- Description
Return the character at the specified offset.
- Returns
Returns the character at offset
offon success, and-1otherwise.- Note
Indexing with negative offsets was not supported in Pike 8.0 and earlier.
- Method
`[]=
_Stdio.Buffer()[off] =char- Description
Set the character at the specified offset to
char.- Note
Indexing with negative offsets was not supported in Pike 8.0 and earlier.
- Method
add
Bufferadd(AddArgument...data)- Description
Add the items in data to the end of the buffer.
The supported argument types are:
string(8bit)An eight bit string.
int(8bit)A single byte
System.MemoryA chunk of memory. The whole memory area is added.
Stdio.BufferA chunk of memory. The whole memory area is added.
String.BufferA chunk of memory. The whole memory area is added.
array(AddArgument)Add all elements in the array individually. Each element may be any one of the types listed here.
- See also
sprintf,add_int8,add_int16,add_int32,add_intandadd_hstring
- Method
add_hint
Bufferadd_hint(inti,int(0..)size_width)- Description
First add the size of the integer when encoded to base 256 as a
size_widthinteger, then add the integer to the buffer, both in network byte order.size_widthmust be less than Int.NATIVE_MAX.
- Method
add_hstring
Bufferadd_hstring(string(8bit)data,int(0..)size_size)Bufferadd_hstring(Stdio.Bufferdata,int(0..)size_size)Bufferadd_hstring(System.Memorydata,int(0..)size_size)Bufferadd_hstring(String.Bufferdata,int(0..)size_size)Bufferadd_hstring(int(8bit)data,int(0..)size_size)Bufferadd_hstring(arraydata,int(0..)size_size)Bufferadd_hstring(int|string(8bit)|Stdio.Buffer|System.Memory|arraydata,int(0..)size_size,int(0..)offset)- Description
Adds length of data followed by
datato the buffer.This is identical to sprintf("%"+size_size+"H",(string)Stdio.Buffer(data)) but significantly faster.
size_sizeis the number of bytes used to represent the length of the data. It must be less than Int.NATIVE_MAX.offsetis added to the length of the data prior to writing out the length. Typical usage involves addingsize_sizeto account for the room used by the size.The supported
dataargument types areint(8bit)An eight bit character.
string(8bit)An eight bit string.
System.MemoryA chunk of memory. The whole memory area is added.
Stdio.BufferA chunk of memory. The whole memory area is added.
String.BufferA chunk of memory. The whole memory area is added.
arrayAdd all elements in the array individually. Each element may be any one of the types listed here.
- Method
add_int
Bufferadd_int(inti,int(0..)width)- Description
Adds a generic integer to the buffer as an (width*8)bit network byteorder number.
widthmust be less than Int.NATIVE_MAX.
- Method
add_int16
Bufferadd_int16(int(16bit))- Description
Add a 16-bit network byte order value to the buffer
- Method
add_int16
Bufferadd_int16(Gmp.mpz)- Description
Add a 16-bit network byte order value to the buffer
- Method
add_int32
Bufferadd_int32(inti)- Description
Adds a 32 bit network byte order value to the buffer
- Method
add_int32
Bufferadd_int32(Gmp.mpzi)- Description
Adds a 32 bit network byte order value to the buffer
- Method
add_ints
Bufferadd_ints(array(int)integers,int(8bit)len)- Description
Add the integers in the specified array,
lenbytes per int. Equivalent to callingadd_intfor each integer, but faster, and if an error occurs the buffer will contain no new data. Either all or none of the integers will be added.Errors can occur if one of the elements in
integersis not actually an integer, if sizeof(integers)*len is bigger than can be represented in a size_t, or if the buffer cannot grow due to an out of memory condition.
- Method
add_padding
Bufferadd_padding(int(0..)nbytes,int(8bit)|voidbyte)- Description
Add
nbytesbytes of padding, ifbyteis not specified the area will be filled with 0's, otherwise the specified byte will be repeated.
- Method
allocate
voidallocate(int(0..)n)- Description
Make sure that at least
nbytes of space are available in this buffer.
- Method
cast
(string(8bit))_Stdio.Buffer()- Description
Convert the buffer to a string.
- Note
This only works for buffers whose length is less than 0x7fffffff.
- Method
consume
int(0..)|int(-1)consume(int(0..)n)- Description
Discard the first
nbytes from the bufferReturns -1 on error and the amount of space still left otherwise.
- Method
create
_Stdio.Buffer_Stdio.Buffer(int|voidlen)_Stdio.Buffer_Stdio.Buffer(string(8bit)contents)_Stdio.Buffer_Stdio.Buffer(System.Memory|String.Buffercontents)- Description
If passed an integer or no argument, create a buffer of that size, or if no argument is given, 226 bytes.
If
contentsare specified a new buffer with the contents of the given string/System.Memory or String.Buffer will be created.- Note
In the
String.Buffercase the data has to be copied unless there is only one reference to the String.Buffer object, since modifications of the String.Buffer would cause the Buffer to point into invalid memory.In all other cases this will not copy the string data, instead data will be read from the source until it needs to be modified, so the buffer creation is fast regardless of the length of the string.
However, as an example, if the buffer is created with a 100Gb
System.Memorymmap:ed file as thecontentsand you later on try to modify the buffer using one of theaddfunctions (orsprintfand similar) the old contents will be copied.You can use
read_only()to avoid accidents.
- Method
input_from
int(-1..)input_from(Stdio.Streamf,int|voidnbytes)- Description
Read data from
finto this buffer. Ifnbytesis not specified, read until there is no more data to read (currently).Returns the amount of data that was read, or
-1on read error.- Note
Please note that this funcition will read all data from the filedescriptor unless it's set to be non-blocking.
- Method
lock
objectlock()- Description
Makes this buffer read only until the returned object is released.
- Note
This currently simply returns a 0-length subbuffer.
- Method
match
__deprecated__string(8bit)|int|float|arraymatch(string(8bit)format)- Description
Reads data from the beginning of the buffer to match the specifed format, then return the match.
The non-matching data will be left in the buffer.
This function is very similar to
sscanf, but the result is the sum of the matches. Most useful to match a single value.- Returns
Returns the sum of the matching %-expressions,
""if a prefix (but no %-expression) matches andUNDEFINEDon mismatch. Note that the addition may throw errors.- Note
Prior to Pike 9.0
0was returned on mismatch andformatwas returned on a prefix match.- Example
// Get the next whitespace separated word from the buffer. buffer->match("%*[ \t\r\n]%[^ \t\r\n]");// Get the next integer as a string. buffer->match("%0s%d");- Deprecated
Replaced by
sscanf.- See also
sscanf(),predef::sscanf(),array_sscanf()
- Method
output_to
int(-1..)output_to(Stdio.Stream|function(string(8bit):int)fun,int(0..)|voidnbytes)- Description
Write data from the buffer to the indicated file.
- Parameter
fun Write function. Either one of:
Stdio.StreamA file object in which the function
write()will be called.function(string(8bit):int)A function which will be called with a
string(8bit)to write and is expected to return anintindicating the number of bytes successfully written or-1on failure.- Parameter
nbytes If
nbytesis not specified the whole buffer will be written if possible. Otherwise at mostnbyteswill be written.- Returns
Will return the number of bytes that have been written successfully.
If no bytes have been written successfully and
fun()failed with an error,-1will be returned.This function is similar to
int(-1..) output_to(Stdio.Stream|function(string(8bit):int) fun,int(0..)|void nbytes){if(objectp(fun)) fun =([object]fun)->write;int(0..) total;while(sizeof(this)){int(0..) bytes = undefinedp(nbytes)?sizeof(this):nbytes;if(bytes > 0x8000) bytes = 0x8000;string(8bit) chunk = read(bytes);int(-1..) written =([function]fun)(chunk);if(written <= 0){return total || written;} total += written;if(written < sizeof(chunk)){ unread(sizeof(chunk)- written);}if(!undefinedp(nbytes)){ nbytes -= written;if(!nbytes){break;}}}return total;}- Deprecated
This function is going to get deprecated. In case you want to use it against an
Stdio.Filelike object, please consider using thef->write(buf)API. If you want to use it against a custom write function, please consider supporting thef->write(buf)API in it.
- Method
range_error
protectedboolrange_error(inthowmuch)- Description
This function is called when an attempt is made to read out of bounds.
The default implementation simply returns
0(zero).Override this function to change the behavior.
- Parameter
howmuch The argument
howmuchindicates how much data is needed:(1..)Need
howmuchbytes more0The amount of data needed is not certain. This most often happens when
sscanforread_jsonis used(..-1)Tried to
unread-howmuchbytes. There is usually no way to satisfy the requested range.The only supported way is to extract the data from the buffer, add the requested amount of "go backbuffer", add the data back, and forward -
howmuchbytes.- Returns
trueif the operation should be retried,falseotherwise.Do not return true unless you have added data to the buffer, doing so could result in an infinite loop (since no data is added, the range_error will be called again immediately).
- Method
read
string(8bit)read()- Description
Read all data from the buffer.
If there is not enough data available this returns 0.
This is basically equivalent to (string)buffer, but it also removes the data from the buffer.
- See also
try_read()
- Method
read
string(8bit)read(int(0..)n)- Description
Read
nbytes of data from the buffer.If there is not enough data available this returns 0.
- See also
try_read()
- Method
read_buffer
Bufferread_buffer(int(0..)n)Bufferread_buffer(int(0..)n,boolcopy)- Description
Same as
read, but returns the result as an Buffer.No data is copied unless
copyis specified and true, the new buffer points into the old one.- Note
As long as the subbuffer exists the main buffer is locked in memory.
Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.
- Method
read_cstring
string(8bit)read_cstring(void|int(8bit)sentinel,void|int(8bit)escape)- Description
Reads a \0 terminated C-string and returns the string excluding the terminating \0.
If there is not enough data available return UNDEFINED.
Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).
- Parameter
sentinel A different character can be used as end sentinel of the string.
- Parameter
escape An optional character used as a prefix to quote the following character. UNDEFINED and the same value as
sentinelmean that there is no escape character.- Note
Escape characters (if any) are left untouched in the returned string.
- See also
_search()
- Method
read_hbuffer
Bufferread_hbuffer(intn)Bufferread_hbuffer(intn,boolcopy)- Description
Same as
read_hstring, but returns the result as an Buffer.No data is copied unless
copyis specified and true, the new buffer points into the old one.- Note
As long as the subbuffer exists no data can be added to the main buffer.
Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.
If you need to unlink the new buffer after it has been created, call
trimin it.
- Method
read_hint
intread_hint(int(0..)n)- Description
Read a network byte order unsigned number of size n*8 bits, then read another network byte order number of the size indicated by the first size.
Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.
- Method
read_hstring
string(8bit)read_hstring(int(0..)n,void|intoffset)- Description
Identical in functionality to
read(read_number(n)) but faster.Read a network byte order number of size n*8 bits, then return the indicated number of bytes as a string.
offsetis substracted from the specified length prior to reading the string. Typical usage involves substractingnto account for the room used by the size.If there is not enough data available return 0.
Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).
- Method
read_int
intread_int(int(0..)n)- Description
Read a network byte order unsigned number of size n*8 bits, then return it.
Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.
- See also
read_le_int
- Method
read_ints
array(int) read_ints(intn,int(8bit)width)- Description
Read a list of
nnetwork byte order unsigned numbers each of sizewidth*8 bits, then return it.Will return 0 if there is not enough buffer space available unless error mode is set to throw errors.
- Method
read_json
mixedread_json(int|voidrequire_whitespace_separator)- Description
Read a single JSON expression from the buffer and return it.
If
require_whitespace_separatoris true there must be a whitespace after each json value (as an example, newline or space).The JSON is assumed to be utf-8 encoded.
- Returns
UNDEFINED if no data is available to read. The read value otherwise.
- Note
Unless whitespaces are required this function only really work correctly with objects, arrays and strings.
There is really no way to see where one value starts and the other ends for most other cases
- Method
read_le_int
intread_le_int(int(0..)n)- Description
Read a little endian byte order unsigned number of size n*8 bits, then return it.
Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.
- See also
read_int
- Method
read_only
voidread_only()- Description
This makes the existing data in the buffer permanently read only.
- Note
You can use lock() to do this temporarily.
- Method
read_sint
intread_sint(intsize)- Description
Read a network byte order two:s complement signed number of size n*8 bits, then return it.
Will return UNDEFINED if there is not enough buffer space available unless error mode is set to throw errors.
- Method
rewind_on_error
Method rewind_key RewindKeyrewind_on_error()RewindKeyrewind_key()- Description
These functions are very similar. The
rewind_on_errorvariant will create an object that, when it goes out of scope without having been destructed explicitly, will cause the buffer to rewind to the location it had when this function is called.This will happen if you throw an error or otherwise let the object fall out of scope.
Use
destruct(RewindKey)orRewindKey.releaseto stop the buffer from being rewound.The second version (
rewind_key) requires you to explicitly callRewindKey.rewindto do the rewind.Take some care with these objects, if you create multiple ones at once the results might be somewhat confusing if you do not release them in the reverse order they were created in (then again, you almost certainly really only need one)
You can call
RewindKey.updatein the generated object to change where it will be rewound to.The typical use-case of this functionality is when parsing a packet protocol with variable length packets where the length is not immediately known. It saves you from keeping track of how much to rewind if you had not actually gotten the whole packet yet.
- Example
void parse_packet(Stdio.Buffer b ){Stdio.Buffer.RewindKey rewind = b->rewind_on_error(); b->set_error_mode(1);switch( b->read_int8())// packet type{case DATA:int channel = b->read_int8();Stdio.Buffer data = b->read_hbuffer( 4 );// we have read the whole packet, so no longer rewind on error. rewind->release();return handle_data_packet( channel, data );}}- Note
Just calling
rewind_on_errorwithout assigning the return value to something will not do anything. You need to keep the object around while the rewind-to position is still valid.Keeping the object around forbids the buffer from moving data inside itself, this means that it can only grow. So do not keep the rewind key when it is not needed.
- Method
set_error_mode
Bufferset_error_mode(intm)Bufferset_error_mode(programm)- Description
Set the error mode of this buffer to
m.If true operations that would normally return 0 (like trying to read too much) will instead throw an error. If
mis a program a clone of it will be thrown on error.This is useful when parsing received data, you do not have to verify that each and every read operation suceeds.
However, the non-error mode is more useful when checking to see if a packet/segment/whatever has arrived.
The thrown error object will have the constant buffer_error set to a non-false value.
- Example
void read_callback(int i,string(8bit) new_data){ inbuffer->add( new_data );while( Buffer packet = inbuffer->read_hbuffer(2)){ packet->set_error_mode(Buffer.THROW_ERROR);if(mixed e =catch( handle_packet( packet )))if( e->buffer_error ) protocol_error();// illegal data in packetelse throw(e);// the other code did something bad}}void handle_packet( Buffer pack ){switch( pack->read_int8()){ ... case HEADER_FRAME:int num_headers = pack->read_int32();for(int i = 0; i<num_headers; i++ ) headers[pack->read_hstring(2)]= pack->read_hstring(2); ... }}
- Method
set_max_waste
voidset_max_waste(floatfactor)- Description
Configure how much free space should be allowed, at most, as a factor of the current buffer size.
The default is 0.5, leaving at most half the buffer as waste.
- Method
sprintf
Buffersprintf(strict_sprintf_formatformat,sprintf_args...args)- Description
Appends the output from
sprintfat the end of the buffer.This is somewhat faster than add(sprintf(...)) since no intermediate string is created.
- Method
sscanf
arraysscanf(string(8bit)format)- Description
Reads data from the beginning of the buffer to match the specifed format, then return an array with the matches.
The non-matching data will be left in the buffer.
See
array_sscanffor more information.- See also
match(),predef::sscanf(),array_sscanf()
- Method
trim
voidtrim()- Description
Frees unused memory.
Note that calling this function excessively will slow things down, since the data often has to be copied.
- Note
This function could possibly throw an out-of-memory error if the realloc fails to find a new (smaller) memory area.
- Method
truncate
int(0..)|int(-1)truncate(int(0..)n)- Description
Truncates the buffer to a length of
nbytes.Returns -1 on error and the number of bytes removed otherwise.
- Method
try_read
string(8bit)try_read(int(0..)len)- Description
Attempt to read some data from the buffer.
- Parameter
len Read at most
lenbytes from the buffer.- Returns
If the buffer contains less than
lenbytes of data, the entire buffer contents are returned. Otherwise the firstlenbytes are returned.- See also
read()
- Method
unread
int(0..)|int(-1)unread(int(0..)n)- Description
Rewind the buffer
nbytes.- Returns
This function returns how many more bytes of buffer is available to rewind, or -1 on error.
- Note
Unless you add new data to the buffer using any of the add functions you can always rewind.
You can call
unread(0)to see how much.
Class _Stdio.Buffer.RewindKey
- Description
The return value of
Buffer.rewind_on_error()andBuffer.rewind_key()This object will cause the buffer to unwind to the position it was at when the object was created either when it is released (when it falls out of scope, explicit destruct does not count) or when
rewindis called, depending on which function was used to create it.
- Method
release
voidrelease()- Description
Do not rewind if the object is released.
- Note
This is equivalent to calling destruct() on the object
Class _Stdio.Fd
- Description
Low level I/O operations.
- Note
This is not the class you want. Use
Stdio.Fileand friends instead.- See also
Stdio.File,Stdio.FILE,_Stdio.Fd_ref
- Variable
_errno
protectedSystem.Errno_Stdio.Fd._errno- Description
Variable containing the internal value returned by
errno().- See also
errno()
- Variable
_read_callback
Variable _write_callback
Variable _read_oob_callback
Variable _write_oob_callback
Variable _error_callback
Variable _fs_event_callback mixed_Stdio.Fd._read_callbackmixed_Stdio.Fd._write_callbackmixed_Stdio.Fd._read_oob_callbackmixed_Stdio.Fd._write_oob_callbackmixed_Stdio.Fd._error_callbackmixed_Stdio.Fd._fs_event_callback- Description
Callback functions installed by
Stdio.File()->set_callbacks()et al.
- Method
cd
boolcd(string(8bit)|voidrelpath)- Description
Change current directory relative to this file.
- Returns
Returns
1on success and0(zero) on failure.- See also
predef::cd()
- Method
close
intclose()intclose(stringdirection)- Description
Close a file or stream.
If direction is not specified, both the read and the write direction are closed. Otherwise only the directions specified is closed.
- Returns
Returns
1if the file or stream now is closed in all directions, and0otherwise.- Throws
An exception is thrown if an I/O error occurs.
The default behaviour for sockets is typically to flush buffered data in the background, but this can be changed with
linger().- Note
close()has no effect if this file object has been associated with an already opened file, i.e. ifopen()was given an integer as the first argument.- See also
linger(),open(),open_socket()
- Method
connect
int(-1..1)connect(string(8bit)dest_addr,intdest_port)int(-1..1)connect(string(8bit)dest_addr,intdest_port,string(8bit)src_addr,intsrc_port)string(8bit)|int(-1..0)connect(string(8bit)dest_addr,intdest_port,string(8bit)|voidsrc_addr,int|voidsrc_port,string(8bit)data)- Description
Open a TCP/IP connection to the specified destination.
In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.
If the
dataargument is included the socket will use TCP_FAST_OPEN if available, if not the data will not be sent. In the data case the function either returns the data that has not been sent (only one packet can be sent with this option) or 0 if the connection failed immediately.- Returns
Returns one of
string(8bit)datathat did not fit into the initial connection packet. Note that the connection may not have been established yet.int(0)Returns
0on (synchronous) connection failure.int(1)Returns
1if there was nodatato send.int(-1)Returns
-1if the connection has not yet been established. Use egpoke()orquery_address()to wait or check for when the connection completes.- Note
Note that in versions of Pike prior to 9.0
1was returned also in the not yet established case.Note that
-1may be returned also for sockets in blocking mode if the connect(3N) system call was interrupted.- See also
open_socket(),poke()
- Method
connect_unix
boolconnect_unix(stringfilename)- Description
Open a UNIX domain socket connection to the specified destination.
- Parameter
filename Filename to create.
In nonblocking mode, success is indicated with the write-callback, and failure with the close-callback or the read_oob-callback.
- Returns
Returns
1on success, and0on failure.- Note
In nonblocking mode
0(zero) may be returned anderrno()set to EWOULDBLOCK. This should not be regarded as a connection failure.- Note
filenamehad a quite restrictive length limit (~100 characters) prior to Pike 7.8.334.
- Method
create
_Stdio.Fd_Stdio.Fd(stringfilename)_Stdio.Fd_Stdio.Fd(stringfilename,stringmode)_Stdio.Fd_Stdio.Fd(stringfilename,stringmode,intaccess)_Stdio.Fd_Stdio.Fd(intfd)_Stdio.Fd_Stdio.Fd(intfd,stringmode)- Description
See
open().- See also
open()
- Method
dup2
intdup2(Stdio.Fileto)- Description
Duplicate a file over another.
This function works similarly to
assign(), but instead of making the argument a reference to the same file, it creates a new file with the same properties and places it in the argument.- Returns
Returns
1on success and0(zero) on failure.- Note
toneed not be open, in which case a new fd is allocated.- Note
Note also that
tois also assigned to the same backend (if any) as this object.- See also
Stdio.File()->assign(),dup()
- Method
errno
System.Errnoerrno()- Description
Return the errno for the latest failed file operation.
- See also
System.Errno
- Method
fd_factory
Fdfd_factory()- Description
Factory creating
Stdio.Fdobjects.This function is called by
openat(),pipe(),dup()and other functions creating new file objects.The default implementation calls
object_program(this_object())()to create the new object, and returns theFdinherit in it.- Note
Note that this function must return the
Fdinherit in the object.- See also
Stdio.Port()->fd_factory(),openat(),pipe()
- Method
get_dir
array(string) get_dir(string|voidpath)- Description
Get directory contents relative to an open directory.
- Parameter
path Path relative to the open directory. Defaults to the directory itself.
- Returns
Returns an array of filenames.
- Note
Not available on all architectures.
- See also
predef::get_dir(),statat(),openat(),unlinkat()
- Method
getxattr
stringgetxattr(stringattr)- Description
Return the value of a specified attribute, or 0 if it does not exist
- Method
grantpt
stringgrantpt()- Description
If this file has been created by calling
openpt(), return the filename of the associated pts-file. This function should only be called once.- Returns
Returns the filename of the corresponding pts.
- Note
This function is only available on some platforms.
- Method
hardlinkat
voidhardlinkat(string(8bit)from,string(8bit)to,Stdio.File|voidtofd)- Description
Create a hardlink named
tofrom the filefrom, wherefromis relative to this file, andtois relative totofdunless it is not set in which case it is also relative to this file.- Note
This function is not available on all platforms.
- See also
hardlink(),symlinkat(),unlinkat()
- Method
is_open
intis_open()- Description
Returns true if the file is open.
- Note
If the file is a socket that has been closed from the remote side, this function might still return true.
- Note
Most methods can't be called for a file descriptor that isn't open. Notable exceptions
errno,mode, and the set and query functions for callbacks and backend.
- Method
linger
boollinger(int(-1..65535)|voidseconds)- Description
Set the socket linger behaviour on
close().- Parameter
seconds -1Reset to default behaviour. This typically means that
close()will return immediately, but any buffered data will still be sent if possible.0Terminate the connection immediately on
close(), and discard any buffered data.(1..65535)Have
close()wait for at mostsecondsseconds for any buffered data to be sent after which the connection is terminated.- Returns
Returns
1on success, and0(zero) on failure.- Note
This operation is only valid on sockets.
- Note
This function was not available in Pike 7.8.775 and earlier.
- See also
close()
- Method
listxattr
array(string) listxattr()- Description
Return an array of all extended attributes set on the file
- Method
lock
Stdio.FileLockKeylock()Stdio.FileLockKeylock(boolis_recursive)- Description
Makes an exclusive file lock on this file.
- See also
trylock()
- Method
mode
FileModeFlags|FilePropertyFlagsmode()- Description
Returns the open mode and capabilities for the file.
- Returns
Returns an
`|()of the following flags:0x1000FILE_READ0x2000FILE_WRITE0x4000FILE_APPEND0x8000FILE_CREATE0x0100FILE_TRUNC0x0200FILE_EXCLUSIVE0x0400FILE_NONBLOCKING0x0080PROP_TTY0x0040PROP_SEND_FD0x0010PROP_BIDIRECTIONAL0x0008PROP_BUFFERED0x0004PROP_SHUTDOWN0x0002PROP_NONBLOCK0x0001PROP_IPC- Note
In some versions of Pike 7.8 the PROP_ flags were filtered from the result.
- See also
open()
- Method
open
intopen(stringfilename,stringmode)intopen(stringfilename,stringmode,intaccess)intopen(intfd,stringmode)- Description
Open a file, or use an existing fd.
If
filenameis given, attempt to open the named file. Iffdis given instead, it should be the file descriptor for an already opened file, which will then be used by this object.modedescribes how the file is opened. It's a case-insensitive string consisting of one or more of the following letters:- "r"
Open for reading.
- "w"
Open for writing.
- "a"
Append new data to the end.
- "c"
Create the file if it doesn't exist already.
- "t"
Truncate the file to zero length if it already contains data. Use only together with
"w".- "x"
Open exclusively - the open fails if the file already exists. Use only together with
"c". Note that it's not safe to assume that this is atomic on some systems.
accessspecifies the permissions to use if a new file is created. It is a UNIX style permission bitfield:- 0400
User has read permission.
- 0200
User has write permission.
- 0100
User has execute permission.
- 0040
Group has read permission.
- 0020
Group has write permission.
- 0010
Group has execute permission.
- 0004
Others have read permission.
- 0002
Others have write permission.
- 0001
Others have execute permission.
It's system dependent on which of these bits that are actually heeded. If
accessis not specified, it defaults to00666, but note that on UNIX systems it's masked with the process umask before use.- Returns
Returns nonzero on success and
0(zero) on failure. If there is a failure thenerrnoreturns the error code.- See also
close()
- Method
openat
Stdio.Fileopenat(stringfilename)Stdio.Fileopenat(stringfilename,stringmode)Stdio.Fileopenat(stringfilename,stringmode,intaccess)- Description
Open a file relative to an opened directory.
- Returns
Returns a new file object on success, and
0(zero) on failure.- Note
Not available on all architectures.
- See also
open(),statat(),unlinkat()
- Method
openpt
intopenpt(stringmode)- Description
Open the master end of a pseudo-terminal pair.
- Returns
This function returns
1for success,0otherwise.- See also
grantpt()
- Method
peek
int(-1..1)peek()int(-1..1)peek(int|floattimeout)int(-1..1)peek(int|floattimeout,intnot_eof)- Description
Check if there is data available to read, or wait some time for available data to read.
More specifically, a later call to
read()will return immediately, either due to data being present, or due to some error (eg if a socket has been closed).- Parameter
timeout Timeout in seconds.
- Parameter
not_eof Flag for specifying handling of end of file. The following values are currently defined:
0Traditional (and default) behaviour. Return
1at EOF.1Regard EOF as an error. Return
-1and seterrno()to returnEPIPEat EOF.- Returns
1There is data available to
read(), ornot_eofis0(zero) and we're at EOF. A later call toread()will not block.0There is no data available (ie timeout), or the wait was interrupted.
-1Error condition. The error code returned by
errno()has been updated.- See also
errno(),poke(),read()- Note
The function may be interrupted prematurely of the timeout (due to signals); check the timing manually if this is imporant.
- Method
poke
int(-1..1)poke()int(-1..1)poke(int|floattimeout)int(-1..1)poke(int|floattimeout)- Description
Check if there is buffer space available to write data, or wait some time for available space.
More specifically, a later nonblocking call to
write()will succeed in writing some data, or indicate some error (eg if a nonblocking socket failed to connect).- Parameter
timeout Timeout in seconds.
- Returns
1There is buffer space available, or nonblocking
connect()has completed.0There is no data available (ie timeout), or the call was interrupted by a signal.
-1Error condition. The error code returned by
errno()has been updated (eg a nonblockingconnect()has failed).- See also
errno(),connect(),write(),peek()- Note
The function may be interrupted prematurely of the timeout (due to signals); check the timing manually if this is imporant.
- Method
proxy
voidproxy(Stdio.Filefrom)- Description
Starts a thread that asynchronously copies data from
fromto this file.- See also
Stdio.sendfile()
- Method
query_address
stringquery_address()stringquery_address(boollocal)- Description
Get address and port of a socket end-point.
- Parameter
local If the argument
localis not specified, or is0(zero), the remote end-point is returned. Otherwise, iflocalis1, the local end-point is returned.- Returns
This function returns the address and port of a socket end-point on the form
"x.x.x.x port"(IPv4) or"x:x:x:x:x:x:x:x port"(IPv6). IPv6 addresses may use the contracted syntax.If this file is not a socket, is not connected, or some other error occurs,
0(zero) is returned anderrno()will return the error code.- Throws
An error is thrown if the socket (or file) isn't open.
- See also
connect()
- Method
query_backend
Pike.Backendquery_backend()- Description
Return the backend used for the callbacks.
- See also
set_backend
- Method
query_fd
intquery_fd()- Description
Returns the file descriptor number associated with this object.
- Method
query_mtu
intquery_mtu()- Description
Get the Max Transfer Unit for the object (if any).
- Returns
-1Returns
-1if the object is not a socket or if the mtu is unknown.(1..)Returns a positive value with the mtu on success.
- Method
read
string(8bit)read()string(8bit)read(intlen)string(8bit)read(intlen,boolnot_all)- Description
Read data from a file or a stream.
Attempts to read
lenbytes from the file, and return it as a string. Less thanlenbytes can be returned if:end-of-file is encountered for a normal file, or
it's a stream that has been closed from the other end, or
it's a stream in nonblocking mode, or
it's a stream and
not_allis set, ornot_allisn't set and an error occurred (see below).
If
not_allis nonzero,read()does not try its best to read as many bytes as you have asked for, but merely returns as much as the system read function returns. This is mainly useful with stream devices which can return exactly one row or packet at a time. Ifnot_allis used in blocking mode,read()only blocks if there's no data at all available.If something goes wrong and
not_allis set, zero is returned. If something goes wrong andnot_allis zero or left out, then either zero or a string shorter thanlenis returned. If the problem persists then a later call toread()fails and returns zero, however.If everything went fine, a call to
errno()directly afterwards returns zero. That includes an end due to end-of-file or remote close.If no arguments are given,
read()reads to the end of the file or stream.If any file descriptors have been sent by the other side of the stream,
receive_fd()will be called once for every sent file descriptor.- Note
It's not necessary to set
not_allto avoid blocking reading when nonblocking mode is used.- Note
When at the end of a file or stream, repeated calls to
read()will return the empty string since it's not considered an error. The empty string is never returned in other cases, unless nonblocking mode is used orlenis zero.- See also
read_oob(),write(),receive_fd(),send_fd()
- Method
read
intread(System.Memorydst,void|int(0..)offset)- Description
Reads data from a file or stream into the buffer
dstat offsetoffset. Tries to read as many bytes as buffer space available.- Returns
The number of bytes read. Returns
-1on error anderrno()will return the corresponding error code.
- Method
read
intread(Stdio.Buffer|String.Bufferdst)- Description
Reads data from a file or stream into the buffer
dst. Tries to read as many bytes as buffer space available. Will advance the write position indstby the number of bytes read.- Returns
The number of bytes read. Returns
-1on error anderrno()will return the corresponding error code.
- Method
read_oob
stringread_oob()stringread_oob(intlen)stringread_oob(intlen,boolnot_all)- Description
Attempts to read
lenbytes of out-of-band data from the stream, and returns it as a string. Less thanlenbytes can be returned if:the stream has been closed from the other end, or
nonblocking mode is used, or
not_allis set, ornot_allisn't set and an error occurred (see below).
If
not_allis nonzero,read_oob()only returns as many bytes of out-of-band data as are currently available.If something goes wrong and
not_allis set, zero is returned. If something goes wrong andnot_allis zero or left out, then either zero or a string shorter thanlenis returned. If the problem persists then a later call toread_oob()fails and returns zero, however.If everything went fine, a call to
errno()directly afterwards returns zero. That includes an end due to remote close.If no arguments are given,
read_oob()reads to the end of the stream.- Note
It is not guaranteed that all out-of-band data sent from the other end is received. Most streams only allow for a single byte of out-of-band data at a time.
- Note
It's not necessary to set
not_allto avoid blocking reading when nonblocking mode is used.- Note
When at the end of a file or stream, repeated calls to
read()returns the empty string since it's not considered an error. The empty string is never returned in other cases, unless nonblocking mode is used orlenis zero.- See also
read(),write_oob()
- Method
readlinkat
stringreadlinkat(string(8bit)path)- Description
Returns what the symbolic link
pathpoints to, wherepathis relative to the open file.- Note
This function is not available on all platforms.
- See also
readlink(),symlink(),symlinkat()
- Method
receive_fd
voidreceive_fd(Stdio.Fdfd)- Description
Remote file descriptor reception handler.
- Parameter
fd File descriptor received from the remote end of a
pipe(). This object has been created byfd_factory().This function is called from
read()when a remote file descriptor has been received over aPROP_SEND_FDcapablepipe().The default implementation is just a prototype.
Overload this function to enable reception of remote file descriptors.
- Note
The capability of sending and receiving remote file descriptors is only available on some operating systems. This capability is indicated by the precence of
__HAVE_SEND_FD__.- See also
send_fd(),read(),fd_factory(),__HAVE_SEND_FD__
- Method
release_fd
intrelease_fd()- Description
Returns the file descriptor number associated with this object, in addition to releasing it so that this object behaves as if closed. Other settings like callbacks and backend remain intact.
take_fdcan later be used to reinstate the file descriptor so that the state is restored.- See also
query_fd(),take_fd()
- Method
seek
intseek(intoffset)intseek(intoffset,stringwhence)- Description
The seek() function repositions the offset of the open file associated with the file descriptor fd to the argument
offsetaccording to the directivewhenceas follows:Stdio.SEEK_SETThe offset is set to
offsetbytes.Stdio.SEEK_CURThe offset is set to its current location plus
offsetbytes.Stdio.SEEK_ENDThe offset is set to the size of the file plus
offsetbytes.If
whenceis not specified it isSEEK_SETifoffsetis positive, and ifoffsetis negativeSEEK_END.The seek() function on most operating systems allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap.
Seeking file data and holes
Stdio.SEEK_DATAandStdio.SEEK_HOLEare nonstandard extensions present in Linux, Solaris, FreeBSD, and DragonFly BSD; they are proposed for inclusion in the next POSIX revision.Stdio.SEEK_DATAAdjust the file offset to the next location in the file greater than or equal to offset containing data. If offset points to data, then the file offset is set to offset.
Stdio.SEEK_HOLEAdjust the file offset to the next hole in the file greater than or equal to offset. If offset points into the middle of a hole, then the file offset is set to offset. If there is no hole past offset, then the file offset is adjusted to the end of the file (i.e., there is an implicit hole at the end of any file).
In both of the above cases,
seek()fails ifoffsetpoints past the end of the file.These operations allow applications to map holes in a sparsely allocated file. This can be useful for applications such as file backup tools, which can save space when creating backups and preserve holes, if they have a mechanism for discovering holes.
For the purposes of these operations, a hole is a sequence of zeros that (normally) has not been allocated in the underlying file storage. However, a filesystem is not obliged to report holes, so these operations are not a guaranteed mechanism for mapping the storage space actually allocated to a file. (Furthermore, a sequence of zeros that actually has been written to the underlying storage may or may not be reported as a hole.)
In the simplest implementation, a filesystem can support the operations by making
SEEK_HOLEalways return the offset of the end of the file, and makingSEEK_DATAalways return offset (i.e., even if the location referred to by offset is a hole, it can be considered to consist of data that is a sequence of zeros).- Returns
Upon successful completion,
seek()returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value(off_t) -1is returned anderrnois set to indicate the error.- See also
tell()
- Method
seek
variant__deprecated__intseek(intunit,intmult)variant__deprecated__intseek(intunit,intmult,intadd)- Description
Seek to a specified offset in a file.
If
multoraddare specified, the position is calculated aspos =.unit*mult+addIf the resulting position is negative then it is relative to the end of the file, otherwise it's an absolute offset from the start of the file.
- Returns
Returns the new offset, or
-1on failure.- Note
The arguments
multandaddare considered obsolete, and should not be used.- See also
tell()
- Method
send_fd
voidsend_fd(Stdio.Fdfd)- Description
Queues an open file descriptor for sending to the other end of a stream.
- Note
The actual sending is performed at the next successful call to
write(), this is due to limitations in the system calls. This means that it isn't possible to send a file descriptor without also sending some in-band data.This operation is only supported on
pipe()'s created withPROP_SEND_FD.This function is not available on all operating systems, check for
__HAVE_SEND_FD__.The queue is emptied on successful
write()and when the write direction isclose()'d.- See also
receive_fd(),write(),pipe(),read(),__HAVE_SEND_FD__
- Method
set_backend
voidset_backend(Pike.Backendbackend)- Description
Set the backend used for the callbacks.
- Note
The backend keeps a reference to this object only when it is in callback mode. So if this object hasn't got any active callbacks and it runs out of other references, it will still be destructed quickly (after closing, if necessary).
Also, this object does not keep a reference to the backend.
- See also
query_backend(),set_nonblocking(),Stdio.File()->set_read_callback(),Stdio.File()->set_write_callback(),Stdio.File()->set_fs_event_callback()
- Method
set_blocking
voidset_blocking()- Description
Sets this file to blocking operation.
This is the inverse operation of
set_nonblocking().- See also
set_nonblocking()
- Method
set_buffer
voidset_buffer(intbufsize,stringmode)voidset_buffer(intbufsize)- Description
Set internal socket buffer.
This function sets the internal buffer size of a socket or stream.
The second argument allows you to set the read or write buffer by specifying
"r"or"w".- Note
It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.
- See also
open_socket(),Stdio.Port()->accept()
- Method
set_close_on_exec
voidset_close_on_exec(boolyes_no)- Description
Marks the file as to be closed in spawned processes.
This function determines whether this file will be closed when calling
exece().Default is that the file WILL be closed on exec except for stdin, stdout and stderr.
- See also
Process.create_process(),exece()
- Method
set_keepalive
boolset_keepalive(boolon_off)- Description
Equivalent to
setsockopt(Stdio.SO_KEEPALIVE, on_off), but will set errno if SO_KEEPALIVE is not supported, rather than issuing a compilation error for the missing constant.
- Method
set_nodelay
boolset_nodelay(bool|voidstate)- Description
Control Nagle's Algorithm (RFC 896)
- Parameter
state 0Return to the normal state of using Nagle's Algorithm
1(default) Disable Nagling - small writes will not be queued.
- Returns
Returns
1on success, and0(zero) on failure.- Note
This operation is only valid on sockets.
- See also
setsockopt()
- Method
set_nonblocking
voidset_nonblocking()- Description
Sets this file to nonblocking operation.
- Note
Nonblocking operation is not supported on all Stdio.File objects. Notably it is not guaranteed to be supported on objects returned by
pipe()unlessPROP_NONBLOCKwas specified in the call topipe().- See also
set_blocking()
- Method
setsockopt
boolsetsockopt(intlevel,intopt,intstate)- Description
Set socket options like Stdio.SO_KEEPALIVE. This function is always available; the presence or absence of the option constants indicates availability of those features.
- Returns
1 if successful, 0 if not (and sets errno())
- See also
set_keepalive()
- Method
setxattr
voidsetxattr(stringattr,stringvalue,intflags)- Description
Set the attribute
attrto the valuevalue.The flags parameter can be used to refine the semantics of the operation.
Stdio.XATTR_CREATEspecifies a pure create, which fails if the named attribute exists already.Stdio.XATTR_REPLACEspecifies a pure replace operation, which fails if the named attribute does not already exist.By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.
- Returns
1 if successful, 0 otherwise, setting errno.
- Method
stat
Statstat()- Description
Get status for an open file.
This function returns the same information as the function
file_stat(), but for the file it is called in. If file is not an open file,0(zero) is returned. Zero is also returned if file is a pipe or socket.- Returns
See
file_stat()for a description of the return value.- See also
file_stat(),statat()
- Method
statat
Statstatat(stringpath,void|boolsymlink)- Description
Get status for a file relative an open directory.
This function returns the same information as the function
file_stat(), but relative to the file it is called in. If file is not an open file,0(zero) is returned. Zero is also returned if file is a pipe or socket.- Returns
See
file_stat()for a description of the return value.- Note
Not available on all architectures.
- Note
The
symlinkmode may not be available. In which case an error will be thrown if the operation is attempted.- See also
file_stat(),stat(),openat(),unlinkat()
- Method
symlinkat
voidsymlinkat(string(8bit)from,string(8bit)to)- Description
Create a symbolic link named
tothat points tofrom, wheretois relative to this file..- Note
This function is not available on all platforms.
- See also
hardlinkat(),symlink(),readlinkat(),unlinkat()
- Method
sync
boolsync()- Description
Flush buffers to disk.
- Returns
Returns
0(zero) and sets errno on failure.Returns
1on success.
- Method
take_fd
voidtake_fd(intfd)- Description
Rehooks the given file descriptor number to be associated with this object. As opposed to using
openwith a file descriptor number, it will be closed by this object upon destruct or whencloseis called.- See also
release_fd()
- Method
tcdrain
booltcdrain()- Description
Wait for transmission buffers to empty.
- Returns
Returns
1on success and0(zero) on failure.- See also
tcflush()
- Method
tcflush
booltcflush(string(7bit)|voidflush_direction)- Description
Flush queued terminal control messages.
- Parameter
flush_direction "TCIFLUSH"Flush received but not read.
"TCOFLUSH"Flush written but not transmitted.
"TCIOFLUSH"Flush both of the above. Default.
- Returns
Returns
1on success and0(zero) on failure.- See also
tcdrain()
- Method
tcgetattr
Method tcsetattr mapping(string(7bit):int) tcgetattr()inttcsetattr(mapping(string(7bit):int)attr)inttcsetattr(mapping(string(7bit):int)attr,string(7bit)when)- Description
Gets/sets term attributes. The returned value/the
attrparameter is a mapping on the form"ispeed":int(-1..)In baud rate.
"ospeed":int(-1..)Out baud rate.
"csize":int(-1)|int(5..8)Character size in bits.
"rows":intTerminal rows.
"columns":intTerminal columns.
flag_name:boolThe value of a named flag. The flag name is the string describing the termios flags (IGNBRK, BRKINT, IGNPAR, PARMRK, INPCK, ISTRIP, INLCR, IGNCR, ICRNL, IUCLC, IXON, IXANY, IXOFF, IMAXBEL, OPOST, OLCUC, ONLCR, OCRNL, ONOCR, ONLRET, OFILL, OFDEL, OXTABS, ONOEOT, CSTOPB, CREAD, PARENB, PARODD, HUPCL, CLOCAL, CRTSCTS, ISIG, ICANON, XCASE, ECHO, ECHOE, ECHOK, ECHONL, ECHOCTL, ECHOPRT, ECHOKE, FLUSHO, NOFLSH, TOSTOP, PENDIN). See the manpage for termios or other documentation for more information. All flags are not available on all platforms.
character_name:int(8bit)Sets the value of a control character (VINTR, VQUIT, VERASE, VKILL, VEOF, VTIME, VMIN, VSWTC, VSTART, VSTOP, VSUSP, VEOL, VREPRINT, VDISCARD, VWERASE, VLNEXT, VEOL2). All control characters are not available on all platforms.
Negative values are not allowed as indata, but might appear in the result from
tcgetattrwhen the actual value is unknown.tcsetattrreturns 0 if failed.The argument
whentotcsetattrdescribes when the changes are to take effect:"TCSANOW"The change occurs immediately (default).
"TCSADRAIN"The change occurs after all output has been written.
"TCSAFLUSH"The change occurs after all output has been written, and empties input buffers.
- Example
// setting the terminal in raw mode: Stdio.stdin->tcsetattr((["ECHO":0,"ICANON":0,"VMIN":0,"VTIME":0]));
- Note
Unknown flags are ignored by
tcsetattr().tcsetattralways changes the attribute, so only include attributes that actually should be altered in the attribute mapping.- Bugs
Terminal rows and columns setting by
tcsetattr()is not currently supported.- See also
tcsetsize()
- Method
tcsendbreak
booltcsendbreak(int|voidduration)- Description
Send a break signal.
- Parameter
duration Duration to send the signal for.
0(zero) causes a break signal to be sent for between 0.25 and 0.5 seconds. Other values are operating system dependent:- SunOS
The number of joined break signals as above.
- Linux, AIX, Digital Unix, Tru64
The time in milliseconds.
- FreeBSD, NetBSD, HP-UX, MacOS
The value is ignored.
- Solaris, Unixware
The behavior is changed to be similar to
tcdrain().
- Returns
Returns
1on success and0(zero) on failure.
- Method
tcsetsize
booltcsetsize(introws,intcols)- Description
Set the number of rows and columns for a terminal.
- Returns
Returns
1on success and0(zero) on failure.- See also
tcgetattr(),tcsetattr()
- Method
truncate
booltruncate(intlength)- Description
Truncate a file.
Truncates the file to the specified length
length.- Returns
Returns
1on success, and0(zero) on failure.- See also
open()
- Method
trylock
Stdio.FileLockKeytrylock()Stdio.FileLockKeytrylock(boolis_recursive)- Description
Attempts to place a file lock on this file.
- See also
lock()
- Method
unlinkat
intunlinkat(stringf)- Description
Remove a file or directory relative to an open file.
- Returns
Returns
0(zero) on failure,1otherwise.- See also
rm(),openat(),statat()
- Method
write
intwrite(string(8bit)data)intwrite(string(8bit)format,mixed...extras)intwrite(array(string(8bit))data)intwrite(array(string(8bit))format,mixed...extras)intwrite(Stdio.Buffer|String.Buffer|System.Memorydata,void|int(0..)offset)- Description
Write data to a file or a stream.
If there are any file descriptors that have been queued for sending (with
send_fd()), they will be sent.- Parameter
data Data to write.
If
datais an array of strings, they are written in sequence.- Parameter
format - Parameter
extras If more than one argument is given,
sprintf()is used to format them usingformat. Ifformatis an array, the strings in it are concatenated and the result is used as format string.- Parameter
offset The offset in data to start writing from.
- Returns
Writes
dataand returns the number of bytes that were actually written.(1..)The number of bytes successfully written to the OS buffers.
This can be less than the size of the given data if eg:
Some data was written successfully and then something went wrong.
If only some data was written due to an error and that error persists, then a later call to
write()will fail and return-1.Nonblocking mode is used and not all data could be written without blocking.
0No bytes were written. This may be due to
dataor the formatted data being the empty string.Nonblocking mode is used and no data could be written without blocking.
-1Something went wrong and no bytes were written.
If everything went fine, a call to
errno()directly afterwards returns zero.- Note
Writing of wide strings is not supported. You have to encode the data somehow, e.g. with
string_to_utf8or with one of the charsets supported byCharset.encoder.- Note
The variant of this function using a buffer object does not release the interpreter lock.
- See also
read(),write_oob(),send_fd()
- Method
write_oob
intwrite_oob(stringdata)intwrite_oob(stringformat,mixed...extras)- Description
Write out-of-band data to a stream.
Writes out-of-band data to a stream and returns how many bytes that were actually written. It can be less than the size of the given data if some data was written successfully and then something went wrong.
-1 is returned if something went wrong and no bytes were written. If only some data was written due to an error and that error persists, then a later call to
write_oob()fails and returns -1.If everything went fine, a call to
errno()directly afterwards returns zero.If more than one argument is given,
sprintf()is used to format them.- Note
It is not guaranteed that all out-of-band data sent from the other end is received. Most streams only allow for a single byte of out-of-band data at a time. Some streams sends the rest of the data as ordinary data.
- See also
read_oob(),write()
Class _Stdio.Fd_ref
- Description
Proxy class that contains stub functions that call the corresponding functions in
Fd.Used by
Stdio.File.- Note
This is not the class you want. Use
Stdio.Fileand friends instead.- See also
Stdio.File,Stdio.FILE,_Stdio.Fd
Class _Stdio.UDP
- Constant
MSG_OOB
constant_Stdio.UDP.MSG_OOB- Description
Flag to specify to
read()to read out of band packets.
- Constant
MSG_PEEK
constant_Stdio.UDP.MSG_PEEK- Description
Flag to specify to
read()to cause it to not remove the packet from the input buffer.
- Method
add_membership
intadd_membership(stringgroup,void|stringaddress)- Description
Join a multicast group.
- Parameter
group groupcontains the address of the multicast group the application wants to join. It must be a valid multicast address.- Parameter
address addressis the address of the local interface with which the system should join to the multicast group. If not provided the system will select an appropriate interface.See also the Unix man page for setsocketopt IPPROTO_IP IP_ADD_MEMBERSHIP and IPPROTO_IPV6 IPV6_JOIN_GROUP.
- Note
The
addressparameter is currently not supported for IPv6.- Note
This function did not support IPv6 in Pike 7.8 and earlier.
- See also
drop_membership()
- Method
bind
UDPbind(int|stringport,string|voidaddress,string|boolno_reuseaddr)- Description
Binds a port for receiving or transmitting UDP.
- Parameter
port Either a port number or the name of a service as listed in /etc/services.
- Parameter
address Local address to bind to.
- Parameter
no_reuseaddr If set to
1, Pike will not set theSO_REUSEADDRoption on the UDP port.- Note
SO_REUSEADDRis never applied when binding a random port (bind(0)).In general,
SO_REUSEADDRis not desirable on UDP ports. Unless used for receiving multicast, be sure to never bind a non-random port without settingno_reuseaddrto1.- Throws
Throws error when unable to bind port.
- Method
close
boolclose()- Description
Closes an open UDP port.
- Note
This method was introduced in Pike 7.5.
- Method
connect
boolconnect(stringaddress,int|stringport)- Description
Establish an UDP connection.
This function connects an UDP socket previously created with
Stdio.UDP()to a remote socket. Theaddressis the IP name or number for the remote machine.- Returns
Returns
1on success,0(zero) otherwise.- Note
If the socket is in nonblocking mode, you have to wait for a write or close callback before you know if the connection failed or not.
- See also
bind(),query_address()
- Method
drop_membership
intdrop_membership(stringgroup,void|stringaddress)- Description
Leave a multicast group.
- Parameter
group groupcontains the address of the multicast group the application wants to join. It must be a valid multicast address.- Parameter
address addressis the address of the local interface with which the system should join to the multicast group. If not provided the system will select an appropriate interface.See also the Unix man page for setsocketopt IPPROTO_IP IP_DROP_MEMBERSHIP and IPPROTO_IPV6 IPV6_LEAVE_GROUP.
- Note
The
addressparameter is currently not supported for IPv6.- Note
This function did not support IPv6 in Pike 7.8 and earlier.
- See also
add_membership()
- Method
enable_broadcast
boolenable_broadcast()- Description
Set the broadcast flag. If enabled then sockets receive packets sent to a broadcast address and they are allowed to send packets to a broadcast address.
- Returns
Returns
1on success,0(zero) otherwise.- Note
This is normally only avalable to root users.
- Method
enable_multicast
boolenable_multicast(stringreply_address)- Description
Set the local device for a multicast socket.
- Parameter
reply_address Local address that should appear in the multicast packets.
See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_IF and IPPROTO_IPV6 IPV6_MULTICAST_IF.
- Note
This function did not support IPv6 in Pike 7.8.
- Method
errno
interrno()- Description
Returns the error code for the last command on this object. Error code is normally cleared when a command is successful.
- Method
fd_factory
UDPfd_factory()- Description
Factory creating
Stdio.UDPobjects.This function is called by
dup()and other functions creating new UDP objects.The default implementation calls
object_program(this_object())()to create the new object, and returns theUDPinherit in it.- Note
Note that this function must return the
UDPinherit in the object.- See also
dup(),Stdio.File()->fd_factory()
- Method
query_address
stringquery_address()- Description
Returns the local address of a socket on the form "x.x.x.x port". If this file is not a socket, not connected or some other error occurs, zero is returned.
- Method
query_backend
Pike.Backendquery_backend()- Description
Return the backend used for the read callback.
- See also
set_backend
- Method
query_mtu
intquery_mtu()- Description
Get the Max Transfer Unit for the object (if any).
- Returns
-1Returns
-1if the object is not a socket or if the mtu is unknown.(1..)Returns a positive value with the mtu on success.
- Note
The returned value is adjusted to take account for the IP and UDP headers, so that it should be usable without further adjustment unless further IP options are in use.
- Method
read
mapping(string:int|string) read()mapping(string:int|string) read(intflag)- Description
Read from the UDP socket.
Flag
flagis a bitfield, 1 for out of band data and 2 for peek- Returns
mapping(string:int|string) in the form ([ "data" : string received data "ip" : string received from this ip "port" : int ...and this port ])
- See also
Stdio.UDP()->set_read_callback(),MSG_OOB,MSG_PEEK
- Method
send
intsend(stringto,int|stringport,stringmessage)intsend(stringto,int|stringport,stringmessage,intflags)- Description
Send data to a UDP socket.
- Parameter
to The recipient address. For
connect()ed objects specifying a recipient of eitherUNDEFINEDor""causes the default recipient to be used.- Parameter
port The recipient port number. For
connect()ed objects specifying port number0casues the default recipient port to be used.- Parameter
flag A flag bitfield with
1for out of band data and2for don't route flag.- Returns
(0..)The number of bytes that were actually written.
(..-1)Failed to send the
message. Checkerrno()for the cause. Common causes are:System.EMSGSIZEThe
messageis too large to send unfragmented.System.EWOULDBLOCKThe send buffers are full.
- Throws
Throws errors on invalid arguments and uninitialized object.
- Note
Versions of Pike prior to 8.1.5 threw errors also on EMSGSIZE (
"Too big message") and EWOULDBLOCK ("Message would block."). These versions of Pike also did not update the object errno on this function failing.- Note
Versions of Pike prior to 8.1.13 did not support the default recipient for
connect()ed objects.- See also
connect(),errno(),query_mtu()
- Method
set_backend
voidset_backend(Pike.Backendbackend)- Description
Set the backend used for the read callback.
- Note
The backend keeps a reference to this object as long as there can be calls to the read callback, but this object does not keep a reference to the backend.
- See also
query_backend
- Method
set_buffer
voidset_buffer(intbufsize,stringmode)voidset_buffer(intbufsize)- Description
Set internal socket buffer.
This function sets the internal buffer size of a socket or stream.
The second argument allows you to set the read or write buffer by specifying
"r"or"w".- Note
It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.
- See also
Stdio.File()->open_socket(),Stdio.Port()->accept()
- Method
set_multicast_ttl
intset_multicast_ttl(intttl)- Description
Set the time-to-live value of outgoing multicast packets for this socket.
- Parameter
ttl The number of router hops sent multicast packets should survive.
It is very important for multicast packets to set the smallest TTL possible. The default before calling this function is 1 which means that multicast packets don't leak from the local network unless the user program explicitly requests it.
See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_TTL and IPPROTO_IPV6 IPV6_MULTICAST_HOPS.
- Note
This function did not support IPv6 in Pike 7.8 and earlier.
- See also
add_membership()
- Method
set_nonblocking
objectset_nonblocking(function(:void)|voidrcb,function(:void)|voidwcb)- Description
Sets this object to be nonblocking and the read and write callbacks.
- Method
set_type
UDPset_type(intsock_type)UDPset_type(intsock_type,intfamily)- Description
Sets socket type and protocol family.
- Constant
MSG_OOB
Class _Stdio._port
- Variable
_id
protectedmixed_Stdio._port._id- Description
The id set via
set_id()(if any).- See also
query_id(),set_id()
- Method
accept
Stdio.Fileaccept()- Description
Get the first connection request waiting for this port and return it as a connected socket.
If no connection request is waiting and the port is in nonblocking mode (i.e. an accept callback is installed) then zero is returned. Otherwise this function waits until a connection has arrived.
In Pike 7.8 and later the returned object is created via
fd_factory().- Note
In Pike 7.7 and later the resulting file object will be assigned to the same backend as the port object.
- Method
bind
intbind(int|stringport,void|function(:void)accept_callback,void|stringip,void|stringreuse_port)- Description
Opens a socket and binds it to port number on the local machine. If the second argument is present, the socket is set to nonblocking and the callback funcition is called whenever something connects to it. The callback will receive the id for this port as argument and should typically call
acceptto establish a connection.If the optional argument
ipis given,bindwill try to bind to an interface with that host name or IP number. Omitting this will bind to all available IPv4 addresses; specifying "::" will bind to all IPv4 and IPv6 addresses.If the OS supports TCP_FASTOPEN it is enabled automatically.
If the OS supports SO_REUSEPORT it is enabled if the fourth argument is true.
- Returns
1 is returned on success, zero on failure.
errnoprovides further details about the error in the latter case.- See also
accept,set_id
- Method
bind_unix
intbind_unix(stringpath,void|function(:void)accept_callback)- Description
Opens a Unix domain socket at the given path in the file system. If the second argument is present, the socket is set to nonblocking and the callback funcition is called whenever something connects to it. The callback will receive the id for this port as argument and should typically call
acceptto establish a connection.- Returns
1 is returned on success, zero on failure.
errnoprovides further details about the error in the latter case.- Note
This function is only available on systems that support Unix domain sockets.
- Note
pathhad a quite restrictive length limit (~100 characters) prior to Pike 7.8.334.- See also
accept,set_id
- Method
create
_Stdio._port_Stdio._port(int|stringport,void|function(:void)accept_callback,void|stringip)_Stdio._port_Stdio._port("stdin",void|function(:void)accept_callback)- Description
When called with an int or any string except
"stdin"as first argument, this function does the same asbind()would do with the same arguments.When called with
"stdin"as argument, a socket is created out of the file descriptor 0. This is only useful if that actually IS a socket to begin with, and is equivalent to creating a port and initializing it withlisten_fd(0).- See also
bind,listen_fd
- Method
errno
interrno()- Description
If the last call done on this port failed, this function will return an integer describing what went wrong. Refer to your unix manual for further information.
- Method
fd_factory
protectedStdio.Fdfd_factory()- Description
Factory creating empty
Stdio.Fdobjects.- Returns
Returns a new unopened
Stdio.Fdobject.The default implementation creates an empty
Stdio.Fdobject.- See also
accept(),Stdio.File()->fd_factory()
- Method
listen_fd
intlisten_fd(intfd,void|function(:void)accept_callback)- Description
This function does the same as
bind, except that instead of creating a new socket and bind it to a port, it expects the file descriptorfdto be an already open port.- Note
This function is only for the advanced user, and is generally used when sockets are passed to Pike at exec time.
- See also
bind,accept
- Method
query_address
stringquery_address()- Description
Get the address and port of the local socket end-point.
- Returns
This function returns the address and port of a socket end-point on the form
"x.x.x.x port"(IPv4) or"x:x:x:x:x:x:x:x port"(IPv6).If there is some error querying or formatting the address,
0(zero) is returned anderrno()will return the error code.- Throws
An error is thrown if the socket isn't bound.
- Method
query_backend
Pike.Backendquery_backend()- Description
Return the backend used for the accept callback.
- See also
set_backend
- Method
query_fd
intquery_fd()- Description
Returns the file descriptor number associated with this object.
- Method
query_id
mixedquery_id()- Description
This function returns the id for this port. The id is normally the first argument to accept_callback.
- See also
set_id
- Method
set_accept_callback
voidset_accept_callback(function(:void)|voidaccept_callback)- Description
Change or remove the accept callback.
- Parameter
accept_callback New accept callback.
- See also
bind(),listen_fd(),set_id()
- Method
set_backend
voidset_backend(Pike.Backendbackend)- Description
Set the backend used for the accept callback.
- Note
The backend keeps a reference to this object as long as the port is accepting connections, but this object does not keep a reference to the backend.
- See also
query_backend
- Variable
_id
Class _Stdio.sendfile
- Description
Send
headers + from_fd[off..off+len-1] + trailerstoto_fdasyncronously.- Note
This is the low-level implementation, which has several limitations. You probably want to use
Stdio.sendfile()instead.- See also
Stdio.sendfile()
- Method
create
_Stdio.sendfile_Stdio.sendfile(array(string)headers,objectfrom,intoffset,intlen,array(string)trailers,objectto,function(:void)callback,mixed...args)- Description
Low-level implementation of
Stdio.sendfile().Sends
headersfollowed bylenbytes starting atoffsetfrom the filefromfollowed bytrailersto the fileto. When completedcallbackwill be called with the total number of bytes sent as the first argument, followed byargs.Any of
headers,fromandtrailersmay be left out by setting them to0.Setting
offsetto-1means send from the current position infrom.Setting
lento-1means send untilfrom's end of file is reached.- Note
Don't use this class directly! Use
Stdio.sendfile()instead.In Pike 7.7 and later the
callbackfunction will be called from the backend associated withto.- Note
May use blocking I/O and thus trigger process being killed with SIGPIPE when the other end closes the connection. Add a call to
signal()to avoid this.- See also
Stdio.sendfile()
Module _Stdio.IPPROTO
- Description
Module containing various IP-protocol options.
Module _Stdio.SOCK
- Description
Module containing constants for specifying socket options.