

















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















































1 The Linux operating system
In March 1991 Linus Benedict Torvalds bought the multitasking system Minix for his AT 386. He used it to develop his own multitasking system which he called Linux. In September 1991 he released the first prototype by e-mail to some other Minix users on the internet, thus beginning the Linux project. Many programmers from that point on have supported Linux. They have added device drivers, developed applications, and aimed for POSIX compliance. Today Linux is very powerful, but what is best is that it's free. Work is beeing done to port Linux to other platforms.
2 The Linux kernel
The base of Linux is the kernel. You could replace each and every library, but as long as the Linux kernel remained, it would still be Linux. The kernel contains device drivers, memory management, process management and communication management. The kernel hacker gurus follow POSIX guidelines which sometimes makes programming easier and sometimes harder. If your program behaves differently on a new Linux kernel release, chances are that a new POSIX guideline has been implemented. For programming information about the Linux kernel, read the Linux Kernel Hacker's Guide.
3 The Linux libc package
libc: ISO 8859.1, <linux/param.h>, YP functions, crypt functions, some basic shadow routines (by default not included), ... old routines for compatibility in libcompat (by default not activated), english, french or german error messages, bsd 4.4lite compatible screen handling routines in libcurses, bsd compatible routines in libbsd, screen handling routines in libtermcap, database management routines in libdbm, mathematic routines in libm, entry to execute programs in crt0.o ???, byte sex information in libieee ??? (could someone give some infos instead of laughing ?), user space profiling in libgmon. I wish someone of the Linux libc developers would write this chapter. All i can say now that there is going to be a change from the a.out executable format to the elf (executable and linkable format) which also means a change in building shared libraries. Currently both formats (a.out and elf) are supported.
Most parts of the Linux libc package are under the Library GNU Public License, though some are under a special exception copyright like crt0.o. For commercial binary distributions this means a restriction that forbids statically linked executables. Dynamically linked executables are again a special exception and Richard Stallman of the FSF said:
[...] But it seems to me that we should unambiguously permit distribution of a dynamically linked executable without accompanying libraries, provided that the object files that make up the executable are themselves unrestricted according to section 5 [...] So I'll make the decision now to permit this. Actually updating the LGPL will have to wait for when I have time to make and check a new version.
4 System calls
A system call is usually a request to the operating system (kernel) to do a hardware/system- specific or privileged operation. As of Linux-1.2, 140 system calls have been defined. System calls like close() are implemented in the Linux libc. This implementation often involves calling a macro which eventually calls syscall(). Parameters passed to syscall() are the number of the
system call followed by the needed arguments. The actual system call numbers can be found in
<linux/unistd.h> while <sys/syscall.h> gets updated with a new libc. If new calls appear that don't have a stub in libc yet, you can use syscall(). As an example, you can close a file using syscall() like this (not advised):
#include <syscall.h>
extern int syscall(int, ...);
int my_close(int filedescriptor)
{
return syscall(SYS_close, filedescriptor);
}
On the i386 architecture, system calls are limited to 5 arguments besides the system call number because of the number of hardware registers. If you use Linux on another architecture you can check <asm/unistd.h> for the _syscall macros to see how many arguments your hardware supports or how many the developers chose to support. These _syscall macros can be used instead of syscall(), but this is not recommended since such a macro expands to a full function which might already exist in a library. Therefore, only kernel hackers should play with the _syscall macros. To demonstrate, here is the close() example using a _syscall macro.
#include <linux/unistd.h>
_syscall1(int, close, int, filedescriptor);
The _syscall1 macro expands revealing the close() function. Thus we have close() twice-once in libc and once in our program. The return value of syscall() or a _syscall macro is -1 if the system call failed and 0 or greater on success. Take a look at the global variable errno to see what happened if a system call failed.
The following system calls that are available on BSD and SYS V are not available on Linux: audit(), auditon(), auditsvc(), fchroot(), getauid(), getdents(), getmsg(), mincore(), poll(), putmsg (), setaudit(), setauid().
5 The ``swiss army knife'' ioctl
ioctl stands for input/output control and is used to manipulate a character device via a filedescriptor. The format of ioctl is ioctl(unsigned int fd, unsigned int request, unsigned long argument). The return value is -1 if an error occured and a value greater or equal than 0 if the request succeeded just like other system calls. The kernel distinguishes special and regular files. Special
files are mainly found in /dev and /proc. They differ from regular files in that way that they hide
Although most of us use pipes quite religiously in shell script programming, we often do so
without giving a second thought to what transpires at the kernel level.
When a process creates a pipe, the kernel sets up two file descriptors for use by the pipe. One descriptor is used to allow a path of input into the pipe (write), while the other is used to obtain data from the pipe (read). At this point, the pipe is of little practical use, as the creating process can only use the pipe to communicate with itself. Consider this representation of a process and the kernel after a pipe has been created:
From the above diagram, it is easy to see how the descriptors are connected together. If the
process sends data through the pipe (fd0), it has the ability to obtain (read) that information from fd1. However, there is a much larger objective of the simplistic sketch above. While a pipe initially connects a process to itself, data traveling through the pipe moves through the kernel. Under Linux, in particular, pipes are actually represented internally with a valid inode. Of course, this inode resides within the kernel itself, and not within the bounds of any physical file system. This particular point will open up some pretty handy I/O doors for us, as we will see a bit later on.
At this point, the pipe is fairly useless. After all, why go to the trouble of creating a pipe if we are only going to talk to ourself? At this point, the creating process typically forks a child process. Since a child process will inherit any open file descriptors from the parent, we now have the basis for multiprocess communication (between parent and child). Consider this updated version of our simple sketch:
Above, we see that both processes now have access to the file descriptors which constitute the
pipeline. It is at this stage, that a critical decision must be made. In which direction do we desire data to travel? Does the child process send information to the parent, or vice-versa? The two processes mutually agree on this issue, and proceed to ``close'' the end of the pipe that they are not concerned with. For discussion purposes, let's say the child performs some processing, and
sends information back through the pipe to the parent. Our newly revised sketch would appear as
such:
Construction of the pipeline is now complete! The only thing left to do is make use of the pipe. To access a pipe directly, the same system calls that are used for low-level file I/O can be used (recall that pipes are actually represented internally as a valid inode).
To send data to the pipe, we use the write() system call, and to retrieve data from the pipe, we use the read() system call. Remember, low-level file I/O system calls work with file descriptors! However, keep in mind that certain system calls, such as lseek(), do not work with descriptors to pipes.
6.2.2 Creating Pipes in C
Creating ``pipelines'' with the C programming language can be a bit more involved than our simple shell example. To create a simple pipe with C, we make use of the pipe() system call. It takes a single argument, which is an array of two integers, and if successful, the array will
contain two new file descriptors to be used for the pipeline. After creating a pipe, the process typically spawns a new process (remember the child inherits open file descriptors).
SYSTEM CALL: pipe();
PROTOTYPE: int pipe( int fd[2] );
RETURNS: 0 on success
-1 on error: errno = EMFILE (no free descriptors)
EMFILE (system file table is full)
EFAULT (fd array is not valid)
NOTES: fd[0] is set up for reading, fd[1] is set up for writing
main() { int fd[2]; pid_t childpid;
pipe(fd);
if((childpid = fork()) == -1) { perror("fork"); exit(1); }
if(childpid == 0) { /* Child process closes up input side of pipe / close(fd[0]); } else { / Parent process closes up output side of pipe */ close(fd[1]); } . . } As mentioned previously, once the pipeline has been established, the file descriptors may be treated like descriptors to normal files.
#include <stdio.h> #include <unistd.h> #include <sys/types.h>
int main(void) { int fd[2], nbytes; pid_t childpid; char string[] = "Hello, world!\n"; char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1) { perror("fork"); exit(1); }
if(childpid == 0)
/* Child process closes up input side of pipe */ close(fd[0]);
/* Send "string" through the output side of pipe / write(fd[1], string, (strlen(string)+1)); exit(0); } else { / Parent process closes up output side of pipe */ close(fd[1]);
/* Read in a string from the pipe */ nbytes = read(fd[0], readbuffer, sizeof(readbuffer)); printf("Received string: %s", readbuffer); }
return(0); } Often, the descriptors in the child are duplicated onto standard input or output. The child can then exec() another program, which inherits the standard streams. Let's look at the dup() system call:
SYSTEM CALL: dup();
PROTOTYPE: int dup( int oldfd ); RETURNS: new descriptor on success -1 on error: errno = EBADF (oldfd is not a valid descriptor) EBADF (newfd is out of range) EMFILE (too many descriptors for the process)
NOTES: the old descriptor is not closed! Both may be used interchangeably
Although the old descriptor and the newly created descriptor can be used interchangeably, we will typically close one of the standard streams first. The dup() system call uses the lowest- numbered, unused descriptor for the new one.
Consider: . . childpid = fork();
if(childpid == 0) { /* Close up standard input of the child */ close(0);
if(childpid == 0) { /* Close stdin, duplicate the input side of pipe to stdin */ dup2(0, fd[0]); execlp("sort", "sort", NULL); . . }
6.2.3 Pipes the Easy Way!
If all of the above ramblings seem like a very round-about way of creating and utilizing pipes, there is an alternative.
LIBRARY FUNCTION: popen();
PROTOTYPE: FILE *popen ( char *command, char *type); RETURNS: new file stream on success NULL on unsuccessful fork() or pipe() call
NOTES: creates a pipe, and performs fork/exec operations using "command"
This standard library function creates a half-duplex pipeline by calling pipe() internally. It then
forks a child process, execs the Bourne shell, and executes the "command" argument within the shell. Direction of data flow is determined by the second argument, "type". It can be "r" or "w", for "read" or "write". It cannot be both! Under Linux, the pipe will be opened up in the mode specified by the first character of the "type" argument. So, if you try to pass "rw", it will only open it up in "read" mode.
While this library function performs quite a bit of the dirty work for you, there is a substantial tradeoff. You lose the fine control you once had by using the pipe() system call, and handling the fork/exec yourself. However, since the Bourne shell is used directly, shell metacharacter expansion (including wildcards) is permissible within the "command" argument.
Pipes which are created with popen() must be closed with pclose(). By now, you have probably
realized that popen/pclose share a striking resemblance to the standard file stream I/O functions fopen() and fclose().
LIBRARY FUNCTION: pclose();
PROTOTYPE: int pclose( FILE *stream ); RETURNS: exit status of wait4() call -1 if "stream" is not valid, or if wait4() fails
NOTES: waits on the pipe process to terminate, then closes the stream.
The pclose() function performs a wait4() on the process forked by popen(). When it returns, it destroys the pipe and the file stream. Once again, it is synonymous with the fclose() function for normal stream-based file I/O.
Consider this example, which opens up a pipe to the sort command, and proceeds to sort an array of strings:
#include <stdio.h>
#define MAXSTRS 5
int main(void) {
int cntr; FILE *pipe_fp; char *strings[MAXSTRS] = { "echo", "bravo", "alpha", "charlie", "delta"};
/* Create one way pipe line with call to popen() */ if (( pipe_fp = popen("sort", "w")) == NULL) { perror("popen"); exit(1); }
/* Processing loop */ for(cntr=0; cntr<MAXSTRS; cntr++) { fputs(strings[cntr], pipe_fp); fputc('\n', pipe_fp); }
/* Close the pipe */ pclose(pipe_fp);
return(0); } Since popen() uses the shell to do its bidding, all shell expansion characters and metacharacters are available for use! In addition, more advanced techniques such as redirection, and even output piping, can be utilized with popen(). Consider the following sample calls:
popen("ls ~scottb", "r");
popen("sort > /tmp/foo", "w");
popen("sort | uniq | more", "w");
As another example of popen(), consider this small program, which opens up two pipes (one to the ls command, the other to sort):
/* Open up input file */ if (( infile = fopen(argv[2], "rt")) == NULL) { perror("fopen"); exit(1); }
/* Create one way pipe line with call to popen() */ if (( pipe_fp = popen(argv[1], "w")) == NULL) { perror("popen"); exit(1); }
/* Processing loop */ do { fgets(readbuf, 80, infile); if(feof(infile)) break;
fputs(readbuf, pipe_fp); } while(!feof(infile));
fclose(infile); pclose(pipe_fp);
return(0); } Try this program out, with the following invocations: popen3 sort popen3.c popen3 cat popen3.c popen3 more popen3.c popen3 cat popen3.c | grep main 6.2.4 Atomic Operations with Pipes
In order for an operation to be considered ``atomic'', it must not be interrupted for any reason at all. The entire operation occurs at once. The POSIX standard dictates in /usr/include/ posix1_lim.h that the maximum buffer size for an atomic operation on a pipe is:
#define _POSIX_PIPE_BUF 512
Up to 512 bytes can be written or retrieved from a pipe atomically. Anything that crosses this threshold will be split, and not atomic. Under Linux, however, the atomic operational limit is defined in ``linux/limits.h'' as:
#define PIPE_BUF 4096
As you can see, Linux accommodates the minimum number of bytes required by POSIX, quite considerably I might add. The atomicity of a pipe operation becomes important when more than one process is involved (FIFOS). For example, if the number of bytes written to a pipe exceeds the atomic limit for a single operation, and multiple processes are writing to the pipe, the data
will be interleaved'' orchunked''. In other words, one process may insert data into the pipeline
between the writes of another.
6.2.5 Notes on half-duplex pipes:
Two way pipes can be created by opening up two pipes, and properly reassigning the file descriptors in the child process.
The pipe() call must be made BEFORE a call to fork(), or the descriptors will not be inherited by the child! (same for popen()).
With half-duplex pipes, any connected processes must share a related ancestry. Since the pipe resides within the confines of the kernel, any process that is not in the ancestry for the creator of the pipe has no way of addressing it. This is not the case with named pipes (FIFOS).
6.3 Named Pipes (FIFOs - First In First Out)
6.3.1 Basic Concepts
A named pipe works much like a regular pipe, but does have some noticeable differences. Named pipes exist as a device special file in the file system. Processes of different ancestry can share data through a named pipe. When all I/O is done by sharing processes, the named pipe remains in the file system for later use.
6.3.2 Creating a FIFO
There are several ways of creating a named pipe. The first two can be done directly from the shell.
mknod MYFIFO p
mkfifo a=rw MYFIFO
The above two commands perform identical operations, with one exception. The mkfifo command provides a hook for altering the permissions on the FIFO file directly after creation. With mknod, a quick call to the chmod command will be necessary.
FIFO files can be quickly identified in a physical file system by the ``p'' indicator seen here in a long directory listing:
$ ls -l MYFIFO
prw-r--r-- 1 root root 0 Dec 14 22:15 MYFIFO|
Also notice the vertical bar (``pipe sign'') located directly after the file name. Another great reason to run Linux, eh?
To create a FIFO in C, we can make use of the mknod() system call:
LIBRARY FUNCTION: mknod();
FILE *fp; char readbuf[80];
/* Create the FIFO if it does not exist */ umask(0); mknod(FIFO_FILE, S_IFIFO|0666, 0);
while(1) { fp = fopen(FIFO_FILE, "r"); fgets(readbuf, 80, fp); printf("Received string: %s\n", readbuf); fclose(fp); }
return(0); } Since a FIFO blocks by default, run the server in the background after you compile it:
$ fifoserver&
We will discuss a FIFO's blocking action in a moment. First, consider the following simple client frontend to our server:
#include <stdio.h> #include <stdlib.h>
#define FIFO_FILE "MYFIFO"
int main(int argc, char *argv[]) { FILE *fp;
if ( argc != 2 ) { printf("USAGE: fifoclient [string]\n"); exit(1); }
if((fp = fopen(FIFO_FILE, "w")) == NULL) { perror("fopen"); exit(1); }
fputs(argv[1], fp);
fclose(fp); return(0); }
6.3.4 Blocking Actions on a FIFO
Normally, blocking occurs on a FIFO. In other words, if the FIFO is opened for reading, the process will "block" until some other process opens it for writing. This action works vice-versa as well. If this behavior is undesirable, the O_NONBLOCK flag can be used in an open() call to disable the default blocking action.
In the case with our simple server, we just shoved it into the background, and let it do its blocking there. The alternative would be to jump to another virtual console and run the client end, switching back and forth to see the resulting action.
6.3.5 The Infamous SIGPIPE Signal
On a last note, pipes must have a reader and a writer. If a process tries to write to a pipe that has no reader, it will be sent the SIGPIPE signal from the kernel. This is imperative when more than two processes are involved in a pipeline.
6.4 System V IPC
6.4.1 Fundamental Concepts
With System V, AT&T introduced three new forms of IPC facilities (message queues, semaphores, and shared memory). While the POSIX committee has not yet completed its standardization of these facilities, most implementations do support these. In addition, Berkeley (BSD) uses sockets as its primary form of IPC, rather than the System V elements. Linux has the ability to use both forms of IPC (BSD and System V), although we will not discuss sockets until a later chapter
IPC Identifiers
Each IPC object has a unique IPC identifier associated with it. When we say ``IPC object'', we are speaking of a single message queue, semaphore set, or shared memory segment. This identifier is used within the kernel to uniquely identify an IPC object. For example, to access a particular shared memory segment, the only item you need is the unique ID value which has been assigned to that segment.
The uniqueness of an identifier is relevant to the type of object in question. To illustrate this, assume a numeric identifier of ``12345''. While there can never be two message queues with this same identifier, there exists the distinct possibility of a message queue and, say, a shared memory segment, which have the same numeric identifier.
IPC Keys
To obtain a unique ID, a key must be used. The key must be mutually agreed upon by both client and server processes. This represents the first step in constructing a client/server framework for an application.
When you use a telephone to call someone, you must know their number. In addition, the phone company must know how to relay your outgoing call to its final destination. Once the other party responds by answering the telephone call, the connection is made.
ipcs -q: Show only message queues
ipcs -s: Show only semaphores ipcs -m: Show only shared memory ipcs --help: Additional arguments
By default, all three categories of objects are shown. Consider the following sample output of ipcs:
------ Shared Memory Segments -------- shmid owner perms bytes nattch status
------ Semaphore Arrays -------- semid owner perms nsems status
------ Message Queues -------- msqid owner perms used-bytes messages 0 root 660 5 1
Here we see a single message queue which has an identifier of ``0''. It is owned by the user root, and has octal permissions of 660, or -rw-rw--. There is one message in the queue, and that message has a total size of 5 bytes.
The ipcs command is a very powerful tool which provides a peek into the kernel's storage mechanisms for IPC objects. Learn it, use it, revere it.
The ipcrm Command
The ipcrm command can be used to remove an IPC object from the kernel. While IPC objects can be removed via system calls in user code (we'll see how in a moment), the need often arises, especially under development environments, to remove IPC objects manually. Its usage is simple:
ipcrm <msg | sem | shm>
Simply specify whether the object to be deleted is a message queue (msg), a semaphore set (sem), or a shared memory segment (shm). The IPC ID can be obtained by the ipcs command. You have to specify the type of object, since identifiers are unique among the same type (recall our discussion of this earlier).
6.4.2 Message Queues
Basic Concepts
Message queues can be best described as an internal linked list within the kernel's addressing space. Messages can be sent to the queue in order and retrieved from the queue in several different ways. Each message queue (of course) is uniquely identified by an IPC identifier
Internal and User Data Structures
The key to fully understanding such complex topics as System V IPC is to become intimately familiar with the various internal data structures that reside within the confines of the kernel itself. Direct access to some of these structures is necessary for even the most primitive operations, while others reside at a much lower level.
Message buffer
The first structure we'll visit is the msgbuf structure. This particular data structure can be thought of as a template for message data. While it is up to the programmer to define structures of this
type, it is imperative that you understand that there is actually a structure of type msgbuf. It is declared in linux/msg.h as follows:
/* message buffer for msgsnd and msgrcv calls / struct msgbuf { long mtype; / type of message / char mtext[1]; / message text */ };
There are two members in the msgbuf structure:
mtype
The message type, represented in a positive number. This must be a positive number!
mtext
The message data itself.
The ability to assign a given message a type, essentially gives you the capability to multiplex messages on a single queue. For instance, client processes could be assigned a magic number, which could be used as the message type for messages sent from a server process. The server itself could use some other number, which clients could use to send messages to it. In another scenario, an application could mark error messages as having a message type of 1, request messages could be type 2, etc. The possibilities are endless.
On another note, do not be misled by the almost too-descriptive name assigned to the message data element (mtext). This field is not restricted to holding only arrays of characters, but any data, in any form. The field itself is actually completely arbitrary, since this structure gets redefined by the application programmer. Consider this redefinition:
struct my_msgbuf { long mtype; /* Message type / long request_id; / Request identifier / struct client info; / Client information structure */ };