Types
The State Thread library defines the following types in the st.h
header file:
st_thread_t
Thread type.
#include <st.h> typedef void * st_thread_t;
The thread identifier remains valid until the thread returns from its root function and, if the thread was created joinable, is joined.
st_cond_t
Condition variable type.
#include <st.h> typedef void * st_cond_t;
In the State Threads library there is no need to lock a mutex before waiting on a condition variable.
st_mutex_t
Mutex type.
#include <st.h> typedef void * st_mutex_t;
If application using the State Threads library is written with no I/O or control yielding in critical sections (that is no blocking functions in critical sections), then there is no need for mutexes.
These mutexes can only be used for intra-process thread synchronization. They cannot be used for inter-process synchronization.
st_utime_t
High resolution time type ("u" stands for "micro").
#include <st.h> typedef unsigned long long st_utime_t;
st_netfd_t
File descriptor type.
#include <st.h> typedef void * st_netfd_t;
st_switch_cb_t
Context switch callback function type.
#include <st.h> typedef void (*st_switch_cb_t)(void);
Error Handling
All State Threads library non-void functions return on success either a
non-negative integer or a pointer to a newly created object (constructor-type
functions). On failure they return either -1 or a NULL
pointer respectively and set global errno to indicate the error.
It is safe to use errno because it is set right before the function
return and only one thread at a time can modify its value.
The perror(3) function can be used to produce an error message on the standard error output.
These functions operate on a callback function of type st_switch_cb_t:
st_init()
Initializes the runtime.
#include <st.h> int st_init(void);
Among other things, this function limits the number of open file descriptors to the OS imposed per-process maximum number or, if select(2) is used, to FD_SETSIZE, whichever is less (getrlimit(2)). This limit can be retrieved by st_getfdlimit(). It also sets the disposition of the SIGPIPE signal to SIG_IGN (to be ignored) (signal(5)).
Unlike POSIX threads, a new process created by the fork(2) system call is an exact copy of the calling process and all state threads which are running in the parent do exist in the child. That means that st_init() may be called either before or after multiple processes are created by fork(2).
If the library runtime is not properly initialized (e.g., st_init() is accidentally omitted), then the process will receive either an arithmetic exception (SIGFPE or SIGTRAP) or segmentation fault (SIGSEGV) signal upon new thread creation or the first context switch, respectively.
st_getfdlimit()
Returns the maximum number of file descriptors that the calling process
can open.
#include <st.h> int st_getfdlimit(void);
st_set_eventsys()
Sets event notification mechanism.
#include <st.h> int st_set_eventsys(int eventsys);
eventsys
An integer value identifying selected event notification mechanism. The following values are defined in the st.h header file:
ST_EVENTSYS_DEFAULT | Use default event notification mechanism. Usually it's select(2) but if the library was compiled with the USE_POLL macro defined then the default is poll(2). |
ST_EVENTSYS_SELECT | Use select(2) as an event notification mechanism. | ST_EVENTSYS_POLL | Use poll(2) as an event notification mechanism. | ST_EVENTSYS_ALT | Use an alternative event notification mechanism. The actual mechanism selected depends on OS support. For example, epoll(4) will be used on Linux if supported and kqueue(2) will be used on FreeBSD/OpenBSD. If the OS supports no alternative event notification mechanism, setting ST_EVENTSYS_ALT has no effect and the ST_EVENTSYS_DEFAULT mechanism will be used. |
EINVAL | The supplied eventsys parameter has an invalid value. |
EBUSY | The event notification mechanism has already been set. |
There are no strict rules for selecting an event notification mechanism. The "best" one depends on how your application behaves. Try a few to see which one works best for you. As a rule of thumb, you should use the ST_EVENTSYS_ALT mechanism if your application deals with a very large number of network connections of which only a few are active at once.
st_get_eventsys()
Returns the integer value identifying the event notification mechanism
being used by the State Threads library.
#include <st.h> int st_get_eventsys(void);
st_get_eventsys_name()
Returns the name of the event notification mechanism being used by the
State Threads library.
#include <st.h> const char *st_get_eventsys_name(void);
st_set_switch_in_cb()
st_set_switch_out_cb()
Set the optional callback function for thread switches.
#include <st.h> st_switch_cb_t st_set_switch_in_cb(st_switch_cb_t cb); st_switch_cb_t st_set_switch_out_cb(st_switch_cb_t cb);
cb
A function to be called when a thread is resumed and stopped respectively.
These functions can be called at any time.
This feature is available only when ST_SWITCH_CB is defined in <st.h>.
Thread Control and Identification
These functions operate on a thread object of type st_thread_t.
st_thread_create()
Creates a new thread.
#include <st.h> st_thread_t st_thread_create(void *(*start)(void *arg), void *arg, int joinable, int stack_size);
start
A pointer to the thread's start function, which is called as the root of the new thread. Return from this function terminates a thread.
arg
A pointer to the root function's only parameter.
joinable
Specifies whether the thread is joinable or unjoinable. If this parameter is zero, the thread is unjoinable. Otherwise, it is joinable. See also st_thread_join().
stack_size
Specifies your preference for the size of the stack, in bytes, associated with the newly created thread. If you pass zero in this parameter, the default stack size will be used. The default stack size is 128 KB on IA-64 and 64 KB on all other platforms. On IA-64 only a half of stack_size bytes is used for the memory stack. The other half is used for the register stack backing store.
st_thread_exit()
Terminates the calling thread.
#include <st.h> void st_thread_exit(void *retval);
retval
If the thread is joinable, then the value retval may be retrieved by st_thread_join(). If a thread returns from its start function, it acts as if it had called st_thread_exit() with retval as the value returned.
When the last thread terminates the process exits with a zero status value.
st_thread_join()
Blocks the calling thread until a specified thread terminates.
#include <st.h> int st_thread_join(st_thread_t thread, void **retvalp);
thread
A valid identifier for the thread that is to be joined.
retvalp
If this parameter is not NULL, then the exit value of the thread will be placed in the location referenced by this parameter (see st_thread_exit()).
EINVAL | Target thread is unjoinable. |
EINVAL | Other thread already waits on the same joinable thread. |
EDEADLK | Target thread is the same as the calling thread. |
EINTR | Current thread was interrupted by st_thread_interrupt(). |
st_thread_self()
Identifies the calling thread.
#include <st.h> st_thread_t st_thread_self(void);
st_thread_interrupt()
Interrupts a target thread.
#include <st.h> void st_thread_interrupt(st_thread_t thread);
thread
A valid identifier for the thread being interrupted.
Note: State Threads library functions are never interrupted by a caught signal. A blocking library function returns an error and sets errno to EINTR only if the current thread was interrupted via st_thread_interrupt().
If a target thread is already runnable or running (e.g., it is a newly created thread or calling thread itself), this function will prevent it from subsequent blocking. In other words, the interrupt will be "delivered" only when a target thread is about to block.
st_sleep(), st_usleep()
Suspends current thread for a specified amount of time.
#include <st.h> int st_sleep(int secs); int st_usleep(st_utime_t usecs);
secs
The number of seconds you want the thread to sleep for.
st_usleep() has the following parameters:
usecs
The number of microseconds you want the thread to sleep for. This parameter is a variable of type st_utime_t.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
If zero is passed as a parameter to st_sleep(), or ST_UTIME_NO_WAIT (0) is passed to st_usleep(), the calling thread yields, thus potentially allowing another thread to run.
If -1 is passed as a parameter to st_sleep(), or ST_UTIME_NO_TIMEOUT (-1) is passed to st_usleep(), the calling thread will be suspended permanently. It can be resumed again by interrupting it via st_thread_interrupt().
st_randomize_stacks()
Turns stack base address randomization on or off.
#include <st.h> int st_randomize_stacks(int on);
on
If this parameter has a non-zero value, the State Threads library randomizes the base addresses of stacks allocated for threads created after this call. Otherwise new threads' stacks are typically page aligned.
When randomization is enabled, new stacks are allocated one page larger to accomodate the randomization.
This call affects only threads created afterward. It has no effect on existing threads.
Per-Thread Private Data
These functions allow to associate private data with each of the threads in
a process.
st_key_create()
Creates a key (non-negative integer) that can be used by all
threads in the process to get and set thread-specific data.
#include <st.h> int st_key_create(int *keyp, void (*destructor)(void *));
keyp
The newly created key is returned in the memory pointed to by this parameter. The new key can be used with st_thread_setspecific() and st_thread_getspecific().
destructor
Specifies an optional destructor function for the private data associated with the key. This function can be specified as NULL. Upon thread exit (see st_thread_exit()), if a key has a non-NULL destructor and has a non-NULL value associated with that key, then the destructor function will be called with the associated value.
EAGAIN | The limit on the total number of keys per process has been exceeded (see st_key_getlimit()). |
The key maintains independent data values for each binding thread. A thread can get access only to its own thread-specific data. There is no way to deallocate a private data key once it is allocated.
st_key_getlimit()
Returns the key limit.
#include <st.h> int st_key_getlimit(void);
st_thread_setspecific()
Sets per-thread private data.
#include <st.h> int st_thread_setspecific(int key, void *value);
key
This parameter represents a key with which thread-specific data is associated.
value
The per-thread private data, or more likely, a pointer to the data which is associated with key.
EINVAL | The specified key is invalid. |
If the thread already has non-NULL private data associated with key, and if the destructor function for that key is not NULL, this destructor function will be called before setting the new data value.
st_thread_getspecific()
Retrieves the per-thread private data for the current thread.
#include <st.h> void *st_thread_getspecific(int key);
key
This parameter represents a key with which thread-specific data is associated.
These functions operate on condition variables and mutual exclusion locks (mutexes).
Functions are provided to wait on a condition variable and to wake up (signal) threads that are waiting on the condition variable.
st_cond_new()
Creates a new condition variable.
#include <st.h> st_cond_t st_cond_new(void);
st_cond_destroy()
Destroys a condition variable.
#include <st.h> int st_cond_destroy(st_cond_t cvar);
cvar
An identifier of the condition variable object to be destroyed.
EBUSY | The condition variable is currently being used by one or more threads. |
st_cond_wait()
Waits on a condition.
#include <st.h> int st_cond_wait(st_cond_t cvar);
cvar
The condition variable on which to wait.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
Note: The State Threads library scheduling guarantees that the condition cannot change between the checking and blocking, therefore there is no need for mutex protection. You must not call any blocking functions between the condition checking and the st_cond_wait() call.
st_cond_timedwait()
Waits on a condition.
#include <st.h> int st_cond_timedwait(st_cond_t cvar, st_utime_t timeout);
cvar
The condition variable on which to wait.
timeout
If the number of microseconds specified by this parameter passes before the waiting thread is signalled, an error is returned. This parameter is a variable of type st_utime_t. Note that this time value is a time delta; it is not an absolute time. Also note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred before the thread was awakened by st_cond_signal() or st_cond_broadcast(). |
st_cond_signal()
Unblocks a thread waiting on a condition variable.
#include <st.h> int st_cond_signal(st_cond_t cvar);
cvar
The condition variable to signal.
st_cond_broadcast()
Unblocks all threads waiting on a condition variable.
#include <st.h> int st_cond_broadcast(st_cond_t cvar);
cvar
The condition variable to broadcast.
st_mutex_new()
Creates a new mutual exclusion lock (mutex).
#include <st.h> st_mutex_t st_mutex_new(void);
st_mutex_destroy()
Destroys a specified mutex object.
#include <st.h> int st_mutex_destroy(st_mutex_t lock);
lock
An identifier of the mutex object to be destroyed.
EBUSY | The mutex is currently being used by other threads. |
st_mutex_lock()
Locks a specified mutex object.
#include <st.h> int st_mutex_lock(st_mutex_t lock);
lock
An identifier of the mutex object to be locked.
EDEADLK | The current thread already owns the mutex. |
EINTR | The current thread was interrupted by st_thread_interrupt(). |
st_mutex_trylock()
Attempts to acquire a mutex.
#include <st.h> int st_mutex_trylock(st_mutex_t lock);
lock
An identifier of the mutex object to be locked.
EBUSY | The mutex is currently held by another thread. |
st_mutex_unlock()
Releases a specified mutex object.
#include <st.h> int st_mutex_unlock(st_mutex_t lock);
lock
An identifier of the mutex object to be unlocked.
EPERM | The current thread does not own the mutex. |
st_utime()
Returns current high-resolution time.
#include <st.h> st_utime_t st_utime(void);
st_set_utime_function()
Set high-resolution time function.
#include <st.h> int st_set_utime_function(st_utime_t (*func)(void));
func
This function will be called to get high-resolution time instead of the default st_utime() function. It must return number of microseconds since some arbitrary time in the past.
st_timecache_set()
Turns the time caching on or off.
#include <st.h> int st_timecache_set(int on);
on
If this parameter has a non-zero value, the time caching is turned on (enabled). Otherwise, the time caching is turned off (disabled). By default time caching is disabled.
Note: There are some pathological cases (e.g., very heavy loads during application benchmarking) when a single thread runs for a long time without giving up control and the cached time value is not updated properly. If you always need "real-time" time values, don't enable the time caching.
st_time()
Returns the value of time in seconds since 00:00:00 UTC, January 1, 1970.
#include <st.h> time_t st_time(void);
Most State Threads library I/O functions look like corresponding C library functions with two exceptions:
st_netfd_open()
Creates a new file descriptor object.
#include <st.h> st_netfd_t st_netfd_open(int osfd);
osfd
Any open OS file descriptor; can be obtained from calls to functions including, but not restricted to, pipe(2), socket(3), socketpair(3), fcntl(2), dup(2), etc.
Note: Among other things, this function sets a non-blocking flag on the underlying OS file descriptor. You should not modify this flag directly. Also, once an st_netfd_t has been created with a given file descriptor, you should avoid passing that descriptor to normal I/O or stdio functions. Since the O_NONBLOCK flag is shared across dup(2), this applies to dup()'ed file descriptors as well - for instance, if you pass standard output or standard input to st_netfd_open(), then you should use st_write() instead of write or fprintf when writing to standard error as well - since all three descriptors could point to the same terminal. If necessary, you can still use write directly if you remember to check errno for EAGAIN, but fprintf and other stdio functions should be avoided completely because, at least on Linux, the stdio library cannot be made to work reliably with non-blocking files. (This only applies to file descriptors which are passed to st_netfd_open() or st_netfd_open_socket(), or which are related to such descriptors through dup(); other file descriptors are untouched by State Threads.)
st_netfd_open_socket()
Creates a new file descriptor object from a socket.
#include <st.h> st_netfd_t st_netfd_open_socket(int osfd);
osfd
An open OS file descriptor which is a socket initially obtained from a socket(3) or socketpair(3) call.
Unlike the st_netfd_open() function which may be used on OS file descriptors of any origin, st_netfd_open_socket() must be used only on sockets. It is slightly more efficient than st_netfd_open().
Note: Among other things, this function sets a non-blocking flag on the underlying OS socket. You should not modify this flag directly. See st_netfd_open().
st_netfd_free()
Frees a file descriptor object without closing the underlying OS file
descriptor.
#include <st.h> void st_netfd_free(st_netfd_t fd);
fd
A file descriptor object identifier (see st_netfd_t).
A thread should not free file descriptor objects that are in use by other threads because it may lead to unpredictable results (e.g., a freed file descriptor may be reused without other threads knowing that).
st_netfd_close()
Closes a file descriptor.
#include <st.h> int st_netfd_close(st_netfd_t fd);
fd
A file descriptor object identifier (see st_netfd_t).
A thread should not close file descriptor objects that are in use by other threads because it may lead to unpredictable results (e.g., a closed file descriptor may be reused without other threads knowing that).
st_netfd_fileno()
Returns an underlying OS file descriptor.
#include <st.h> int st_netfd_fileno(st_netfd_t fd);
fd
A file descriptor object identifier (see st_netfd_t).
st_netfd_setspecific()
Sets per-descriptor private data.
#include <st.h> void st_netfd_setspecific(st_netfd_t fd, void *value, void (*destructor)(void *));
fd
A valid file descriptor object identifier (see st_netfd_t).
value
The per-descriptor private data, or more likely, a pointer to the data which is being associated with the named file descriptor object.
destructor
Specifies an optional destructor function for the private data associated with fd. This function can be specified as NULL. If value is not NULL, then this destructor function will be called with value as an argument upon freeing the file descriptor object (see st_netfd_free() and st_netfd_close()).
st_netfd_getspecific()
Retrieves the per-descriptor private data.
#include <st.h> void *st_netfd_getspecific(st_netfd_t fd);
fd
A valid file descriptor object identifier (see st_netfd_t).
st_netfd_serialize_accept()
Serializes all subsequent accept(3) calls on a specified file
descriptor object.
#include <st.h> int st_netfd_serialize_accept(st_netfd_t fd);
fd
A file descriptor object identifier (see st_netfd_t) which has been successfully created from a valid listening socket by st_netfd_open() or st_netfd_open_socket().
st_netfd_serialize_accept() must be called before creating multiple server processes via fork(2). If the application does not create multiple processes to accept network connections on the same listening socket, there is no need to call this function.
Deciding whether or not to serialize accepts is tricky. On some platforms (IRIX, Linux) it's not needed at all and st_netfd_serialize_accept() is a no-op. On other platforms it depends on the version of the OS (Solaris 2.6 doesn't need it but earlier versions do). Serializing accepts does incur a slight performance penalty so you want to enable it only if necessary. Read your system's manual pages for accept(2) and select(2) to see if accept serialization is necessary on your system.
st_netfd_serialize_accept() allocates resources that are freed upon freeing of the specified file descriptor object (see st_netfd_free() and st_netfd_close()).
st_netfd_poll()
Waits for I/O on a single file descriptor object.
#include <st.h> int st_netfd_poll(st_netfd_t fd, int how, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
how
Specifies I/O events of interest. This parameter can be constructed by OR-ing any combination of the following event flags which are defined in the poll.h header file:
POLLIN | fd is readable. |
POLLOUT | fd is is writable. |
POLLPRI | fd has an exception condition. |
timeout
Amount of time in microseconds the call will block waiting for I/O to become ready. This parameter is a variable of type st_utime_t. If this time expires without any I/O becoming ready, st_netfd_poll() returns an error and sets errno to ETIME. Note that timeouts are measured since the last context switch.
EBADF | The underlying OS file descriptor is invalid. |
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred without any I/O becoming ready. |
Despite having an interface like poll(2), this function uses the same event notification mechanism as the rest of the library. For instance if an alternative event nofication mechanism was set using st_set_eventsys(), this function uses that mechanism to check for events.
Note: if kqueue(2) is used as an alternative event notification mechanism (see st_set_eventsys()), the POLLPRI event flag is not supported and st_netfd_poll() will return an error if it's set (errno will be set to EINVAL).
st_accept()
Accepts a connection on a specified file descriptor object.
#include <st.h> st_netfd_t st_accept(st_netfd_t fd, struct sockaddr *addr, int *addrlen, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t) representing the rendezvous socket on which the caller is willing to accept new connections. This object has been created from a valid listening socket by st_netfd_open() or st_netfd_open_socket().
addr
If this value is non-zero, it is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer (see accept(3)).
addrlen
This parameter should initially contain the amount of space pointed to by addr; on return it will contain the actual length (in bytes) of the address returned (see accept(3)).
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the accept operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and no pending connection was accepted. |
st_accept() blocks the calling thread until either a new connection is successfully accepted or an error occurs. If no pending connection can be accepted before the time limit, this function returns NULL and sets errno to ETIME.
st_connect()
Initiates a connection on a specified file descriptor object.
#include <st.h> int st_connect(st_netfd_t fd, struct sockaddr *addr, int addrlen, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t) representing a socket.
addr
A pointer to the address of the peer to which the socket is to be connected.
addrlen
This parameter specifies the amount of space pointed to by addr.
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the connect operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and connection setup was not completed. |
st_connect() blocks the calling thread until either the connection is successfully established or an error occurs. If the connection setup cannot complete before the specified time limit, this function fails with errno set to ETIME.
st_read()
Reads data from a specified file descriptor object.
#include <st.h> ssize_t st_read(st_netfd_t fd, void *buf, size_t nbyte, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
buf
A pointer to a buffer to hold the data read in. On output the buffer contains the data.
nbyte
The size of buf in bytes.
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the read operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and no data was read. |
st_read_fully()
Reads the specified amount of data in full from a file descriptor object.
#include <st.h> ssize_t st_read_fully(st_netfd_t fd, void *buf, size_t nbyte, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
buf
A pointer to a buffer to hold the data read in. On output the buffer contains the data.
nbyte
The amount of data to be read in full (in bytes). It must not exceed the size of buf.
timeout
A value of type st_utime_t specifying the inactivity timeout (in microseconds). Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred. |
st_read_resid()
Reads the specified amount of data in full from a file descriptor object.
#include <st.h> int st_read_resid(st_netfd_t fd, void *buf, size_t *resid, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
buf
A pointer to a buffer to hold the data read in. On output the buffer contains the data.
resid
A pointer to a number of bytes. On entry, the amount of data to be read in full. It must not exceed the size of buf. On return, the amount of data remaining to be read. (A non-zero returned value means some but not all of the data was read.)
timeout
A value of type st_utime_t specifying the inactivity timeout (in microseconds). Note that timeouts are measured since the last context switch.
Otherwise, a value of -1 is returned, *resid is non-zero, and errno is set to indicate the error. Possible errno values are the same as set by the read(2) call with two exceptions:
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred. |
st_readv()
Reads data from a specified file descriptor object into multiple buffers.
#include <st.h> ssize_t st_readv(st_netfd_t fd, const struct iovec *iov, int iov_size, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
iov
An array of iovec structures that identify the buffers for holding the data read in. On return the buffers contain the data.
iov_size
The number of iovec structures in the iov array.
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the read operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and no data was read. |
st_readv_resid()
Reads the specified amount of data in full from a file descriptor object
into multiple buffers.
#include <st.h> int st_readv_resid(st_netfd_t fd, struct iovec **iov, int *iov_size, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
iov
A pointer to an array of iovec structures. On entry, the iovecs identify the buffers for holding the data read in. On return, the incomplete iovecs. This function modifies both the pointer and the array to which it points.
iov_size
A pointer to a number of iovec structures. On entry, the number of iovec structures pointed to by *iov. On return, the number of incomplete or unused iovec structures. (A non-zero returned value means some but not all of the data was read.)
timeout
A value of type st_utime_t specifying the inactivity timeout (in microseconds). Note that timeouts are measured since the last context switch.
Otherwise, a value of -1 is returned, *iov_size is non-zero, and errno is set to indicate the error. *iov points to the first unused iovec. Possible errno values are the same as set by the readv(2) call with two exceptions:
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred. |
All of the iovecs before *iov are modified such that iov_base points to the end of the original buffer and iov_len is zero.
st_write()
Writes a buffer of data to a specified file descriptor object.
#include <st.h> ssize_t st_write(st_netfd_t fd, const void *buf, size_t nbyte, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
buf
A pointer to the buffer holding the data to be written.
nbyte
The amount of data in bytes to be written from the buffer.
timeout
A value of type st_utime_t specifying the inactivity timeout (in microseconds). Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred. |
st_write_resid()
Writes a buffer of data to a specified file descriptor object.
#include <st.h> int st_write_resid(st_netfd_t fd, const void *buf, size_t *resid, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
buf
A pointer to the buffer holding the data to be written.
resid
A pointer to a number of bytes. On entry, the amount of data to be written from the buffer. On return, the amount of data remaining to be written. (A non-zero returned value means some but not all of the data was written.)
timeout
A value of type st_utime_t specifying the inactivity timeout (in microseconds). Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred. |
st_writev()
Writes data to a specified file descriptor object from multiple buffers.
#include <st.h> ssize_t st_writev(st_netfd_t fd, const struct iovec *iov, int iov_size, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
iov
An array of iovec structures that describe the buffers to write from (see writev(2)).
iov_size
Number of iovec structures in the iov array.
timeout
A value of type st_utime_t specifying the inactivity timeout (in microseconds). Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred. |
st_writev_resid()
Writes multiple buffers of data to a specified file descriptor object.
#include <st.h> int st_writev_resid(st_netfd_t fd, struct iovec **iov, int *iov_size, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t).
iov
A pointer to an array of iovec structures. On entry, the iovecs identify the buffers holding the data to write. On return, the incomplete iovecs. This function modifies both the pointer and the array to which it points.
iov_size
A pointer to a number of iovec structures. On entry, the number of iovec structures pointed to by *iov. On return, the number of incomplete or unused iovec structures. (A non-zero returned value means some but not all of the data was written.)
timeout
A value of type st_utime_t specifying the inactivity timeout (in microseconds). Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred. |
All of the iovecs before *iov are modified such that iov_base points to the end of the original buffer and iov_len is zero.
st_recvfrom()
Receives bytes from a file descriptor object and stores the sending peer's
address.
#include <st.h> int st_recvfrom(st_netfd_t fd, void *buf, int len, struct sockaddr *from, int *fromlen, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t) representing a UDP socket.
buf
A pointer to a buffer to hold the data received.
len
The size of buf in bytes.
from
If this parameter is not a NULL pointer, the source address of the message is filled in (see recvfrom(3)).
fromlen
This is a value-result parameter, initialized to the size of the buffer associated with from, and modified on return to indicate the actual size of the address stored there.
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the receive operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and no data was received. |
st_recvfrom() blocks the calling thread until one or more bytes are transferred, a timeout has occurred, or there is an error. No more than len bytes will be transferred.
st_sendto()
Sends bytes to a specified destination.
#include <st.h> int st_sendto(st_netfd_t fd, const void *msg, int len, struct sockaddr *to, int tolen, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t) representing a UDP socket.
msg
A pointer to a buffer containing the message to be sent.
len
The length of the message to be sent (in bytes).
to
A pointer to the address of the destination (see sendto(3)).
tolen
This parameter specifies the size of the destination address.
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the send operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and no data was sent. |
st_recvmsg()
Receives a message from a file descriptor object.
#include <st.h> int st_recvmsg(st_netfd_t fd, struct msghdr *msg, int flags, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t) representing a UDP socket.
msg
A pointer to a msghdr structure to describe the data received.
flags
Control flags for recvmsg(3).
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the receive operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and no data was received. |
st_recvmsg() blocks the calling thread until one or more bytes are transferred, a timeout has occurred, or there is an error.
st_sendmsg()
Sends a message to a file descriptor object.
#include <st.h> int st_sendmsg(st_netfd_t fd, const struct msghdr *msg, int flags, st_utime_t timeout);
fd
A file descriptor object identifier (see st_netfd_t) representing a UDP socket.
msg
A pointer to a msghdr structure describing the message to be sent.
flags
Control flags for sendmsg(3).
timeout
A value of type st_utime_t specifying the time limit in microseconds for completion of the send operation. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
ETIME | The timeout occurred and no data was sent. |
st_open()
Opens a file for reading, writing, or both.
#include <st.h> st_netfd_t st_open(const char *path, int oflags, mode_t mode);
path
The pathname of the file to be opened.
oflags
File status flags. These are the same flags that are used by the open(2) system call.
mode
Access permission bits of the file mode, if the file is created when O_CREAT is set in oflags (see open(2)).
The primary purpose of this function is to open FIFOs (named pipes) or other special files in order to create an end point of communication. However, it can be used on regular files as well.
Among other things, this function always sets a non-blocking flag on the underlying OS file descriptor, so there is no need to include that flag in oflags.
st_poll()
Detects when I/O is ready for a set of OS file descriptors.
#include <st.h> int st_poll(struct pollfd *pds, int npds, st_utime_t timeout);
pds
A pointer to an array of pollfd structures (see poll(2)).
npds
The number of elements in the pds array.
timeout
A value of type st_utime_t specifying the amount of time in microseconds the call will block waiting for I/O to become ready. If this time expires without any I/O becoming ready, st_poll() returns zero. Note that timeouts are measured since the last context switch.
EINTR | The current thread was interrupted by st_thread_interrupt(). |
If an alternative event notification mechanism has been set by st_set_eventsys(), other values of errno could be set upon failure as well. The values depend on the specific mechanism in use.
The pollfd structure is defined in the poll.h header file and contains the following members:
int fd; /* OS file descriptor */ short events; /* requested events */ short revents; /* returned events */The events field should be set to the I/O events (readable, writable, exception, or some combination) that the caller is interested in. On return, the revents field is set to indicate what kind of I/O is ready on the respective descriptor.
The events and revents fields are constructed by OR-ing any combination of the following event flags (defined in poll.h):
POLLIN | fd is readable. |
POLLOUT | fd is is writable. |
POLLPRI | fd has an exception condition. |
POLLNVAL | fd is bad. |
The POLLNVAL flag is only valid in the revents field; it is not used in the events field.
Despite having an interface like poll(2), this function uses the same event notification mechanism as the rest of the library. For instance if an alternative event nofication mechanism was set using st_set_eventsys(), this function uses that mechanism to check for events.
Note that unlike the poll(2) call, this function has the timeout parameter expressed in microseconds. If the value of timeout is ST_UTIME_NO_TIMEOUT (-1), this function blocks until a requested I/O event occurs or until the call is interrupted by st_thread_interrupt().
Note: if kqueue(2) is used as an alternative event notification mechanism (see st_set_eventsys()), the POLLPRI event flag is not supported and st_poll() will return an error if it's set (errno will be set to EINVAL).
Generally, the following steps should be followed when writing an application using the State Threads library:
Note that only State Threads library I/O functions should be used for a network I/O: any other I/O calls may block the calling process indefinitely. For example, standard I/O functions (fgets(3), fread(3), fwrite(3), fprintf(3), etc.) call read(2) and write(2) directly and therefore should not be used on sockets or pipes.
Also note that for short timeouts to work the program should do context switches (for example by calling st_usleep()) on a regular basis.
The thread context switch (process state change) can only happen in a well-known set of blocking functions. Only the following functions can block the calling thread: