When referring to process IDs in a C or C++ program, always use the pid_t typedef, which is defined in <sys/types.h>.A program can obtain the process ID of the process it’s running in with the getpid() system call, and it can obtain the process ID of its parent process with the getppid() system call. For instance, the program in Listing 3.1 prints its process ID and its parent’s process ID.
1: // Printing the process ID and parent process ID
2: #include <stdio.h>
3: #include <unistd.h>
4: int main ()
5: {
6: printf (“The process ID is %d\n”, (int) getpid ());
7: printf (“The parent process ID is %d\n”, (int) getppid ());
8: return 0;
9: }
When a program calls fork, a duplicate process, called the child process, is created. The parent process continues executing the program from the point that fork was called. The child process, too, executes the same program from the same place. So how do the two processes differ? First, the child process is a new process and therefore has a new process ID, distinct from its parent’s process ID.One way for a program to distinguish whether it’s in the parent process or the child process is to call getpid. However, the fork function provides different return values to the parent and child processes—one process “goes in” to the fork call, and two processes “come out,” with different return values.The return value in the parent process is the process ID of the child.The return value in the child process is zero. Because no process ever has a process ID of zero, this makes it easy for the program whether it is now running as the parent or the child process.
The following example show the fork to duplicate a program’s process. Note that the first block of the if statement is executed only in the parent process, while the else clause is executed in the child process.
1: // to create a process using fork()
2: #include <stdio.h>
3: #include <sys/types.h>
4: #include <unistd.h>
5: int main ()
6: {
7: pid_t child_pid;
8: printf (“the main program process ID is %d\n”, (int) getpid ());
9: child_pid = fork ();
10: if (child_pid != 0) {
11: printf (“this is the parent process, with id %d\n”, (int) getpid ());
12: printf (“the child’s process ID is %d\n”, (int) child_pid);
13: }
14: else
15: printf (“this is the child process, with id %d\n”, (int) getpid ());
16: return 0;
17: }
Observation:
The program can be compiled using gcc compiler
$: gcc –o <linkname> <filename.c>
$: ./linkname
Comments
Post a Comment