Linux Communications

Appendix B Unix Error Messages

Errors generated by the failure of a system call or library function, can be displayed using the perror or strerror library function calls (see Managing Failures Section 1.5, Managing System Call Failures). For example, the error messages returned by strerror on a Linux system can be displayed in their entirety using Program B.1. Program B.1 Displaying strerror messages. for (int err 0 err < sys_nerr ++err) cout err ' t' strerror(err) endl As the output of the program will fill more than one...

Exercise

The discussion in the text centers on a parent process waiting for a child process to terminate or stop. We already have the tools necessary for a child process to determine if its parent process has terminated. Show how this can be done. What are the advantages and disadvantages of your implementation On some occasions, the information returned from wait orwaitpid may be insufficient. Additional information on resource usage by a child process may be sought. There are two BSD compatibility...

We then use rpcgen with the a and c flags to generate the header file the client and server stub files the client and

Figure 9.20 Using rpcgen with the -a and -C flags. linux rpcgen -a -C fact.x linux Is -x fact_client.c fact_clnt.c fact.h fact_server.c fact_svc.c fact.x Makefile.fact As shown, passing rpcgen the protocol definition file with the -a and -c flags generates six files the header file, fact.h, and the RPC stub files, fact_cint.c and fact_svc.c, which are similar in content and nature to those in the previous example. The three new files created by rpcgen bear further investigation. The client...

Introduction

Conceptually, a semaphore is a data structure that is shared by several processes. Semaphores are most often used to synchronize operations when multiple processes access a common, non-shareable resource. By using semaphores, we attempt to avoid starvation (which occurs when a process is habitually denied access to a resource it needs) and deadlock (which occurs when two or more processes each hold a resource that the other needs while waiting for the other process to release its resource)....

Semaphore Control

The semget system call (Table 7.3) is used to create or gain access to a set of semaphores. The semcti system call allows the user to perform a variety of generalized control operations on the system semaphore structure, on the semaphores as a set, and on individual semaphores. Additional manipulative operations on specific semaphores within a set are covered in the following section on semaphore operations (Section 7.4). Table 7.3. Summary of the semcti System Call. < sys types.h> Manual...

Multithread Semaphores

The activities of threads may also be coordinated with semaphores. A semaphore is similar in function to a mutex. However, a semaphore can act as either a binary entity similar to a mutex or as a counting entity. Counting semaphores can be used to manage multiple resources. As they are somewhat more complex, semaphores are more system-intensive than mutexes. Semaphore concepts and operations were presented in some detail in Chapter 7. However, the Chapter 7 semaphore operations are System...

Key Terms and Concepts

Local_sock.h include file < arpa inet.h> include file < netdb.h> include file < netinet in.h> include file < sys iocti.h> include file < sys socket.h> include file < sys time.h> include file < sys un.h> include file < time.h> include file accept system call address resolution protocol (ARP) AFJNET AF_UNIX American Registry for Internet Numbers (ARIN) Asia Pacific Network Information Center (APNIC) BIND domain name system (DNS) dotted decimal notation (DDN)...

Real and Effective User and Group IDs

In UNIX, with the exception of a few special system processes, processes are generated by users (root and otherwise) who have logged on to the system. During the login process the system queries the password file to obtain two identification (ID) numbers. The numbers the system obtains are in the third and fourth fields of the password entry for the user. These are, respectively, the real user ID (UID) and real group ID (GID) for the user. For example, in the sample password file entry 1 J In...

Creating a Shared Memory Segment

The shmget system call is used to create the shared memory segment and generate the associated system data structure or to gain access to an existing segment. The shared memory segment and the system data structure are identified by a unique shared memory identifier that the shmget system call returns (see Table 8.1). Providing no system parameters are exceeded, the shmget system call creates a new shared memory segment if The value for its first argument, key, is the symbolic constant...

Condition Flag Set Action Taken by semop

Semval o Increment semzcnt for the semaphore and wait (block) semval o, then adjust semzcnt and return. semid is removed, then return -1 and seterrno to EIDRM. A signal is caught, then adjust semzcnt and set errno to EINTR. Constant pe rror Message Explanation While in a wait queue for the semaphore, a signal was received by the calling process. The value for nsops is greater than the system limit. The requested operation would cause the calling process to block, but IPC_NOWAIT was specified....

Semaphore Class

As with message queues, the syntax and manipulation of semaphores is somewhat complex, making them a prime candidate for incorporation into a C++ class. A semaphore class would define the relationships between semaphore data and the functions (methods) that manipulate this data. A declaration of a simplified semaphore class called ssemaphore is shown in Figure 7.10. The name ssemaphore (with the extra'S') was chosen to minimize any conflicts with existing semaphore definitions. Figure 7.10...

Mutex Kind ConstantBehavior

Fast PTHREAD_MUTEX_FAST If the mutex is already locked by another thread, the calling thread blocks. If the thread that owns (locked) the mutex attempts to lock it a second time, the thread will deadlock The thread that unlocks the mutex is assumed to be the owner of the mutex. Unlocking a nonlocked mutex will result in undefined behavior. recursive PTHREAD_MUTEX_RECURSIVE The system will the record number of lock requests for the mutex. The mutex is unlocked only when an equal number of unlock...

Permissions Message Required Queues

Msgcti write out semcti set the value of one shmcti write out modified IPC semaphore or a whole set modified IPC status information write out modified IPC status information msgrcv obtain semop block until a message from semaphore becomes 0 queue shmat read from the shared memory segment msgcti to retrieve IPC status information semcti to retrieve IPC status shmcti to retrieve In addition to setting access modes, there are two defined constants, found in , that can be ORed with the access...

Creating a Process

It is apparent that there must be some mechanism by which the system can create a new process. With the exception of some special initial processes generated by the kernel during bootstrapping (e.g., nit), all processes in a Linux environment are created by a fork system call, shown in Table 1.3. The initiating process is termed the parent, and the newly generated process, the child. Table 1.3. Summary of the fork System Call. Include File(s) Manual Section 0 in child, child process ID in the...

Program 1012 Internet domain connectionless server nonblocking

Program 10.12 - SERVER Internet Domain - connectionless - NON-BLOCKING socklen_t serverjen, clientjen struct sockaddrjn server, Internet Addresses + if ((sock socket(PF_INET, SOCK_DGRAM, 0)) 0) perror( SERVER socket ) return 1 if (ioctl(sock, FIONBIO, &flag) 0 ) perror( SERVER ioctl ) return 2 memset(&server, 0, sizeof(server)) Clear structure server.sin_family AF_INET Set address type server.sin_addr.s_addr htonl(INADDR_ANY) if (bind(sock, (struct sockaddr *) &server, sizeof(server)) 0)...

Mutex Variables

One of the easiest methods to ensure coordination is to use a mutual exclusion lock, or mutex. Conceptually, a mutex can be thought of as a binary semaphore with ownership whose state either allows (0, unlocked) or prohibits (nonzero, locked) access. Unlike a binary semaphore, any thread within the scope of a mutex can lock a mutex, but only the thread that locked the mutex should unlock it. Again, while it should not be done, unlocking a mutex that a thread did not lock does not generate an...

Message Queue Control

The ownership and access permissions, established when the message queue was created, can be examined and modified using the msgcti system call (see Table 6.7). The msgcti system call references the message queue indicated by the msqid argument. The value of the cmd argument is used to indicate the action that msgcti should take. The following defined constants actions can be specified Table 6.7. Summary of the msgget System Call. < sys types.h> Manual Section int msgget (int msqid,int cmd,...

Symbolic Constant File Type

The dev argument for mknod is used only when a character or block special file is specified. For character and block special files, the dev argument is used to assign the major and minor number of the device. For nonprivileged users, the mknod system call can only be used to generate a FIFO. When generating a FIFO, the dev argument should be left as 0. If mknod is successful, it returns a value of 0. Otherwise, errno is set to indicate the error, and a value of-1 is returned. The effective ID...

Shared Memory Control

The shmcti system call permits the user to perform a number of generalized control operations on an existing shared memory segment and on the system shared memory data structure (see Table 8.4). Table 8.4. Summary of the shmcti System Call. Summary nt Shmctl(int shmid, int cmd, struct shmid_ds *buf) Success Failure Sets errno There are three arguments for the shmcti system call. The first, shmid, is a valid shared memory segment identifier generated by a prior shmget system call. The second...

Using a File as Shared Memory

Most versions of Linux-UNIX also support the mmap system call, which can be used to map a file to a process's virtual memory address space. In many ways mmap is more flexible than its shared memory system call counterpart. Once a mapping has been established, standard system calls rather than specialized system calls can be used to manipulate the shared memory object (Table 8.11). Unlike memory, the contents of a file are nonvolatile and will remain available even after a system has been shut...

The use of the sigprocmask system call is shown in Program

* Demonstration of the sigprocmask call 7 void signal_catcher(int) < --1 struct sigaction new_action < - 2 sigprocmask(SIG_BLOCK, & new_signals, NULL) new_action.sa_handler signal_catcher 20 if (sigaction(SIGUSR2, & new_action, NULL) -1) cout Waiting for signal endl cout Done endl cout Received signal n will release SIGUSR1 endl sigprocmask(SIG_UNBLOCK, & new_signals, NULL) cout SIGUSR1 released endl (1) Empty (clear) the set of signals. (2) Add the SIGUSR1 signal to this set. The...

Explanation

A signal was received by the process before data was sent. The socket is set to non-blocking, and no connections are pending. Insufficient memory to perform operation. Argument references location outside user address space. toien argument contains an incorrect value. Local end of a connection-oriented socket is closed. The socket argument is a file descriptor, not a socket descriptor. Socket type requires message to be sent to be atomic (all sent at once) and the message to send is too long....

Program 1016 Internet domain connectionoriented server using MSGOOB

Internet domain, connection-oriented SERVER - MSG PEEK include local_sock.h include < time.h> void signal_catcher(int) int orig_sock, Original socket in server new_sock New socket from connect socklen_t clntjen Length of client address struct sockaddrjn Internet addr client & server clnt_adr, serv_adr int len, i, Misc counters, etc. urg, mark Flag reception of OOB msg and to note its location in the stream. Catch when child terminates if (signal(SIGCHLD , signal_catcher) SIG_ERR)...

Process Resource Limits

As system resources are finite, every process is restrained by certain operating system-imposed limits. At the command line, the ulimit command (which is actually a built-in command found in the Bourne shell bin sh ) provides the user with a means to display and modify current system limits available to the shell and the processes that The C shell ( bin csh) provides a somewhat similar built-in command called limit. The command ulimit-Ha displays the hard limits for the system. The hard limits...

Thread Attributes

In a POSIX implementation, if we want to generate a thread that does not have the default attributes (obtained by setting the second parameter of the pthread_create call to NULL), an attribute object is used. To use an attribute object, it must first be initialized. This is accomplished using the library call pthread_attr_init (see Table 11.5). Table 11.5. The pthread_attr_init Library Function. int pthread_attr_init ( pthread_attr_t *attr) Success Failure Sets errno The pthread_attr_init...

The first call to semget provided the system limits have not been reached creates a set of three semaphores The

Create a second set of three semaphores. The call uses the same key value as the first but includes the specification IPC_EXCL. With the IPC_EXCL flag set and the previous successful creation of the semaphore set using the same key value, this invocation of semget will fail. The third call to semget creates a three-semaphore set used by specifying IPC_PRIVATE instead of using the ftok key value. The semaphore identifier generated for this set will be private to this process. When the program is...

D4 Viewing and Interpreting Profile Data

The profile data stored in the gmon.out file is analyzed and displayed using the gprof utility. If called with no options or command-line arguments, gprof assumes that the executable it is working with is a.out and that the profile data for this executable is in the file gmon.out. Also, unless directed otherwise, gprof generates and displays a fully annotated flat profile and a call graph using the collected data. Like most utilities, gprof supports an extensive set of options. We will examine...

J A reentrant function supports access by multiple threads and maintains the integrity of its data across consecutive

Iinux ar t usr lib libc.a grep'_r .o' pr-n-2-t 28 efgcvt_r.o 59 nscd_gethst_r.o 29 qefgcvt_r.o 60 getutent_r.o 30 hsearch_r.o 61 getutid_r.o 31 getspent_r.o 62 getutline_r.o As shown, reentrant functions have _r appended to their non-reentrant name. The object code library for POSIX thread functions must be linked in at compile time using the compiler switch -ipthread. Additionally, _posix_c_source should be defim if strict compliance to POSIX standards is required. For example, L J On...

A Unix Domain Datagram Socket Example

Our UNIX domain datagram socket example is somewhat similar in function to the stream socket example presented in Section 10.4. In this example, the server creates a datagram socket (SOCK_DGRAM) in the UNIX domain and binds it to an address (file name). The client also creates a datagram socket and binds it to an address (using a different file name, unique to each client process). The client and server use the sendto and recvfrom network calls for communication. The client generates 10...

Constant Protocol Family

PF_ATMPVC Access to raw ATM PVCs PF_AX25 Amateur radio AX.25 protocol PFJNET6 IPv6 Internet protocols PF_NETLINK Kernel user interface device PF_PACKET Low-level packet interface PFJJNIX, PF_LOCAL Local communication PF_X25 ITU-T X.25 ISO-8208 protocol x25(7) When a socket call is made in a program in some, but not all, development settings, the socket library must be specifically linked at compile time using the option -isocket. When creating a socket, insufficient memory available. Cannot...

IPC Using Socketpair

As a warmup, we begin our exploration of sockets with the generation of a pair of UNIX domain sockets. The socketpair call, shown in Table 10.1, is used to create the pair of sockets. The socketpair call takes four arguments. The first argument, d, is an integer value that specifies the domain. In general, the domains for socket-based calls should be specified as one of the protocol family-defined constants found in the header file . As in previous examples, the programmer does not directly...

Message Queue Class

As the functionality of and syntax for message queues is somewhat complex, they are ideal candidates for incorporation into a C++ class. A message queue class would define the relationships between message queue data and the functions (methods) that manipulate this data. A declaration of a simplified message queue class called Message_que is shown in Figure 6.10. Figure 6.10 Header file for a basic message queue class. A VERY simplified message queue class for use in a std UNIX environment. See...

Command Line Values

Part of the processing environment of every process are the values passed to the process in the function main. These values can be from the command line or may be passed to a child process from the parent via an exec system call. These values are stored in a ragged character array referenced by a character pointer array that, by tradition, is called argv. The number of elements in the argv array is stored as an integer value, which (again by tradition) is referenced by the identifier argc....

Linking Object Code

Code from library files, predefined or user-defined, is combined with object code from the source program at compile time on an as-needed basis. When programming in C C++, additional library files containing the object code for system calls and library functions not contained in the standard library can be specified at compile time. This is done by using the -I compiler option, followed by the library name without the lib prefix and the a extension. For example, the compilation command...