Associated with each process is a unique positive integer identification number called a process ID ( PID ). As process IDs are allocated sequentially, when a system is booted , a few system processes, which are initiated only once, will always be assigned the same process ID. For example, on a Linux system process 0 (historically known as swapper ) is created from scratch during the startup process. This process initializes kernel data structures and creates another process called init . The init process, PID 1, creates a number of special kernel threads [1] to handle system management. These special threads typically have low PID numbers .
[1] Threads are covered in detail in Chapter 11. Simplistically, a thread is the flow of control through a process. Operating systems vary on how they actually implement a thread. In Linux a thread is a special type of process that shares address space and resources with its parent process. A kernel thread, which runs only in kernel mode, is responsible for a single kernel function, such as flushing buffers to disk or reclaiming returned memory.
Other processes are assigned free PIDs of increasing value until the maximum system value for a PID is reached. The maximum value for PIDs can be found as the defined constant PID_MAX in the header file (on older systems check ). When the highest PID has been assigned, the system wraps around and begins to reuse lower PID numbers not currently in use.
The system call getpid can be used to obtain the PID (Table 2.1). The getpid system call does not accept an argument. If it is successful, it will return the PID number. If the calling process does not have the proper access permissions, the getpid call will fail, returning a value of 1 and setting errno to EPERM (1).
Table 2.1. Summary of the getpid System Call.
Include File(s) |
|
Manual Section |
2 |
|
Summary |
pid_t getpid( void ); |
|||
Return |
Success |
Failure |
Sets errno |
|
The process ID |
1 |
Yes |
A process can determine its own PID by use of the getpid system call, as shown in the following code segment:
cout << "My process ID is " << getpid() << endl;
The getpid system call is of limited use. Usually the PID will be different on each invocation of the program. The manual page entry for getpid notes that the most common use for this system call is the generation of unique temporary file names . However, for everyday use, the library function mkstemp is much better suited for the production of unique temporary file names.
Programs and Processes
Processing Environment
Using Processes
Primitive Communications
Pipes
Message Queues
Semaphores
Shared Memory
Remote Procedure Calls
Sockets
Threads
Appendix A. Using Linux Manual Pages
Appendix B. UNIX Error Messages
Appendix C. RPC Syntax Diagrams
Appendix D. Profiling Programs