Threads Library Functions pthread_create(3THR) NAME pthread_create - create a thread SYNOPSIS cc -mt [ flag... ] file...- lpthread [ library... ] #include int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine, void*),void *arg); DESCRIPTION The pthread_create() function is used to create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes are used. (See pthread_attr_init(3THR)). If the attributes specified by attr are modified later, the thread's attributes are not affected. Upon successful completion, pthread_create() stores the ID of the created thread in the location refer- enced by thread. The thread is created executing start_routine with arg as its sole argument. If the start_routine returns, the effect is as if there was an implicit call to pthread_exit() using the return value of start_routine as the exit status. Note that the thread in which main() was originally invoked differs from this. When it returns from main(), the effect is as if there was an implicit call to exit() using the return value of main() as the exit status. The signal state of the new thread is initialised as fol- lows: o The signal mask is inherited from the creating thread. o The set of signals pending for the new thread is empty. Default thread creation: pthread_t tid; void *start_func(void *), *arg; pthread_create(&tid, NULL, start_func, arg); This would have the same effect as: pthread_attr_t attr; pthread_attr_init(&attr); /* initialize attr with default attributes */ pthread_create(&tid, &attr, start_func, arg); SunOS 5.8 Last change: 15 May 1998 1 Threads Library Functions pthread_create(3THR) User-defined thread creation: To create a thread that is scheduled on a system-wide basis, use: pthread_attr_init(&attr); /* initialize attr with default attributes */ pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); /* system-wide contention */ pthread_create(&tid, &attr, start_func, arg); To customize the attributes for POSIX threads, see pthread_attr_init(3THR). A new thread created with pthread_create() uses the stack specified by the stackaddr attribute, and the stack contin- ues for the number of bytes specified by the stacksize attribute. By default, the stack size is 1 megabyte for 32- bit processes and 2 megabyte for 64-bit processes (see pthread_attr_setstacksize(3THR)). If the default is used for both the stackaddr and stacksize attributes, pthread_create() creates a stack for the new thread with at least 1 megabyte for 32-bit processes and 2 megabyte for 64-bit processes. (For customizing stack sizes, see NOTES). If pthread_create() fails, no new thread is created and the contents of the location referenced by thread are undefined. RETURN VALUES If successful, the pthread_create() function returns 0. Otherwise, an error number is returned to indicate the error. ERRORS The pthread_create() function will fail if: ENOMEM The system lacked the necessary resources to create another thread. EINVAL The value specified by attr is invalid. EPERM The caller does not have appropriate permission to set the required scheduling parameters or scheduling pol- icy. EXAMPLES Example 1: This is an example of concurrency with multi- threading. Since POSIX threads and Solaris threads are fully compatible even within the same process, this example uses pthread_create() if you execute a.out 0, or thr_create() if you execute a.out 1. Five threads are created that simultaneously perform a time-consuming function, sleep(10). If the execution of this SunOS 5.8 Last change: 15 May 1998 2 Threads Library Functions pthread_create(3THR) process is timed, the results will show that all five indi- vidual calls to sleep for ten-seconds completed in about ten seconds, even on a uniprocessor. If a single-threaded pro- cess calls sleep(10) five times, the execution time will be about 50-seconds. The command-line to time this process is: /usr/bin/time a.out 0 (for POSIX threading) or /usr/bin/time a.out 1 (for Solaris threading) /* cc thisfile.c -lthread -lpthread */ #define _REENTRANT /* basic 3-lines for threads */ #include #include #define NUM_THREADS 5 #define SLEEP_TIME 10 void *sleeping(void *); /* thread routine */ int i; thread_t tid[NUM_THREADS]; /* array of thread IDs */ int main(int argc, char *argv[]) { if (argc == 1) { printf("use 0 as arg1 to use pthread_create()\n"); printf("or use 1 as arg1 to use thr_create()\n"); return (1); } switch (*argv[1]) { case '0': /* POSIX */ for ( i = 0; i < NUM_THREADS; i++) pthread_create(&tid[i], NULL, sleeping, (void *)SLEEP_TIME); for ( i = 0; i < NUM_THREADS; i++) pthread_join(tid[i], NULL); break; case '1': /* Solaris */ for ( i = 0; i < NUM_THREADS; i++) thr_create(NULL, 0, sleeping, (void *)SLEEP_TIME, 0, &tid[i]); while (thr_join(NULL, NULL, NULL) == 0) ; break; } /* switch */ SunOS 5.8 Last change: 15 May 1998 3 Threads Library Functions pthread_create(3THR) printf("main() reporting that all %d threads have terminated\n", i); return (0); } /* main */ void * sleeping(void *arg) { int sleep_time = (int)arg; printf("thread %d sleeping %d seconds ...\n", thr_self(), sleep_time); sleep(sleep_time); printf("\nthread %d awakening\n", thr_self()); return (NULL); } Example 2: If main() had not waited for the completion of the other threads (using pthread_join(3THR) or thr_join(3THR)), it would have continued to process con- currently until it reached the end of its routine and the entire process would have exited prematurely (see exit(2)). ATTRIBUTES See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | MT-Level | MT-Safe | |_____________________________|_____________________________| SEE ALSO fork(2), sysconf(3C), pthread_attr_init(3THR), pthread_cancel(3THR), pthread_exit(3THR), pthread_join(3THR), attributes(5), standards(5) NOTES MT application threads execute independently of each other, thus their relative behavior is unpredictable. Therefore, it is possible for the thread executing main() to finish before all other user application threads. pthread_join(3THR), on the other hand, must specify the ter- minating thread (IDs) for which it will wait. A user-specified stack size must be greater than the value PTHREAD_STACK_MIN. A minimum stack size may not accommodate the stack frame for the user thread function start_func. If a stack size is specified, it must accommodate start_func requirements and the functions that it may call in turn, in addition to the minimum requirement. SunOS 5.8 Last change: 15 May 1998 4 Threads Library Functions pthread_create(3THR) It is usually very difficult to determine the runtime stack requirements for a thread. PTHREAD_STACK_MIN specifies how much stack storage is required to execute a NULL start_func. The total runtime requirements for stack storage are depen- dent on the storage required to do runtime linking, the amount of storage required by library runtimes (as printf()) that your thread calls. Since these storage parameters are not known before the program runs, it is best to use default stacks. If you know your runtime requirements or decide to use stacks that are larger than the default, then it makes sense to specify your own stacks. SunOS 5.8 Last change: 15 May 1998 5 System Calls exec(2) NAME exec, execl, execle, execlp, execv, execve, execvp - execute a file SYNOPSIS #include int execl(const char *path, const char *arg0, ... /* const char *argn, (char *)0 */); int execv(const char *path, char *const argv[]); int execle(const char *path, const char *arg0, ... /* const char *argn, (char *)0, char *const envp[]*/); int execve(const char *path, char *const argv[], char *const envp[]); int execlp(const char *file, const char *arg0, ... /* const char *argn, (char *)0 */); int execvp(const char *file, char *const argv[]); DESCRIPTION Each of the functions in the exec family replaces the current process image with a new process image. The new image is constructed from a regular, executable file called the new process image file. This file is either an execut- able object file or a file of data for an interpreter. There is no return from a successful call to one of these func- tions because the calling process image is overlaid by the new process image. An interpreter file begins with a line of the form #! pathname [arg] where pathname is the path of the interpreter, and arg is an optional argument. When an interpreter file is executed, the system invokes the specified interpreter. The pathname specified in the interpreter file is passed as arg0 to the interpreter. If arg was specified in the interpreter file, it is passed as arg1 to the interpreter. The remaining argu- ments to the interpreter are arg0 through argn of the origi- nally exec'd file. The interpreter named by pathname must not be an interpreter file. When a C-language program is executed as a result of this call, it is entered as a C-language function call as fol- lows: SunOS 5.10 Last change: 18 Dec 2003 1 System Calls exec(2) int main (int argc, char *argv[], char *envp[]); where argc is the argument count, argv is an array of char- acter pointers to the arguments themselves, and envp is an array of character pointers to the environment strings. The argv and environ arrays are each terminated by a null pointer. The null pointer terminating the argv array is not counted in argc. The value of argc is non-negative, and if greater than 0, argv[0] points to a string containing the name of the file. If argc is 0, argv[0] is a null pointer, in which case there are no arguments. Applications should verify that argc is greater than 0 or that argv[0] is not a null pointer before dereferencing argv[0]. The arguments specified by a program with one of the exec functions are passed on to the new process image in the main() arguments. The path argument points to a path name that identifies the new process image file. The file argument is used to construct a pathname that iden- tifies the new process image file. If the file argument con- tains a slash character, it is used as the pathname for this file. Otherwise, the path prefix for this file is obtained by a search of the directories passed in the PATH environ- ment variable (see environ(5)). The environment is supplied typically by the shell. If the process image file is not a valid executable object file, execlp() and execvp() use the contents of that file as standard input to the shell. In this case, the shell becomes the new process image. The standard to which the caller conforms determines which shell is used. See standards(5). The arguments represented by arg0... are pointers to null- terminated character strings. These strings constitute the argument list available to the new process image. The list is terminated by a null pointer. The arg0 argument should point to a filename that is associated with the process being started by one of the exec functions. The argv argument is an array of character pointers to null-terminated strings. The last member of this array must be a null pointer. These strings constitute the argument list available to the new process image. The value in argv[0] should point to a filename that is associated with the process being started by one of the exec functions. The envp argument is an array of character pointers to null-terminated strings. These strings constitute the environment for the new process image. The envp array is SunOS 5.10 Last change: 18 Dec 2003 2 System Calls exec(2) terminated by a null pointer. For execl(), execv(), execvp(), and execlp(), the C-language run-time start-off routine places a pointer to the environment of the calling process in the global object extern char **environ, and it is used to pass the environment of the calling process to the new process image. The number of bytes available for the new process's combined argument and environment lists is ARG_MAX. It is implementation-dependent whether null terminators, pointers, and/or any alignment bytes are included in this total. File descriptors open in the calling process image remain open in the new process image, except for those whose close-on-exec flag FD_CLOEXEC is set; see fcntl(2). For those file descriptors that remain open, all attributes of the open file description, including file locks, remain unchanged. The preferred hardware address translation size (see memcntl(2)) for the stack and heap of the new process image are set to the default system page size. Directory streams open in the calling process image are closed in the new process image. The state of conversion descriptors and message catalogue descriptors in the new process image is undefined. For the new process, the equivalent of: setlocale(LC_ALL, "C") is executed at startup. Signals set to the default action (SIG_DFL) in the calling process image are set to the default action in the new pro- cess image (see signal(3C)). Signals set to be ignored (SIG_IGN) by the calling process image are set to be ignored by the new process image. Signals set to be caught by the calling process image are set to the default action in the new process image (see signal.h(3HEAD)). After a successful call to any of the exec functions, alternate signal stacks are not preserved and the SA_ONSTACK flag is cleared for all signals. After a successful call to any of the exec functions, any functions previously registered by atexit(3C) are no longer registered. The saved resource limits in the new process image are set to be a copy of the process's corresponding hard and soft SunOS 5.10 Last change: 18 Dec 2003 3 System Calls exec(2) resource limits. If the ST_NOSUID bit is set for the file system containing the new process image file, then the effective user ID and effective group ID are unchanged in the new process image. If the set-user-ID mode bit of the new process image file is set (see chmod(2)), the effective user ID of the new process image is set to the owner ID of the new process image file. Similarly, if the set-group-ID mode bit of the new process image file is set, the effective group ID of the new process image is set to the group ID of the new process image file. The real user ID and real group ID of the new process image remain the same as those of the calling process image. The effective user ID and effective group ID of the new process image are saved (as the saved set-user-ID and the saved set-group-ID for use by setuid(2). The privilege sets are changed according to the following rules: 1. The inheritable set, I, is intersected with the limit set, L. This mechanism enforces the limit set for processes. 2. The effective set, E, and the permitted set, P, are made equal to the new inheritable set. The system attempts to set the privilege-aware state to non-PA both before performing any modifications to the pro- cess IDs and privilege sets as well as after completing the transition to new UIDs and privilege sets, following the rules outlined in privileges(5). If the {PRIV_PROC_OWNER} privilege is asserted in the effec- tive set, the set-user-ID and set-group-ID bits will be honored when the process is being controlled by ptrace(3C). Additional restriction can apply when the traced process has an effective UID of 0. See privileges(5). Any shared memory segments attached to the calling process image will not be attached to the new process image (see shmop(2)). Any mappings established through mmap() are not preserved across an exec. Memory mappings created in the process are unmapped before the address space is rebuilt for the new process image. See mmap(2). Memory locks established by the calling process via calls to mlockall(3C) or mlock(3C) are removed. If locked pages in the address space of the calling process are also mapped into the address spaces the locks established by the other SunOS 5.10 Last change: 18 Dec 2003 4 System Calls exec(2) processes will be unaffected by the call by this process to the exec function. If the exec function fails, the effect on memory locks is unspecified. If _XOPEN_REALTIME is defined and has a value other than -1, any named semaphores open in the calling process are closed as if by appropriate calls to sem_close(3RT) Profiling is disabled for the new process; see profil(2). Timers created by the calling process with timer_create(3RT) are deleted before replacing the current process image with the new process image. For the SCHED_FIFO and SCHED_RR scheduling policies, the policy and priority settings are not changed by a call to an exec function. All open message queue descriptors in the calling process are closed, as described in mq_close(3RT). Any outstanding asynchronous I/O operations may be can- celled. Those asynchronous I/O operations that are not can- celed will complete as if the exec function had not yet occurred, but any associated signal notifications are suppressed. It is unspecified whether the exec function itself blocks awaiting such I/O completion. In no event, however, will the new process image created by the exec function be affected by the presence of outstanding asyn- chronous I/O operations at the time the exec function is called. All active contract templates are cleared (see contract(4)). The new process also inherits the following attributes from the calling process: o nice value (see nice(2)) o scheduler class and priority (see priocntl(2)) o process ID o parent process ID o process group ID o task ID o supplementary group IDs o SunOS 5.10 Last change: 18 Dec 2003 5 System Calls exec(2) semadj values (see semop(2)) o session membership (see exit(2) and signal(3C)) o real user ID o real group ID o project ID o trace flag (see ptrace(3C) request 0) o time left until an alarm clock signal (see alarm(2)) o current working directory o root directory o file mode creation mask (see umask(2)) o file size limit (see ulimit(2)) o resource limits (see getrlimit(2)) o tms_utime, tms_stime, tms_cutime, and tms_cstime (see times(2)) o file-locks (see fcntl(2) and lockf(3C)) o controlling terminal o process signal mask (see sigprocmask(2)) o pending signals (see sigpending(2)) o processor bindings (see processor_bind(2)) o processor set bindings (see pset_bind(2)) o limit privilege set o privilege debugging flag (see privileges(5) and getpflags(2)) A call to any exec function from a process with more than one thread results in all threads being terminated and the new executable image being loaded and executed. No destruc- tor functions will be called. Upon successful completion, each of the functions in the exec family marks for update the st_atime field of the file. SunOS 5.10 Last change: 18 Dec 2003 6 System Calls exec(2) If an exec function failed but was able to locate the pro- cess image file, whether the st_atime field is marked for update is unspecified. Should the function succeed, the pro- cess image file is considered to have been opened with open(2). The corresponding close(2) is considered to occur at a time after this open, but before process termination or successful completion of a subsequent call to one of the exec functions. The argv[] and envp[] arrays of pointers and the strings to which those arrays point will not be modified by a call to one of the exec functions, except as a conse- quence of replacing the process image. The saved resource limits in the new process image are set to be a copy of the process's corresponding hard and soft limits. RETURN VALUES If a function in the exec family returns to the calling pro- cess image, an error has occurred; the return value is -1 and errno is set to indicate the error. ERRORS The exec functions will fail if: E2BIG The number of bytes in the new process's argument list is greater than the system- imposed limit of {ARG_MAX} bytes. The argu- ment list limit is sum of the size of the argument list plus the size of the environment's exported shell variables. EACCES Search permission is denied for a directory listed in the new process file's path pre- fix. The new process file is not an ordinary file. The new process file mode denies execute permission. The {FILE_DAC_SEARCH} privilege overrides the restriction on directory searches. The {FILE_DAC_EXECUTE} privilege overrides the lack of execute permission. SunOS 5.10 Last change: 18 Dec 2003 7 System Calls exec(2) EAGAIN Total amount of system memory available when reading using raw I/O is temporarily insuf- ficient. EFAULT An argument points to an illegal address. EINVAL The new process image file has the appropri- ate permission and has a recognized execut- able binary format, but the system does not support execution of a file with this for- mat. EINTR A signal was caught during the execution of one of the functions in the exec family. ELOOP Too many symbolic links were encountered in translating path or file. ENAMETOOLONG The length of the file or path argument exceeds {PATH_MAX}, or the length of a file or path component exceeds {NAME_MAX} while {_POSIX_NO_TRUNC} is in effect. ENOENT One or more components of the new process path name of the file do not exist or is a null pathname. ENOLINK The path argument points to a remote machine and the link to that machine is no longer active. ENOTDIR A component of the new process path of the file prefix is not a directory. SunOS 5.10 Last change: 18 Dec 2003 8 System Calls exec(2) The exec functions, except for execlp() and execvp(), will fail if: ENOEXEC The new process image file has the appropriate access permission but is not in the proper format. The exec functions may fail if: ENAMETOOLONG Pathname resolution of a symbolic link pro- duced an intermediate result whose length exceeds {PATH_MAX}. ENOMEM The new process image requires more memory than is allowed by the hardware or system- imposed by memory management constraints. See brk(2). ETXTBSY The new process image file is a pure pro- cedure (shared text) file that is currently open for writing by some process. USAGE As the state of conversion descriptors and message catalogue descriptors in the new process image is undefined, portable applications should not rely on their use and should close them prior to calling one of the exec functions. Applications that require other than the default POSIX locale should call setlocale(3C) with the appropriate param- eters to establish the locale of thenew process. The environ array should not be accessed directly by the application. ATTRIBUTES See attributes(5) for descriptions of the following attri- butes: SunOS 5.10 Last change: 18 Dec 2003 9 System Calls exec(2) ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | Interface Stability | Standard | |_____________________________|_____________________________| | MT-Level | See below. | |_____________________________|_____________________________| The execle() and execve() fucntions are Async-Signal-Safe. SEE ALSO ksh(1), ps(1), sh(1), alarm(2), brk(2), chmod(2), exit(2), fcntl(2), fork(2), getpflags(2), getrlimit(2), memcntl(2), mmap(2), nice(2), priocntl(2), profil(2), semop(2), shmop(2), sigpending(2), sigprocmask(2), times(2), umask(2), lockf(3C), ptrace(3C), setlocale(3C), signal(3C), system(3C), timer_create(3RT), a.out(4), contract(4), attri- butes(5), environ(5), privileges(5), standards(5) WARNINGS If a program is setuid to a user ID other than the superuser, and the program is executed when the real user ID is super-user, then the program has some of the powers of a super-user as well. SunOS 5.10 Last change: 18 Dec 2003 10 System Calls fork(2) NAME fork, fork1 - create a new process SYNOPSIS #include #include pid_t fork(void); pid_t fork1(void); DESCRIPTION The fork() and fork1() functions create a new process. The new process (child process) is an exact copy of the calling process (parent process). The child process inherits the following attributes from the parent process: o real user ID, real group ID, effective user ID, effec- tive group ID o environment o open file descriptors o close-on-exec flags (see exec(2)) o signal handling settings (that is, SIG_DFL, SIG_IGN, SIG_HOLD, function address) o supplementary group IDs o set-user-ID mode bit o set-group-ID mode bit o profiling on/off status o nice value (see nice(2)) o scheduler class (see priocntl(2)) o all attached shared memory segments (see shmop(2)) o process group ID -- memory mappings (see mmap(2)) o session ID (see exit(2)) o current working directory o root directory o file mode creation mask (see umask(2)) SunOS 5.8 Last change: 10 Dec 1999 1 System Calls fork(2) o resource limits (see getrlimit(2)) o controlling terminal o saved user ID and group ID o task ID and project ID Scheduling priority and any per-process scheduling parame- ters that are specific to a given scheduling class may or may not be inherited according to the policy of that partic- ular class (see priocntl(2)). The child process differs from the parent process in the following ways: o The child process has a unique process ID which does not match any active process group ID. o The child process has a different parent process ID (that is, the process ID of the parent process). o The child process has its own copy of the parent's file descriptors and directory streams. Each of the child's file descriptors shares a common file pointer with the corresponding file descriptor of the parent. o Each shared memory segment remains attached and the value of shm_nattach is incremented by 1. o All semadj values are cleared (see semop(2)). o Process locks, text locks, data locks, and other memory locks are not inherited by the child (see plock(3C) and memcntl(2)). o The child process's tms structure is cleared: tms_utime, stime, cutime, and cstime are set to 0 (see times(2)). o The child processes resource utilizations are set to 0; see getrlimit(2). The it_value and it_interval values for the ITIMER_REAL timer are reset to 0; see getitimer(2). o The set of signals pending for the child process is initialized to the empty set. o Timers created by timer_create(3RT) are not inherited by the child process. o No asynchronous input or asynchronous output opera- tions are inherited by the child. SunOS 5.8 Last change: 10 Dec 1999 2 System Calls fork(2) Record locks set by the parent process are not inherited by the child process (see fcntl(2)). Solaris Threads In applications that use the Solaris threads API rather than the POSIX threads API (applications linked with -lthread but not -lpthread),fork() duplicates in the child process all threads (see thr_create(3THR)) and LWPs in the parent pro- cess. The fork1() function duplicates only the calling thread (LWP) in the child process. POSIX Threads In applications that use the POSIX threads API rather than the Solaris threads API ( applications linked with -lpthread, whether or not linked with -lthread), a call to fork() is like a call to fork1(), which replicates only the calling thread. There is no call that forks a child with all threads and LWPs duplicated in the child. Note that if a program is linked with both libraries (- lthread and -lpthread), the POSIX semantic of fork() pre- vails. fork() Safety If a Solaris threads application calls fork1() or a POSIX threads application calls fork(), and the child does more than simply call exec(), there is a possibility of deadlock occurring in the child. The application should use pthread_atfork(3THR) to ensure safety with respect to this deadlock. A Solaris threads application must explicitly link with -lpthread to access pthread_atfork(). Should there be any outstanding mutexes throughout the process, the application should call pthread_atfork() to wait for and acquire those mutexes prior to calling fork() or fork1(). See "MT-Level of Libraries" on the attributes(5) manual page. RETURN VALUES Upon successful completion, fork() and fork1() return 0 to the child process and return the process ID of the child process to the parent process. Otherwise, (pid_t)-1 is returned to the parent process, no child process is created, and errno is set to indicate the error. ERRORS The fork() function will fail if: EAGAIN The system-imposed limit on the total number of processes under execution by a single user has been exceeded; or the total amount of system memory avail- able is temporarily insufficient to duplicate this SunOS 5.8 Last change: 10 Dec 1999 3 System Calls fork(2) process. ENOMEM There is not enough swap space. ATTRIBUTES See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | MT-Level | fork() is Async-Signal-Safe | |_____________________________|_____________________________| SEE ALSO alarm(2), exec(2), exit(2), fcntl(2), getitimer(2), getrlimit(2), memcntl(2), mmap(2), nice(2), priocntl(2), ptrace(2), semop(2), shmop(2), times(2), umask(2), wait(2), exit(3C), plock(3C), pthread_atfork(3THR), signal(3C), system(3C), thr_create(3THR) timer_create(3RT), attri- butes(5), standards(5) NOTES An applications should call _exit() rather than exit(3C) if it cannot execve(), since exit() will flush and close stan- dard I/O channels and thereby corrupt the parent process's standard I/O data structures. Using exit(3C) will flush buf- fered data twice. See exit(2). The thread (or LWP) in the child that calls fork1() must not depend on any resources held by threads (or LWPs) that no longer exist in the child. In particular, locks held by these threads (or LWPs) will not be released. In a multithreaded process, fork() or fork1() can cause blocking system calls to be interrupted and return with an EINTR error. The fork() and fork1() functions suspend all threads in the process before proceeding. Threads that are executing in the kernel and are in an uninterruptible wait cannot be suspended immediately and therefore cause a delay before fork() and fork1() can complete. During this delay, since all other threads will have already been suspended, the pro- cess will appear "hung." SunOS 5.8 Last change: 10 Dec 1999 4 Sockets Library Functions socket(3SOCKET) NAME socket - create an endpoint for communication SYNOPSIS cc [ flag ... ] file ... -lsocket -lnsl [ library ... ] #include #include int socket(int domain, int type, int protocol); DESCRIPTION socket() creates an endpoint for communication and returns a descriptor. The domain parameter specifies a communications domain within which communication will take place; this selects the protocol family which should be used. The protocol family generally is the same as the address family for the addresses supplied in later operations on the socket. These families are defined in the include file . There must be an entry in the netconfig(4) file for at least each protocol family and type required. If protocol has been specified, but no exact match for the tuplet family, type, protocol is found, then the first entry containing the specified family and type with zero for protocol will be used. The currently understood formats are: PF_UNIX UNIX system internal protocols PF_INET Internet Protocol Version 4 (IPv4) PF_INET6 Internet Protocol Version 6 (IPv6) PF_NCA Network Cache and Accelerator (NCA) protocols The socket has the indicated type, which specifies the com- munication semantics. Currently defined types are: SOCK_STREAM SOCK_DGRAM SOCK_RAW SOCK_SEQPACKET SOCK_RDM A SOCK_STREAM type provides sequenced, reliable, two-way connection-based byte streams. An out-of-band data transmis- sion mechanism may be supported. A SOCK_DGRAM socket sup- ports datagrams (connectionless, unreliable messages of a SunOS 5.8 Last change: 5 Feb 2001 1 Sockets Library Functions socket(3SOCKET) fixed (typically small) maximum length). A SOCK_SEQPACKET socket may provide a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer may be required to read an entire packet with each read system call. This facility is protocol specific, and presently not implemented for any protocol family. SOCK_RAW sockets provide access to internal network interfaces. The types SOCK_RAW, which is available only to the superuser, and SOCK_RDM, for which no implemen- tation currently exists, are not described here. protocol specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family. How- ever, multiple protocols may exist, in which case a particu- lar protocol must be specified in this manner. The protocol number to use is particular to the "communication domain" in which communication is to take place. If a protocol is specified by the caller, then it will be packaged into a socket level option request and sent to the underlying pro- tocol layers. Sockets of type SOCK_STREAM are full-duplex byte streams, similar to pipes. A stream socket must be in a connected state before any data may be sent or received on it. A con- nection to another socket is created with a connect(3SOCKET) call. Once connected, data may be transferred using read(2) and write(2) calls or some variant of the send(3SOCKET) and recv(3SOCKET) calls. When a session has been completed, a close(2) may be performed. Out-of-band data may also be transmitted as described on the send(3SOCKET) manual page and received as described on the recv(3SOCKET) manual page. The communications protocols used to implement a SOCK_STREAM insure that data is not lost or duplicated. If a piece of data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, then the connection is considered broken and calls will indicate an error with -1 returns and with ETIMEDOUT as the specific code in the global variable errno. The protocols optionally keep sockets "warm" by forcing transmissions roughly every minute in the absence of other activity. An error is then indicated if no response can be elicited on an otherwise idle connection for a extended period (for instance 5 minutes). A SIGPIPE signal is raised if a pro- cess sends on a broken stream; this causes naive processes, which do not handle the signal, to exit. SOCK_SEQPACKET sockets employ the same system calls as SOCK_STREAM sockets. The only difference is that read(2) calls will return only the amount of data requested, and any remaining in the arriving packet will be discarded. SunOS 5.8 Last change: 5 Feb 2001 2 Sockets Library Functions socket(3SOCKET) SOCK_DGRAM and SOCK_RAW sockets allow datagrams to be sent to correspondents named in sendto(3SOCKET) calls. Datagrams are generally received with recvfrom(3SOCKET), which returns the next datagram with its return address. An fcntl(2) call can be used to specify a process group to receive a SIGURG signal when the out-of-band data arrives. It may also enable non-blocking I/O and asynchronous notifi- cation of I/O events with SIGIO signals. The operation of sockets is controlled by socket level options. These options are defined in the file . setsockopt(3SOCKET) and getsockopt(3SOCKET) are used to set and get options, respectively. RETURN VALUES A -1 is returned if an error occurs. Otherwise the return value is a descriptor referencing the socket. ERRORS The socket() call fails if: EACCES Permission to create a socket of the specified type and/or protocol is denied. EMFILE The per-process descriptor table is full. ENOMEM Insufficient user memory is available. ENOSR There were insufficient STREAMS resources available to complete the operation. EPROTONOSUPPORT The protocol type or the specified protocol is not supported within this domain. ATTRIBUTES See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | MT-Level | Safe | |_____________________________|_____________________________| SEE ALSO SunOS 5.8 Last change: 5 Feb 2001 3 Sockets Library Functions socket(3SOCKET) nca(1), close(2), fcntl(2), ioctl(2), read(2), write(2), accept(3SOCKET), bind(3SOCKET), connect(3SOCKET), getsockname(3SOCKET), getsockopt(3SOCKET), listen(3SOCKET), recv(3SOCKET), setsockopt(3SOCKET), send(3SOCKET), shutdown(3SOCKET), socketpair(3SOCKET), attributes(5), in(3HEAD), socket(3HEAD) SunOS 5.8 Last change: 5 Feb 2001 4 Sockets Library Functions bind(3SOCKET) NAME bind - bind a name to a socket SYNOPSIS cc [ flag ... ] file ... -lsocket -lnsl [ library ... ] #include #include int bind(int s, const struct sockaddr *name, int namelen); DESCRIPTION bind() assigns a name to an unnamed socket. When a socket is created with socket(3SOCKET), it exists in a name space (address family) but has no name assigned. bind() requests that the name pointed to by name be assigned to the socket. RETURN VALUES If the bind is successful, 0 is returned. A return value of -1 indicates an error, which is further specified in the global errno. ERRORS The bind() call will fail if: EACCES The requested address is protected and the current user has inadequate permission to access it. EADDRINUSE The specified address is already in use. EADDRNOTAVAIL The specified address is not available on the local machine. EBADF s is not a valid descriptor. EINVAL namelen is not the size of a valid address for the specified address family. EINVAL The socket is already bound to an address. ENOSR There were insufficient STREAMS resources for the operation to complete. ENOTSOCK s is a descriptor for a file, not a socket. The following errors are specific to binding names in the UNIX domain: SunOS 5.8 Last change: 22 Oct 1999 1 Sockets Library Functions bind(3SOCKET) EACCES Search permission is denied for a component of the path prefix of the pathname in name. EIO An I/O error occurred while making the directory entry or allocating the inode. EISDIR A null pathname was specified. ELOOP Too many symbolic links were encountered in translat- ing the pathname in name. ENOENT A component of the path prefix of the pathname in name does not exist. ENOTDIR A component of the path prefix of the pathname in name is not a directory. EROFS The inode would reside on a read-only file system. ATTRIBUTES See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | MT-Level | Safe | |_____________________________|_____________________________| SEE ALSO unlink(2), socket(3SOCKET), attributes(5), socket(3HEAD) NOTES Binding a name in the UNIX domain creates a socket in the file system that must be deleted by the caller when it is no longer needed (using unlink(2)). The rules used in name binding vary between communication domains. SunOS 5.8 Last change: 22 Oct 1999 2