You are currently viewing a snapshot of www.mozilla.org taken on April 21, 2008. Most of this content is highly out of date (some pages haven't been updated since the project began in 1998) and exists for historical purposes only. If there are any pages on this archive site that you think should be added back to www.mozilla.org, please file a bug.



NSPR Reference
Previous     Contents     Next     


Chapter 10   I/O Functions

This chapter describes the NSPR functions used to perform operations such as system access, normal file I/O, and socket (network) I/O.

For sample code that illustrates basic I/O operations, see Introduction to NSPR. For information about the types most commonly used with the functions described in this chapter, see Chapter 9 "I/O Types"

Functions that Operate on Pathnames
Functions that Act on File Descriptors
Directory I/O Functions
Socket Manipulation Functions
Converting Between Host and Network Addresses
Memory-Mapped I/O Functions
Anonymous Pipe Function
Polling Functions
Manipulating Layers

Functions that Operate on Pathnames

A file or directory in a file system is specified by its pathname. NSPR uses Unix-style pathnames, which are null-terminated character strings. Only the ASCII character set is supported. The forward slash (/) separates the directories in a pathname. NSPR converts the slashes in a pathname to the directory separator of the native OS--for example, backslash (\) on Windows and colon (:) on Mac OS--before passing it to the native system calls.

Some file systems also differentiate drives or volumes.

PR_Open
PR_Delete
PR_GetFileInfo
PR_GetFileInfo64
PR_Rename
PR_Access

PR_Open

Opens a file for reading, writing, or both. Also used to create a file.


Syntax
#include <prio.h> 

PRFileDesc* PR_Open(
   const char *name,
   PRIntn flags,
   PRIntn mode);


Parameters
The function has the following parameters:

name

The pathname of the file to be opened.

flags

File status flags. PR_Open performs a bitwise OR of the following bit flags:

  • PR_RDONLY. Open for reading only.

  • PR_WRONLY. Open for writing only.

  • PR_RDWR. Open for reading and writing.

  • PR_CREATE_FILE. If the file does not exist, the file is created. If the file exists, this flag has no effect.

  • PR_APPEND. The file pointer is set to the end of the file prior to each write.

  • PR_TRUNCATE. If the file exists, its length is truncated to 0.

  • PR_SYNC. If set, each write will wait for both the file data and file status to be physically updated.

  • PR_EXCL. Used with PR_CREATE_FILE; if the file does not exist, the file is created. If the file already exists, no action and NULL is returned

In most cases, only one of the first three flags may be used. If the flags parameter does include any of the first three flags (PR_RDONLY, PR_WRONLY, or PR_RDWR), the open file can't be read or written, which is not useful.

mode

Access permission bits of the file mode, if the file is created when PR_CREATE_FILE is on.

The mode parameter is currently applicable only on Unix platforms. It may apply to other platforms in the future. Possible values of the mode parameter include the following:

  • 00400. Read by owner.

  • 00200. Write by owner.

  • 00100. Execute (search if a directory) by owner.

  • 00040. Read by group.

  • 00020. Write by group.

  • 00010. Execute by group.

  • 00004. Read by others.

  • 00002. Write by others.

  • 00001. Execute by others.


Returns
The function returns one of the following values:

  • If the file is successfully opened, a pointer to a dynamically allocated PRFileDesc for the newly opened file. The PRFileDesc should be freed by calling PR_Close.

  • If the file was not opened successfully, a NULL pointer.


Description
PR_Open creates a file descriptor (PRFileDesc) for the file with the pathname name and sets the file status flags of the file descriptor according to the value of flags. If a new file is created as a result of the PR_Open call, its file mode bits are set according to the mode parameter.

PR_Delete

Deletes a file.


Syntax
#include <prio.h> 

PRStatus PR_Delete(const char *name);


Parameter
The function has the following parameter:

name

The pathname of the file to be deleted.


Returns
One of the following values:

  • If the file is successfully deleted, PR_SUCCESS.

  • If the file is not successfully deleted, PR_FAILURE.


Description
Deletes a file from the file system. The operation may fail if the file is already open.

PR_GetFileInfo

Gets information about a file with a specified pathname. File size is expressed as a 32-bit integer.


Syntax
#include <prio.h> 

PRStatus PR_GetFileInfo(
   const char *fn,
   PRFileInfo *info);


Parameters
The function has the following parameters:

fn

The pathname of the file to get information about.

info

A pointer to a file information object (see PRFileInfo). On output, PR_GetFileInfo writes information about the given file to the file information object.


Returns
The function returns one of the following values:

  • If file information is successfully obtained, PR_SUCCESS.

  • If file information is not successfully obtained, PR_FAILURE.


Description
PR_GetFileInfo stores information about the file with the specified pathname in the PRFileInfo structure pointed to by info. The file size is returned as an unsigned 32-bit integer.


See also
For the 64-bit version of this function, see PR_GetFileInfo64. To get equivalent information on a file that's already open, use PR_GetOpenFileInfo.

PR_GetFileInfo64

Gets information about a file with a specified pathname. File size is expressed as a 64-bit integer.


Syntax
#include <prio.h> 

PRStatus PR_GetFileInfo64(
   const char *fn,
   PRFileInfo64 *info);


Parameters
The function has the following parameters:

fn

The pathname of the file to get information about.

info

A pointer to a 64-bit file information object (see PRFileInfo64). On output, PR_GetFileInfo64 writes information about the given file to the file information object.


Returns
The function returns one of the following values:

  • If file information is successfully obtained, PR_SUCCESS.

  • If file information is not successfully obtained, PR_FAILURE.


Description
PR_GetFileInfo64 stores information about the file with the specified pathname in the PRFileInfo64 structure pointed to by info. The file size is returned as an unsigned 64-bit integer.


See also
For the 32-bit version of this function, see PR_GetFileInfo. To get equivalent information on a file that's already open, use PR_GetOpenFileInfo64.

PR_Rename

Renames a file.


Syntax
#include <prio.h> 

PRStatus PR_Rename(
   const char *from,
   const char *to);


Parameters
The function has the following parameters:

from

The old name of the file to be renamed.

to

The new name of the file.


Returns
The function returns one of the following values:

  • If file is successfully renamed, PR_SUCCESS.

  • If file is not successfully renamed, PR_FAILURE.


Description
PR_Rename renames a file from its old name (from) to a new name (to). If a file with the new name already exists, PR_Rename fails with the error code PR_FILE_EXISTS_ERROR. In this case, PR_Rename does not overwrite the existing filename.

PR_Access

Determines the accessibility of a file.


Syntax
#include <prio.h> 

PRStatus PR_Access(
   const char *name,
   PRAccessHow how);


Parameters
The function has the following parameters:

name

The pathname of the file whose accessibility is to be determined.

how

Specifies which access permission to check for. Use one of the following values:

  • PR_ACCESS_READ_OK. Test for read permission.

  • PR_ACCESS_WRITE_OK. Test for write permission.

  • PR_ACCESS_EXISTS. Check existence of file.


Returns
The function returns one of the following values:

  • If the requested access is permitted, PR_SUCCESS.

  • If the requested access is not permitted, PR_FAILURE.


Description
This is the declaration for the enumeration PRAccessHow, used in the how parameter:

typedef enum PRAccessHow {
   PR_ACCESS_EXISTS = 1,
   PR_ACCESS_WRITE_OK = 2,
   PR_ACCESS_READ_OK = 3
} PRAccessHow;

Functions that Act on File Descriptors

PR_Close
PR_Read
PR_Write
PR_Writev
PR_GetOpenFileInfo
PR_GetOpenFileInfo64
PR_Seek
PR_Seek64
PR_Available
PR_Available64
PR_Sync
PR_GetDescType
PR_GetSpecialFD

PR_Close

Closes a file descriptor.


Syntax
#include <prio.h> 

PRStatus PR_Close(PRFileDesc *fd);


Parameter
The function has the following parameter:

fd

A pointer to a PRFileDesc object.


Returns
The function returns one of the following values:

  • If file descriptor is closed successfully, PR_SUCCESS.

  • If the file descriptor is not closed successfully, PR_FAILURE.


Description
The file descriptor may represent a normal file, a socket, or an end point of a pipe. On successful return, PR_Close frees the dynamic memory and other resources identified by the fd parameter.

PR_Read

Reads bytes from a file or socket.


Syntax
#include <prio.h> 

PRInt32 PR_Read(PRFileDesc *fd, 
               void *buf,
               PRInt32 amount);


Parameters
The function has the following parameters:

fd

A pointer to the PRFileDesc object for the file or socket.

buf

A pointer to a buffer to hold the data read in. On output, the buffer contains the data.

amount

The size of buf (in bytes).


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes actually read in.

  • The value 0 means end of file is reached or the network connection is closed.

  • The value -1 indicates a failure. To get the reason for the failure, call PR_GetError.


Description
The thread invoking PR_Read blocks until it encounters an end-of-stream indication, some positive number of bytes (but no more than amount bytes) are read in, or an error occurs.

PR_Write

Writes a buffer of data to a file or socket.


Syntax
#include <prio.h> 

PRInt32 PR_Write(
   PRFileDesc *fd,
   const void *buf,
   PRInt32 amount);


Parameters
The function has the following parameters:

fd

A pointer to the PRFileDesc object for a file or socket.

buf

A pointer to the buffer holding the data to be written.

amount

The amount of data, in bytes, to be written from the buffer.


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes successfully written.

  • The value -1 indicates that the operation failed. The reason for the failure is obtained by calling PR_GetError.


Description
The thread invoking PR_Write blocks until all the data is written or the write operation fails. Therefore, the return value is equal to either amount (success) or -1 (failure). Note that if PR_Write returns -1, some data (less than amount bytes) may have been written before an error occurred.

PR_Writev

Writes data to a socket from multiple buffers.


Syntax
#include <prio.h> 

PRInt32 PR_Writev(
   PRFileDesc *fd,
   PRIOVec *iov,
   PRInt32 size,
   PRIntervalTime timeout);

#define PR_MAX_IOVECTOR_SIZE 16


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object for a socket.

iov

An array of PRIOVec structures that describe the buffers to write from.

size

Number of PRIOVec structures in the iov array. The value of this parameter must not be greater than PR_MAX_IOVECTOR_SIZE. If it is, the function will fail and the error will be set to PR_BUFFER_OVERFLOW_ERROR.

timeout

A value of type PRIntervalTime describing the time limit for completion of the entire write operation.


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes successfully written.

  • The value -1 is an indication that the operation failed. The reason for the failure can be obtained by calling PR_GetError.


Description
The thread calling PR_Writev blocks until all the data is written or the write operation fails. Therefore, the return value is equal to either the sum of all the buffer lengths (on success) or -1 (on failure). Note that if PR_Writev returns -1, part of the data may have been written before an error occurred. If the timeout parameter is not PR_INTERVAL_NO_TIMEOUT and all the data cannot be written in the specified interval, PR_Writev returns -1 with the error code PR_IO_TIMEOUT_ERROR.

This is the type definition for PRIOVec:

typedef struct PRIOVec {
   char *iov_base;
   int iov_len;
} PRIOVec;

The PRIOVec structure has the following fields:

iov_base

A pointer to the beginning of the buffer.

iov_len

The size of the buffer.

PR_GetOpenFileInfo

Gets an open file's information. File size is expressed as a 32-bit integer.


Syntax
#include <prio.h> 

PRStatus PR_GetOpenFileInfo(
   PRFileDesc *fd,
   PRFileInfo *info);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object for an open file.

info

A pointer to a PRFileInfo object. On output, information about the given file is written into the file information object.


Returns
The function returns one of the following values:

  • If file information is successfully obtained, PR_SUCCESS.

  • If file information is not successfully obtained, PR_FAILURE.


Description
PR_GetOpenFileInfo obtains the file type (normal file, directory, or other), file size (as a 32-bit integer), and the file creation and modification times of the open file represented by the file descriptor.


See also
For the 64-bit version of this function, see PR_GetOpenFileInfo64. To get equivalent information on a file that's not already open, use PR_GetFileInfo.

PR_GetOpenFileInfo64

Gets an open file's information. File size is expressed as a 64-bit integer.


Syntax
#include <prio.h> 

PRStatus PR_GetOpenFileInfo64(
   PRFileDesc *fd,
   PRFileInfo64 *info);


Parameters
The function has the following parameter:

fd

A pointer to a PRFileDesc object for an open file.

info

A pointer to a PRFileInfo64 object. On output, information about the specified file is written into the file information object.


Returns
The function returns one of the following values:

  • If file information is successfully obtained, PR_SUCCESS.

  • If file information is not successfully obtained, PR_FAILURE.


Description
PR_GetOpenFileInfo64 is the 64-bit version of PR_GetOpenFileInfo. It obtains the file type (normal file, directory, or other), file size (as a 64-bit integer), and the creation and modification times of the open file represented by the file descriptor.


See also
For the 32-bit version of this function, see PR_GetOpenFileInfo. To get equivalent information on a file that's not already open, use PR_GetFileInfo64.

PR_Seek

Moves the current read-write file pointer by an offset expressed as a 32-bit integer.


Syntax
#include <prio.h> 

PRInt32 PR_Seek(
   PRFileDesc *fd,
   PRInt32 offset,
   PRSeekWhence whence);


Parameters
The function has the following parameters:

fd

Pointer to a PRFileDesc object.

offset

A value, in bytes, used with the whence parameter to set the file pointer. A negative value causes seeking in the reverse direction.

whence

A value of type PRSeekWhence that specifies how to interpret the offset parameter in setting the file pointer associated with the fd parameter. The value for the whence parameter can be one of the following:

  • PR_SEEK_SET. Sets the file pointer to the value of the offset parameter.

  • PR_SEEK_CUR. Sets the file pointer to its current location plus the value of the offset parameter.

  • PR_SEEK_END. Sets the file pointer to the size of the file plus the value of the offset parameter.


Returns
The function returns one of the following values:

  • If the function completes successfully, the resulting pointer location, measured in bytes from the beginning of the file.

  • If the function fails, the file pointer remains unchanged and the function returns the value -1. The error code can then be retrieved with PR_GetError.


Description
Here's an idiom for obtaining the current location of the file pointer for the file descriptor in the fd parameter:

PR_Seek(fd, 0, PR_SEEK_CUR)


See also
If you need to move the file pointer by a large offset that's out of the range of a 32-bit integer, use PR_Seek64.

PR_Seek64

Moves the current read-write file pointer by an offset expressed as a 64-bit integer.


Syntax
#include <prio.h> 

PRInt64 PR_Seek64(
   PRFileDesc *fd,
   PRInt64 offset,
   PRSeekWhence whence);


Parameters
The function has the following parameters:

fd

Pointer to a PRFileDesc object.

offset

A value, in bytes, that is used with the whence parameter to set the file pointer. A negative value causes seeking in the reverse direction.

whence

A value of type PRSeekWhence that specifies how to interpret the offset parameter in setting the file pointer associated with the fd parameter. The value for the whence parameter can be one of the following:

  • PR_SEEK_SET. Sets the file pointer to the value of the offset parameter.

  • PR_SEEK_CUR. Sets the file pointer to its current location plus the value of the offset parameter.

  • PR_SEEK_END. Sets the file pointer to the size of the file plus the value of the offset parameter.


Returns
The function returns one of the following values:

  • If the function completes successfully, the resulting pointer location, measured in bytes from the beginning of the file.

  • If the function fails, the file offset remains unchanged and the function returns the value -1. The error code can then be retrieved via PR_GetError.


Description
This is the idiom for obtaining the current location (expressed as a 64-bit integer) of the file pointer for the file descriptor in the fd parameter:

PR_Seek64(fd, 0, PR_SEEK_CUR)

If the native operating system is capable of handling only a 32-bit file offset, PR_Seek64 may fail with the error code PR_FILE_TOO_BIG_ERROR if the offset parameter is out of the range of a 32-bit integer.


See also
PR_Seek.

PR_Available

Determines the number of bytes (expressed as a 32-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket.


Syntax
#include <prio.h> 

PRInt32 PR_Available(PRFileDesc *fd);


Parameter
The function has the following parameter:

fd

Pointer to a PRFileDesc object representing a file or socket.


Returns
The function returns one of the following values:

  • If the function completes successfully, it returns the number of bytes that are available for reading. For a normal file, these are the bytes beyond the current file pointer.

  • If the function fails, it returns the value -1. The error code can then be retrieved via PR_GetError.


Description
PR_Available works on normal files and sockets. PR_Available does not work with pipes on Win32 platforms.


See also
If the number of bytes available for reading is out of the range of a 32-bit integer, use PR_Available64.

PR_Available64

Determines the number of bytes (expressed as a 64-bit integer) that are available for reading beyond the current read-write pointer in a specified file or socket.


Syntax
#include <prio.h> 

PRInt64 PR_Available64(PRFileDesc *fd);


Parameter
The function has the following parameter:

fd

Pointer to a PRFileDesc object representing a file or socket.


Returns
The function returns one of the following values:

  • If the function completes successfully, it returns the number of bytes that are available for reading. For a normal file, these are the bytes beyond the current file pointer.

  • If the function fails, it returns the value -1. The error code can then be retrieved via PR_GetError.


Description
PR_Available64 works on normal files and sockets. PR_Available does not work with pipes on Win32 platforms.


See also
If the number of bytes available for reading is within the range of a 32-bit integer, use PR_Available.

PR_Sync

Synchronizes any buffered data for a file descriptor to its backing device (disk).


Syntax
#include <prio.h> 

PRStatus PR_Sync(PRFileDesc *fd);


Parameter
The function has the following parameter:

fd

Pointer to a PRFileDesc object representing a file.


Returns
The function returns one of the following values:

  • On successful completion, PR_SUCCESS.

  • If the function fails, PR_FAILURE.


Description
PR_Sync writes all the in-memory buffered data of the specified file to the disk.

PR_GetDescType

Describes what type of file is referenced by a specified file descriptor.


Syntax
#include <prio.h> 

PRDescType PR_GetDescType(PRFileDesc *file);


Parameters
The function has the following parameters:

file

A pointer to a PRFileDesc object whose descriptor type is to be returned.


Returns
The function returns a PRDescType enumeration constant that describes the type of file.


Description
The PRDescType enumeration is defined as follows:

typedef enum PRDescType {
   PR_DESC_FILE       = 1,
   PR_DESC_SOCKET_TCP = 2,
   PR_DESC_SOCKET_UDP = 3,
   PR_DESC_LAYERED    = 4
} PRDescType;

The enumeration has the following enumerators:

PR_DESC_FILE

The PRFileDesc object represents a normal file.

PR_DESC_SOCKET_TCP

The PRFileDesc object represents a TCP socket.

PR_DESC_SOCKET_UDP

The PRFileDesc object represents a UDP socket.

PR_DESC_LAYERED

The PRFileDesc object is a layered file descriptor.

PR_GetSpecialFD

Gets the file descriptor that represents the standard input, output, or error stream.


Syntax
#include <prio.h> 

PRFileDesc* PR_GetSpecialFD(PRSpecialFD id);


Parameter
The function has the following parameter:

id

A pointer to an enumerator of type PRSpecialFD, indicating the type of I/O stream desired: PR_StandardInput, PR_StandardOutput, or PR_StandardError.


Returns
If the id parameter is valid, PR_GetSpecialFD returns a file descriptor that represents the corresponding standard I/O stream. Otherwise, PR_GetSpecialFD returns NULL and sets the error to PR_INVALID_ARGUMENT_ERROR.


Description
Type PRSpecialFD is defined as follows:

typedef enum PRSpecialFD{
PR_StandardInput,
PR_StandardOutput,
PR_StandardError
} PRSpecialFD;

#define PR_STDIN   PR_GetSpecialFD(PR_StandardInput)
#define PR_STDOUT   PR_GetSpecialFD(PR_StandardOutput)
#define PR_STDERR   PR_GetSpecialFD(PR_StandardError)

File descriptors returned by PR_GetSpecialFD are owned by the runtime and should not be closed by the caller.

Directory I/O Functions

PR_OpenDir
PR_ReadDir
PR_CloseDir
PR_MkDir
PR_RmDir

PR_OpenDir

Opens the directory with the specified pathname.


Syntax
#include <prio.h> 

PRDir* PR_OpenDir(const char *name);


Parameter
The function has the following parameter:

name

The pathname of the directory to be opened.


Returns
The function returns one of the following values:

  • If the directory is successfully opened, a PRDir object is dynamically allocated and the function returns a pointer to it.

  • If the directory cannot be opened, the function returns NULL.


Description
PR_OpenDir opens the directory specified by the pathname name and returns a pointer to a directory stream (a PRDir object) that can be passed to subsequent PR_ReadDir calls to get the directory entries (files and subdirectories) in the directory. The PRDir pointer should eventually be closed by a call to PR_CloseDir.

PR_ReadDir

Gets a pointer to the next entry in the directory.


Syntax
#include <prio.h> 

PRDirEntry* PR_ReadDir(
   PRDir *dir,
   PRDirFlags flags);


Parameters
The function has the following parameters:

dir

A pointer to a PRDir object that designates an open directory.

flags

Specifies which directory entries, if any, to skip. Values can include the following:

  • PR_SKIP_NONE. Do not skip any files.

  • PR_SKIP_DOT. Skip the directory entry "." representing the current directory.

  • PR_SKIP_DOT_DOT. Skip the directory entry ".." representing the parent directory.

  • PR_SKIP_BOTH. Skip both "." and ".."

  • PR_SKIP_HIDDEN. Skip hidden files. On Windows platforms and the Mac OS, this value identifies files with the "hidden" attribute set. On Unix platform, this value identifies files whose names begin with a period (".").


Returns
The function returns one of the following values:

  • A pointer to the next entry in the directory.

  • If the end of the directory is reached or an error occurs, NULL. The reason can be retrieved via PR_GetError.


Description
PR_ReadDir returns a pointer to a directory entry structure:

struct PRDirEntry {
   const char *name;
};

typedef struct PRDirEntry PRDirEntry;

The structure has the following field:

name

Name of entry, relative to directory name.

The flags parameter is an enum of type PRDirFlags:

typedef enum PRDirFlags {
   PR_SKIP_NONE    = 0x0,
   PR_SKIP_DOT     = 0x1,
   PR_SKIP_DOT_DOT = 0x2,
   PR_SKIP_BOTH    = 0x3,
   PR_SKIP_HIDDEN  = 0x4
} PRDirFlags;

The memory associated with the returned PRDirEntry structure is managed by NSPR. The caller must not free the PRDirEntry structure. Moreover, the PRDirEntry structure returned by each PR_ReadDir call is valid only until the next PR_ReadDir or PR_CloseDir call on the same PRDir object.

If the end of the directory is reached, PR_ReadDir returns NULL, and PR_GetError returns PR_NO_MORE_FILES_ERROR.


See also
PR_OpenDir

PR_CloseDir

Closes the specified directory.


Syntax
#include <prio.h> 

PRStatus PR_CloseDir(PRDir *dir);


Parameter
The function has the following parameter:

dir

A pointer to a PRDir structure representing the directory to be closed.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be retrieved via PR_GetError.


Description
When a PRDir object is no longer needed, it must be closed and freed with a call to PR_CloseDir call. Note that after a PR_CloseDir call, any PRDirEntry object returned by a previous PR_ReadDir call on the same PRDir object becomes invalid.


See also
PR_OpenDir

PR_MkDir

Creates a directory with a specified name and access mode.


Syntax
#include <prio.h> 

PRStatus PR_MkDir(
   const char *name,
   PRIntn mode);


Parameters
The function has the following parameters:

name

The name of the directory to be created. All the path components up to but not including the leaf component must already exist.

mode

The access permission bits of the file mode of the new directory if the file is created when PR_CREATE_FILE is on.

Caveat: The mode parameter is currently applicable only on Unix platforms. It may be applicable to other platforms in the future.

Possible values include the following:

  • 00400. Read by owner.

  • 00200. Write by owner.

  • 00100. Search by owner.

  • 00040. Read by group.

  • 00020. Write by group.

  • 00010. Search by group.

  • 00004. Read by others.

  • 00002. Write by others.

  • 00001. Search by others.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The actual reason can be retrieved via PR_GetError.


Description
PR_MkDir creates a new directory with the pathname name. All the path components up to but not including the leaf component must already exist. For example, if the pathname of the directory to be created is a/b/c/d, the directory a/b/c must already exist.


See also
PR_RmDir.

PR_RmDir

Removes a directory with a specified name.


Syntax
#include <prio.h> 

PRStatus PR_RmDir(const char *name);


Parameter
The function has the following parameter:

name

The name of the directory to be removed.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The actual reason can be retrieved via PR_GetError.


Description
PR_RmDir removes the directory specified by the pathname name. The directory must be empty. If the directory is not empty, PR_RmDir fails and PR_GetError returns the error code PR_DIRECTORY_NOT_EMPTY_ERROR.


See also
PR_MkDir.

Socket Manipulation Functions

The network programming interface presented here is a socket API modeled after the popular Berkeley sockets. Differences include the following:

  • The blocking socket functions in NSPR take a timeout parameter.

  • Two new functions, PR_TransmitFile and PR_AcceptRead, can exploit the new system calls of some operating systems for higher performance.

For a useful supplement to the NSPR documentation, see the textbook Unix Network Programming, 2nd Ed., Vol. 1: Networking APIs: Sockets and XTI, by W. Richard Stevens (Prentice Hall PTR, 1998).

PR_NewUDPSocket
PR_NewTCPSocket
PR_Connect
PR_Accept
PR_Bind
PR_Listen
PR_Shutdown
PR_Recv
PR_Send
PR_RecvFrom
PR_SendTo
PR_TransmitFile
PR_AcceptRead
PR_GetSockName
PR_GetPeerName
PR_GetSocketOption
PR_SetSocketOption

PR_NewUDPSocket

Creates a new UDP socket.


Syntax
#include <prio.h> 

PRFileDesc* PR_NewUDPSocket(void);


Returns
The function returns one of the following values:

  • Upon successful completion, a pointer to the PRFileDesc object created for the newly opened UDP socket.

  • If the creation of a new UDP socket failed, NULL.


Description
UDP (User Datagram Protocol) is a connectionless, unreliable datagram protocol of the TCP/IP protocol suite. UDP datagrams may be lost or delivered in duplicates or out of sequence.

PR_NewUDPSocket creates a new UDP socket. The socket may be bound to a well-known port number with PR_Bind. Datagrams can be sent with PR_SendTo and received with PR_RecvFrom. When the socket is no longer needed, it should be closed with a call to PR_Close.

PR_NewTCPSocket

Creates a new TCP socket.


Syntax
#include <prio.h> 

PRFileDesc* PR_NewTCPSocket(void);


Returns
The function returns one of the following values:

  • Upon successful completion, a pointer to the PRFileDesc object created for the newly opened TCP socket.

  • If the creation of a new TCP socket failed, NULL.


Description
TCP (Transmission Control Protocol) is a connection-oriented, reliable byte-stream protocol of the TCP/IP protocol suite. PR_NewTCPSocket creates a new TCP socket. A TCP connection is established by a passive socket (the server) accepting a connection setup request from an active socket (the client). Typically, the server binds its socket to a well-known port with PR_Bind, calls PR_Listen to start listening for connection setup requests, and calls PR_Accept to accept a connection. The client makes a connection request using PR_Connect.

After a connection is established, the client and server may send and receive data between each other. To receive data, one can call PR_Read or PR_Recv. To send data, one can call PR_Write, PR_Writev, PR_Send, or PR_TransmitFile. PR_AcceptRead is suitable for use by the server to accept a new client connection and read the client's first request in one function call.

A TCP connection can be shut down by PR_Shutdown, and the sockets should be closed by PR_Close.

PR_Connect

Initiates a connection on a specified socket.


Syntax
#include <prio.h> 

PRStatus PR_Connect(
   PRFileDesc *fd,
   PRNetAddr *addr,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a socket.

addr

A pointer to the address of the peer to which the socket is to be connected.

timeout

A value of type PRIntervalTime specifying the time limit for completion of the connect operation.


Returns
The function returns one of the following values:

  • Upon successful completion of connection setup, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. Further information can be obtained by calling PR_GetError.


Description
PR_Connect is usually invoked on a TCP socket, but it may also be invoked on a UDP socket. Both cases are discussed here.

If the socket is a TCP socket, PR_Connect establishes a TCP connection to the peer. If the socket is not bound, it will be bound to an arbitrary local address.

PR_Connect blocks until either the connection is successfully established or an error occurs. If the timeout parameter is not PR_INTERVAL_NO_TIMEOUT and the connection setup cannot complete before the time limit, PR_Connect fails with the error code PR_IO_TIMEOUT_ERROR.

If the socket is a UDP socket, there is no connection setup to speak of, since UDP is connectionless. If PR_Connect is invoked on a UDP socket, it has an overloaded meaning: PR_Connect merely saves the specified address as the default peer address for the socket, so that subsequently one can send and receive datagrams from the socket using PR_Send and PR_Recv instead of the usual PR_SendTo and PR_RecvFrom.

PR_Accept

Accepts a connection on a specified socket.


Syntax
#include <prio.h> 

PRFileDesc* PR_Accept(
   PRFileDesc *fd,
   PRNetAddr *addr,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing the rendezvous socket on which the caller is willing to accept new connections.

addr

A pointer to a structure of type PRNetAddr. On output, this structure contains the address of the connecting entity.

timeout

A value of type PRIntervalTime specifying the time limit for completion of the accept operation.


Returns
The function returns one of the following values:

  • Upon successful acceptance of a connection, a pointer to a new PRFileDesc structure representing the newly accepted connection.

  • If unsuccessful, NULL. Further information can be obtained by calling PR_GetError.


Description
The socket fd is a rendezvous socket that has been bound to an address with PR_Bind and is listening for connections after a call to PR_Listen. PR_Accept accepts the first connection from the queue of pending connections and creates a new socket for the newly accepted connection. The rendezvous socket can still be used to accept more connections.

If the addr parameter is not NULL, PR_Accept stores the address of the connecting entity in the PRNetAddr object pointed to by addr.

PR_Accept blocks the calling thread until either a new connection is successfully accepted or an error occurs. If the timeout parameter is not PR_INTERVAL_NO_TIMEOUT and no pending connection can be accepted before the time limit, PR_Accept returns NULL with the error code PR_IO_TIMEOUT_ERROR.

PR_Bind

Binds an address to a specified socket.


Syntax
#include <prio.h> 

PRStatus PR_Bind(
   PRFileDesc *fd,
   PRNetAddr *addr);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a socket.

addr

A pointer to a PRNetAddr object representing the address to which the socket will be bound.


Returns
The function returns one of the following values:

  • Upon successful binding of an address to a socket, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. Further information can be obtained by calling PR_GetError.


Description
When a new socket is created, it has no address bound to it. PR_Bind assigns the specified address (also known as name) to the socket. If you do not care about the exact IP address assigned to the socket, set the inet.ip field of PRNetAddr to PR_htonl(PR_INADDR_ANY). If you do not care about the TCP/UDP port assigned to the socket, set the inet.port field of PRNetAddr to 0.

Note that if PR_Connect is invoked on a socket that is not bound, it implicitly binds an arbitrary address the socket.

Call PR_GetSockName to obtain the address (name) bound to a socket.

PR_Listen

Listens for connections on a specified socket.


Syntax
#include <prio.h> 

PRStatus PR_Listen(
   PRFileDesc *fd,
   PRIntn backlog);


Parameters
The function has the following parameters:
fd

A pointer to a PRFileDesc object representing a socket that will be used to listen for new connections.

backlog

The maximum length of the queue of pending connections.


Returns
The function returns one of the following values:

  • Upon successful completion of listen request, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. Further information can be obtained by calling PR_GetError.


Description
PR_Listen turns the specified socket into a rendezvous socket. It creates a queue for pending connections and starts to listen for connection requests on the socket. The maximum size of the queue for pending connections is specified by the backlog parameter. Pending connections may be accepted by calling PR_Accept.

PR_Shutdown

Shuts down part of a full-duplex connection on a specified socket.


Syntax
#include <prio.h> 

PRStatus PR_Shutdown(
   PRFileDesc *fd,
   PRShutdownHow how);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a connected socket.

how

The kind of disallowed operations on the socket. Possible values include the following:

  • PR_SHUTDOWN_RCV. Further receives will be disallowed.

  • PR_SHUTDOWN_SEND. Further sends will be disallowed.

  • PR_SHUTDOWN_BOTH. Further sends and receives will be disallowed.


Returns
The function returns one of the following values:

  • Upon successful completion of shutdown request, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. Further information can be obtained by calling PR_GetError.


Description
The PRShutdownHow enumeration is defined as follows:

typedef enum PRShutdownHow{
   PR_SHUTDOWN_RCV = 0,
   PR_SHUTDOWN_SEND = 1,
   PR_SHUTDOWN_BOTH = 2
} PRShutdownHow;

PR_Recv

Receives bytes from a connected socket.


Syntax
#include <prio.h> 

PRInt32 PR_Recv(
   PRFileDesc *fd,
   void *buf,
   PRInt32 amount,
   PRIntn flags,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a socket.

buf

A pointer to a buffer to hold the data received.

amount

The size of buf (in bytes).

flags

This obsolete parameter must always be zero.

timeout

A value of type PRIntervalTime specifying the time limit for completion of the receive operation.


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes actually received.

  • The value 0 means the network connection is closed.

  • The value -1 indicates a failure. The reason for the failure can be obtained by calling PR_GetError.


Description
PR_Recv blocks until some positive number of bytes are transferred, a timeout occurs, or an error occurs. No more than amount bytes will be transferred.

PR_Send

Sends bytes from a connected socket.


Syntax
#include <prio.h> 

PRInt32 PR_Send(
   PRFileDesc *fd,
   const void *buf,
   PRInt32 amount,
   PRIntn flags,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a socket.

buf

A pointer to a buffer containing the data to be sent.

amount

The size of buf (in bytes).

flags

This obsolete parameter must always be zero.

timeout

A value of type PRIntervalTime specifying the time limit for completion of the send operation.


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes successfully sent. If the parameter fd is a blocking socket, this number must always equal amount.

  • The value -1 indicates a failure. The reason for the failure can be obtained by calling PR_GetError.


Description
PR_Send blocks until all bytes are sent, a timeout occurs, or an error occurs.

PR_RecvFrom

Receives bytes from a socket and stores the sending peer's address.


Syntax
#include <prio.h> 

PRInt32 PR_RecvFrom(
   PRFileDesc *fd,
   void *buf,
   PRInt32 amount,
   PRIntn flags,
   PRNetAddr *addr,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a socket.

buf

A pointer to a buffer to hold the data received.

amount

The size of buf (in bytes).

flags

This obsolete parameter must always be zero.

addr

A pointer to the PRNetAddr object that will be filled in with the address of the sending peer on return.

timeout

A value of type PRIntervalTime specifying the time limit for completion of the receive operation


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes actually received.

  • The value 0 means the network connection is closed.

  • The value -1 indicates a failure. The reason for the failure can be obtained by calling PR_GetError.


Description
PR_RecvFrom receives up to a specified number of bytes from socket, which may or may not be connected. The operation blocks until one or more bytes are transferred, a timeout has occurred, or there is an error. No more than amount bytes will be transferred. PR_RecvFrom is usually used with a UDP socket.

PR_SendTo

Sends bytes a socket to a specified destination.


Syntax
#include <prio.h> 

PRInt32 PR_SendTo(
   PRFileDesc *fd,
   const void *buf,
   PRInt32 amount,
   PRIntn flags,
   PRNetAddr *addr,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a socket.

buf

A pointer to a buffer containing the data to be sent.

amount

The size of buf (in bytes).

flags

This obsolete parameter must always be zero.

addr

A pointer to the address of the destination.

timeout

A value of type PRIntervalTime specifying a time limit for completion of the send operation.


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes successfully sent.

  • The value -1 indicates a failure. The reason for the failure can be obtained by calling PR_GetError.


Description
PR_SendTo sends a specified number of bytes from a socket to the specified destination address. The calling thread blocks until all bytes are sent, a timeout has occurred, or there is an error.

PR_TransmitFile

Sends a complete file across a connected socket.


Syntax
#include <prio.h> 

PRInt32 PR_TransmitFile(
   PRFileDesc *networkSocket,
   PRFileDesc *sourceFile,
   const void *headers,
   PRInt32 hlen,
   PRTransmitFileFlags flags,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

networkSocket

A pointer to a PRFileDesc object representing the connected socket to send data over.

sourceFile

A pointer to a PRFileDesc object representing the file to send.

headers

A pointer to the buffer holding the headers to be sent before sending data.

hlen

Length of the headers buffer in bytes.

flags

One of the following flags:

  • PR_TRANSMITFILE_KEEP_OPEN indicates that the socket will be kept open after the data is sent.

  • PR_TRANSMITFILE_CLOSE_SOCKET indicates that the connection should be closed immediately after successful transfer of the file.

timeout

Time limit for completion of the transmit operation.


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes successfully written, including both the headers and the file.

  • The value -1 indicates a failure. If an error occurs while sending the file, the PR_TRANSMITFILE_CLOSE_SOCKET flag is ignored. The reason for the failure can be obtained by calling PR_GetError.


Description
The PR_TransmitFile function sends a complete file (sourceFile) across a connected socket (networkSocket). If headers is non-NULL, PR_TransmitFile sends the headers across the socket before sending the file.

The enumeration PRTransmitFileFlags, used in the flags parameter, is defined as follows:

typedef enum PRTransmitFileFlags {
   PR_TRANSMITFILE_KEEP_OPEN = 0,
   PR_TRANSMITFILE_CLOSE_SOCKET = 1
} PRTransmitFileFlags;

PR_AcceptRead

Accepts a new connection and receives a block of data.


Syntax
#include <prio.h> 

PRInt32 PR_AcceptRead(
   PRFileDesc *listenSock,
   PRFileDesc **acceptedSock,
   PRNetAddr **peerAddr,
   void *buf,
   PRInt32 amount,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

listenSock

A pointer to a PRFileDesc object representing a socket descriptor that has been called with the PR_Listen function, also known as the rendezvous socket.

acceptedSock

A pointer to a pointer to a PRFileDesc object. On return, *acceptedSock points to the PRFileDesc object for the newly connected socket. This parameter is valid only if the function return does not indicate failure.

peerAddr

A pointer a pointer to a PRNetAddr object. On return, peerAddr points to the address of the remote socket. The PRNetAddr object that peerAddr points to will be in the buffer pointed to by buf. This parameter is valid only if the function return does not indicate failure.

buf

A pointer to a buffer to hold data sent by the peer and the peer's address. This buffer must be large enough to receive amount bytes of data and two PRNetAddr structures (thus allowing the runtime to align the addresses as needed).

amount

The number of bytes of data to receive. Does not include the size of the PRNetAddr structures. If 0, no data will be read from the peer.

timeout

The timeout interval only applies to the read portion of the operation. PR_AcceptRead blocks indefinitely until the connection is accepted; the read will time out after the timeout interval elapses.


Returns
The function returns one of the following values:

  • A positive number indicates the number of bytes read from the peer.

  • The value -1 indicates a failure. The reason for the failure can be obtained by calling PR_GetError.


Description
PR_AcceptRead accepts a new connection and retrieves the newly created socket's descriptor and the connecting peer's address. Also, as its name suggests, PR_AcceptRead receives the first block of data sent by the peer.

PR_GetSockName

Gets network address for a specified socket.


Syntax
#include <prio.h> 

PRStatus PR_GetSockName(
   PRFileDesc *fd,
   PRNetAddr *addr);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing the socket.

addr

On return, the address of the socket.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be obtained by calling PR_GetError.

PR_GetPeerName

Gets the network address of the connected peer.


Syntax
#include <prio.h> 

PRStatus PR_GetPeerName(
   PRFileDesc *fd,
   PRNetAddr *addr);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing a socket.

addr

On return, the address of the peer connected to the socket.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be obtained by calling PR_GetError.

PR_GetSocketOption

Retrieves the socket options set for a specified socket.


Syntax
#include <prio.h> 

PRStatus PR_GetSocketOption(
   PRFileDesc *fd,
   PRSocketOptionData *data);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing the socket whose options are to be retrieved.

data

A pointer to a structure of type PRSocketOptionData. On input, the option field of this structure must be set to indicate which socket option to retrieve for the socket represented by the fd parameter. On output, this structure contains the requested socket option data.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be obtained by calling PR_GetError.

PR_SetSocketOption

Sets the socket options for a specified socket.


Syntax
#include <prio.h> 

PRStatus PR_SetSocketOption(
   PRFileDesc *fd,
   PRSocketOptionData *data);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing the socket whose options are to be set.

data

A pointer to a structure of type PRSocketOptionData specifying the options to set.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be obtained by calling PR_GetError.


Description
On input, the caller must set both the option and value fields of the PRSocketOptionData object pointed to by the data parameter.

Converting Between Host and Network Addresses

PR_ntohs
PR_ntohl
PR_htons
PR_htonl
PR_FamilyInet

PR_ntohs

Performs 16-bit conversion from network byte order to host byte order.


Syntax
#include <prnetdb.h> 

PRUint16 PR_ntohs(PRUint16 conversion);


Parameter
The function has the following parameter:

conversion

The 16-bit unsigned integer, in network byte order, to be converted.


Returns
The value of the conversion parameter in host byte order.

PR_ntohl

Performs 32-bit conversion from network byte order to host byte order.


Syntax
#include <prnetdb.h> 

PRUint32 PR_ntohl(PRUint32 conversion);


Parameter
The function has the following parameter:

conversion

The 32-bit unsigned integer, in network byte order, to be converted.


Returns
The value of the conversion parameter in host byte order.

PR_htons

Performs 16 bit conversion from host byte order to network byte order.


Syntax
#include <prnetdb.h> 

PRUint16 PR_htons(PRUint16 conversion);


Parameter
The function has the following parameter:

conversion

The 16-bit unsigned integer, in host byte order, to be converted.


Returns
The value of the conversion parameter in network byte order.

PR_htonl

Performs 32-bit conversion from host byte order to network byte order.


Syntax
#include <prnetdb.h> 

PRUint32 PR_htonl(PRUint32 conversion);


Parameter
The function has the following parameter:

conversion

The 32-bit unsigned integer, in host byte order, to be converted.


Returns
The value of the conversion parameter in network byte order.

PR_FamilyInet

Gets the value of the address family for Internet Protocol.


Syntax
#include <prnetdb.h> 

PRUint16 PR_FamilyInet(void);


Returns
The value of the address family for Internet Protocol. This is usually PR_AF_INET, but can also be PR_AF_INET6 if IPv6 is enabled. The returned value can be assigned to the inet.family field of a PRNetAddr object.

Memory-Mapped I/O Functions

The memory-mapped I/O functions allow sections of a file to be mapped to memory regions, allowing read-write accesses to the file to be accomplished by normal memory accesses.

Memory-mapped I/O functions are currently implemented for Unix, Linux, Mac OS X, and Win32 only.

PR_CreateFileMap

Creates a file mapping object.


Syntax
#include <prio.h> 

PRFileMap* PR_CreateFileMap(
   PRFileDesc *fd,
   PRInt64 size,
   PRFileMapProtect prot);


Parameters
The function has the following parameters:

fd

A pointer to a PRFileDesc object representing the file that is to be mapped to memory.

size

Size of the file specified by fd.

prot

Protection option for read and write accesses of a file mapping. This parameter consists of one of the following options:

  • PR_PROT_READONLY. Read-only access.

  • PR_PROT_READWRITE. Readable, and write is shared.

  • PR_PROT_WRITECOPY. Readable, and write is private (copy-on-write).


Returns
The function returns one of the following values:

  • If successful, a file mapping of type PRFileMap.

  • If unsuccessful, NULL.


Description
The PRFileMapProtect enumeration used in the prot parameter is defined as follows:

typedef enum PRFileMapProtect {
   PR_PROT_READONLY,
   PR_PROT_READWRITE,
   PR_PROT_WRITECOPY
} PRFileMapProtect;

PR_CreateFileMap only prepares for the mapping a file to memory. The returned file-mapping object must be passed to PR_MemMap to actually map a section of the file to memory.

The file-mapping object should be closed with a PR_CloseFileMap call when it is no longer needed.

PR_MemMap

Maps a section of a file to memory.


Syntax
#include <prio.h> 

void* PR_MemMap(
   PRFileMap *fmap,
   PRInt64 offset,
   PRUint32 len);


Parameters
The function has the following parameters:

fmap

A pointer to the file-mapping object representing the file to be memory-mapped.

offset

The starting offset of the section of file to be mapped. The offset must be aligned to whole pages.

len

Length of the section of the file to be mapped. The length must be a multiple of whole pages.


Returns
The starting address of the memory region to which the section of file is mapped.


Description
PR_MemMap maps a section of the file represented by the file mapping fmap to memory. The section of the file starts at offset and has the length len.

When the file-mapping memory region is no longer needed, it should be unmapped with a call to PR_MemUnmap.

PR_MemUnmap

Unmap a memory region that is backed by a memory-mapped file.


Syntax
#include <prio.h> 

PRStatus PR_MemUnmap(
   void *addr,
   PRUint32 len);


Parameters
The function has the following parameters:

addr

The starting address of the memory region to be unmapped.

len

The length, in bytes, of the memory region.


Returns
The function returns one of the following values:

  • If the memory region is successfully unmapped, PR_SUCCESS.

  • If the memory region is not successfully unmapped, PR_FAILURE. The error code can be retrieved via PR_GetError.


Description
PR_MemUnmap removes the file mapping for the memory region (addr, addr + len). The parameter addr is the return value of an earlier call to PR_MemMap.

PR_CloseFileMap

Closes a file mapping.


Syntax
#include <prio.h> 

PRStatus PR_CloseFileMap(PRFileMap *fmap);


Parameter
The function has the following parameter:

fmap

The file mapping to be closed.


Returns
The function returns one of the following values:

  • If the file mapping is successfully closed, PR_SUCCESS.

  • If the file mapping is not successfully closed, PR_FAILURE. The error code can be retrieved via PR_GetError.


Description
When a file mapping created with a call to PR_CreateFileMap is no longer needed, it should be closed with a call to PR_CloseFileMap.

Anonymous Pipe Function

PR_CreatePipe

Creates an anonymous pipe and retrieves file descriptors for the read and write ends of the pipe.


Syntax
#include <prio.h> 

PRStatus PR_CreatePipe(
   PRFileDesc **readPipe,
   PRFileDesc **writePipe);


Parameters
The function has the following parameters:

readPipe

A pointer to a PRFileDesc pointer. On return, this parameter contains the file descriptor for the read end of the pipe.

writePipe

A pointer to a PRFileDesc pointer. On return, this parameter contains the file descriptor for the write end of the pipe.


Returns
The function returns one of these values:

  • If the pipe is successfully created, PR_SUCCESS.

  • If the pipe is not successfully created, PR_FAILURE. The error code can be retrieved via PR_GetError.


Description
PR_CreatePipe creates an anonymous pipe. Data written into the write end of the pipe can be read from the read end of the pipe. Pipes are useful for interprocess communication between a parent and a child process. When the pipe is no longer needed, both ends should be closed with calls to PR_Close.

PR_CreatePipe is currently implemented on Unix, Linux, Mac OS X, and Win32 only.

Polling Functions

This section describes two of the most important polling functions provided by NSPR:

PR_Poll
PR_GetConnectStatus

PR_Poll

Detects when I/O is ready for a set of socket file descriptors.


Syntax
#include <prio.h> 

PRInt32 PR_Poll(
   PRPollDesc *pds,
   PRIntn npds,
   PRIntervalTime timeout);


Parameters
The function has the following parameters:

pds

A pointer to an array of PRPollDesc structures.

npds

The number of elements in the pds array. If this parameter is zero, PR_Poll is equivalent to PR_Sleep with a timeout.

timeout

Amount of time the call will block waiting for I/O to become ready. If this time expires without any I/O becoming ready, PR_Poll returns zero.


Returns
The function returns one of the following values:

  • If successful, the function returns a positive number indicating the number of PRPollDesc structures in pds that have events.

  • The value 0 indicates the function timed out.

  • The value -1 indicates the function failed. The reason for the failure can be obtained by calling PR_GetError.


Description
This function returns as soon as I/O is ready on one or more of the underlying socket objects. A count of the number of ready descriptors is returned unless a timeout occurs, in which case zero is returned.

The in_flags field of the PRPollDesc data structure should be set to the I/O events (readable, writable, exception, or some combination) that the caller is interested in. On successful return, the out_flags field of the PRPollDesc data structure is set to indicate what kind of I/O is ready on the respective descriptor. PR_Poll uses the out_flags fields as scratch variables during the call. If PR_Poll returns 0 or -1, the out_flags fields do not contain meaningful values and must not be used.

The PRPollDesc structure is defined as follows:

struct PRPollDesc {
   PRFileDesc* fd;
   PRInt16 in_flags;
   PRInt16 out_flags;
};

typedef struct PRPollDesc PRPollDesc;

The structure has the following fields:

fd

A pointer to a PRFileDesc object representing a socket or a pollable event. This field can be set to NULL to indicate to PR_Poll that this PRFileDesc object should be ignored.
On Unix, the fd field can be set to a pointer to any PRFileDesc object, including one representing a file or a pipe. Cross-platform applications should only set the fd field to a pointer to a PRFileDesc object representing a socket or a pollable event because on Windows the select function can only be used with sockets.

in_flags

A bitwise OR of the following bit flags:

  • PR_POLL_READ: fd is readable.

  • PR_POLL_WRITE: fd is writable.

  • PR_POLL_EXCEPT: fd has an exception condition.

out_flags

A bitwise OR of the following bit flags:

  • PR_POLL_READ

  • PR_POLL_WRITE

  • PR_POLL_EXCEPT

  • PR_POLL_ERR: fd has an error.

  • PR_POLL_NVAL: fd is bad.

Note that the PR_POLL_ERR and PR_POLL_NVAL flags are used only in out_flags. The PR_POLL_ERR and PR_POLL_NVAL events are always reported by PR_Poll.

PR_GetConnectStatus

Get the completion status of a nonblocking connection.


Syntax
PRStatus PR_GetConnectStatus(const PRPollDesc *pd);


Parameter
This function has the following parameter:

pd

A pointer to a PRPollDesc satructure whose fd field is the socket and whose in_flags field must contain PR_POLL_WRITE and PR_POLL_EXCEPT.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be retrieved via PR_GetError.

If PR_GetError returns PR_IN_PROGRESS_ERROR, the nonblocking connection is still in progress and has not completed yet.Other errors indicate that the connection has failed.


Description
After PR_Connect on a nonblocking socket fails with PR_IN_PROGRESS_ERROR, you may wait for the connection to complete by calling PR_Poll on the socket with the in_flags PR_POLL_WRITE | PR_POLL_EXCEPT. When PR_Poll returns, call PR_GetConnectStatus on the socket to determine whether the nonblocking connect has succeeded or failed.

Pollable Events

A pollable event is a special kind of file descriptor. The only I/O operation you can perform on a pollable event is to poll it with the PR_POLL_READ flag. You cannot read from or write to a pollable event.

The purpose of a pollable event is to combine event waiting with I/O waiting in a single PR_Poll call. Pollable events are implemented using a pipe or a pair of TCP sockets connected via the loopback address, therefore setting and/or waiting for pollable events are expensive operating system calls. Do not use pollable events for general thread synchronization; use condition variables instead.

A pollable event has two states: set and unset. Events are not queued, so there is no notion of an event count. A pollable event is either set or unset.

A new pollable event is created by calling PR_NewPollableEvent.

PR_WaitForPollableEvent blocks the calling thread until the pollable event is set, and then atomically unsetting the event before returning.

Call PR_SetPollableEvent to set the pollable event.

Call PR_DestroyPollableEvent (not PR_Close) to close and release resources of the pollable event.

One can call PR_Poll with the PR_POLL_READ flag on a pollable event. Whe the pollable event is set, PR_Poll returns the the PR_POLL_READ flag set in the out_flags.

PR_NewPollableEvent

Create a pollable event file descriptor.


Syntax
NSPR_API(PRFileDesc *) PR_NewPollableEvent( void);


Parameter
None.


Returns
Pointer to PRFileDesc or NULL, on error.

PR_DestroyPollableEvent

Close the file descriptor associated with a pollable event and release related resources.


Syntax
NSPR_API(PRStatus) PR_DestroyPollableEvent(PRFileDesc *event);


Parameter

event

Pointer to a PRFileDesc structure previously created via a call to PR_NewPollableEvent.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be retrieved via PR_GetError.

PR_SetPollableEvent

Set a pollable event


Syntax
NSPR_API(PRStatus) PR_SetPollableEvent( PRFileDesc *event);


Parameter

event

Pointer to a PRFileDesc structure previously created via a call to PR_NewPollableEvent.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be retrieved via PR_GetError.

PR_WaitForPollableEvent


Syntax
NSPR_API(PRStatus) PR_WaitForPollableEvent( PRFileDesc *event );


Parameter

event

Pointer to a PRFileDesc structure previously created via a call to PR_NewPollableEvent.


Returns
The function returns one of the following values:

  • If successful, PR_SUCCESS.

  • If unsuccessful, PR_FAILURE. The reason for the failure can be retrieved via PR_GetError.

Manipulating Layers

File descriptors may be layered. For example, SSL is a layer on top of a reliable bytestream layer such as TCP.

Each type of layer has a unique identity, which is allocated by the runtime. The layer implementor should associate the identity with all layers of that type. It is then possible to scan the chain of layers and find a layer that one recognizes and therefore predict that it will implement a desired protocol.

A layer can be pushed onto or popped from an existing stack of layers. The file descriptor of the top layer can be passed to NSPR I/O functions, which invoke the appropriate version of the I/O methods polymorphically.

NSPR defines three identities:

#define PR_INVALID_IO_LAYER (PRDescIdentity)-1
#define PR_TOP_IO_LAYER (PRDescIdentity)-2
#define PR_NSPR_IO_LAYER (PRDescIdentity)0

  • PR_INVALID_IO_LAYER: An invalid layer identify (for error return).

  • PR_TOP_IO_LAYER: The identity of the top of the stack.

  • PR_NSPR_IO_LAYER: The identity for the layer implemented by NSPR.

PR_TOP_IO_LAYER may be used as a shorthand for identifying the topmost layer of an existing stack. For example, the following lines of code are equivalent:

rv = PR_PushIOLayer(stack, PR_TOP_IO_LAYER, my_layer);
rv = PR_PushIOLayer(stack, PR_GetLayersIdentity(stack), my_layer);

PR_GetUniqueIdentity
PR_GetNameForIdentity
PR_GetLayersIdentity
PR_GetIdentitiesLayer
PR_GetDefaultIOMethods
PR_CreateIOLayerStub
PR_PushIOLayer
PR_PopIOLayer

PR_GetUniqueIdentity

Asks the runtime to allocate a unique identity for a layer identified by the layer's name.


Syntax
#include <prio.h> 

PRDescIdentity PR_GetUniqueIdentity(const char *layer_name);


Parameter
The function has the following parameter:

layer_name

The string associated with the creation of a layer's identity.


Returns
The function returns one of the following values:

  • If successful, the PRDescIdentity for the layer associated with the string specified in the layer named layer_name.

  • If the function cannot allocate enough dynamic memory, it fails and returns the value PR_INVALID_IO_LAYER with the error code PR_OUT_OF_MEMORY_ERROR.


Description
A string may be associated with a layer when the layer is created. PR_GetUniqueIdentity allocates a unique layer identity and associates it with the string. The string can be subsequently passed to PR_CreateIOLayerStub to create a new file descriptor of that layer.


For any particular layer name, PR_GetUniqueIdentity can be only called once. Only one identity is allocated for each name.

PR_GetNameForIdentity

Gets the string associated with a layer's unique identity.


Syntax
#include <prio.h> 

const char* PR_GetNameForIdentity(PRDescIdentity ident);


Parameter
The function has the following parameter:

ident

A layer's identity.


Returns
The function returns one of the following values:

  • If successful, the function returns a pointer to the string associated with the specified layer.

  • If unsuccessful, the function returns NULL.


Description
A string may be associated with a layer when the layer is created. The string is copied by the runtime, and PR_GetNameForIdentity returns a pointer to that copy.

PR_GetLayersIdentity

Gets the unique identity for the layer of the specified file descriptor


Syntax
#include <prio.h> 

PRDescIdentity PR_GetLayersIdentity(PRFileDesc* fd);


Parameter
The function has the following parameter:

fd

A pointer to a file descriptor.


Returns
If successful, the function returns the PRDescIdentity for the layer of the specified file descriptor.

PR_GetIdentitiesLayer

Finds the layer with the specified identity in the specified stack of layers.


Syntax
#include <prio.h> 

PRFileDesc* PR_GetIdentitiesLayer(
   PRFileDesc* stack,
   PRDescIdentity id);


Parameters
The function has the following parameters:

stack

A pointer to a PRFileDesc object that is a layer in a stack of layers.

id

The identity of the specified layer.


Returns
The function returns one of the following values:

  • If successful, a pointer to a file descriptor of the layer with the specified identity in the given stack of layers.

  • If not successful, NULL.


Description
The stack of layers to be searched is specified by the fd parameter, which is a layer in the stack. Both the layers underneath fd and the layers above fd are searched to find the layer with the specified identity.

PR_GetDefaultIOMethods

Gets the default I/O methods table.


Syntax
#include <prio.h> 

const PRIOMethods* PR_GetDefaultIOMethods(void);


Returns
If successful, the function returns a pointer to a PRIOMethods structure.


Description
After using PR_GetDefaultIOMethods to identify the default I/O methods table, you can select elements from that table with which to build your own layer's methods table. You may not modify the default I/O methods table directly. You can pass your own layer's methods table to PR_CreateIOLayerStub to create your new layer.

PR_CreateIOLayerStub

Creates a new layer.


Syntax
#include <prio.h> 

PRFileDesc* PR_CreateIOLayerStub(
   PRDescIdentity ident
   PRIOMethods const *methods);


Parameters
The function has the following parameters:

ident

The identity to be associated with the new layer.

methods

A pointer to the PRIOMethods structure specifying the functions for the new layer.


Returns
A new file descriptor for the specified layer.


Description
A new layer may be allocated by calling PR_CreateIOLayerStub. The file descriptor returned contains the pointer to the I/O methods table provided. The runtime neither modifies the table nor tests its correctness.

The caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack.

PR_PushIOLayer

Adds a layer onto the stack.


Syntax
#include <prio.h> 

PRStatus PR_PushIOLayer(
   PRFileDesc *stack,
   PRDescIdentity id,
   PRFileDesc *layer);


Parameters
The function has the following parameters:

stack

A pointer to a PRFileDesc object representing the stack.

id

A PRDescIdentity object for the layer on the stack above which the new layer is to be added.

layer

A pointer to a PRFileDesc object representing the new layer to be added to the stack.


Returns
The function returns one of the following values:

  • If the layer is successfully pushed onto the stack, PR_SUCCESS.

  • If the layer is not successfully pushed onto the stack, PR_FAILURE. Use PR_GetError to get additional information regarding the reason for the failure.


Description
A file descriptor for a layer (possibly allocated using PR_CreateIOLayerStub) may be pushed onto an existing stack of file descriptors at any time. The new layer is inserted into the stack just above the layer with the identity specified by id.

Even if the id parameter indicates the topmost layer of the stack, the value of the file descriptor describing the original stack will not change. In other words, stack continues to point to the top of the stack after the function returns.


Caution
Keeping the pointer to the stack even as layers are pushed onto the top of the stack is accomplished by swapping the contents of the file descriptor being pushed and the stack's current top layer file descriptor.

The intent is that the pointer to the stack remain the stack's identity even if someone (perhaps covertly) has pushed other layers. Some subtle ramifications:

  • The ownership of the storage pointed to by the caller's layer argument is relinquished to the runtime. Accessing the object via the pointer is not permitted while the runtime has ownership. The correct mechanism to access the object is to get a pointer to it by calling PR_GetIdentitiesLayer.

  • The contents of the caller's object are swapped into another container, including the reference to the object's destructor. If the original container was allocated using a different mechanism than used by the runtime, the default calling of the layer's destructor by the runtime will fail PR_CreateIOLayerStub is provided to allocate layer objects and template implementations). The destructor will be called on all layers when the stack is closed (see PR_Close). If the containers are allocated by some method other than PR_CreateIOLayerStub, it may be required that the stack have the layers popped off (in reverse order that they were pushed) before calling PR_Close.

PR_PopIOLayer

Removes a layer from the stack.


Syntax
#include <prio.h> 

PRFileDesc *PR_PopIOLayer(
   PRFileDesc *stack,
   PRDescIdentity id);


Parameters
The function has the following parameters:

stack 

A pointer to a PRFileDesc object representing the stack from which the specified layer is to be removed.

id

Identity of the layer to be removed from the stack.


Returns
The function returns one of the following values:

  • If the layer is successfully removed from the stack, a pointer to the removed layer.

  • If the layer is not found in the stack or cannot be popped (for example, the bottommost layer), the function returns NULL with the error code PR_INVALID_ARGUMENT_ERROR.


Description
PR_PopIOLayer pops the specified layer from the stack. If the object to be removed is found, PR_PopIOLayer returns a pointer to the removed object The object then becomes the responsibility of the caller.

Even if the identity indicates the top layer of the stack, the reference returned is not the file descriptor for the stack and that file descriptor remains valid. In other words, stack continues to point to the top of the stack after the function returns.


Previous     Contents     Next     

Last Updated May 18, 2001