qingsong@db2a:~/linuxc$ cat pstest.c
qingsong@db2a:~/linuxc$ cat pstest.c /*filename: pstest.c*/ #include <stdlib.h> #include <stdio.h> int main() { system("ps -al"); printf("ps command finished\n"); return 0; } qingsong@db2a:~/linuxc$ gcc -o pstest pstest.c && ./pstest F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 T 1000 2876 58189 0 80 0 - 1054 signal pts/0 00:00:00 1.9.1 0 S 1000 41102 58189 0 90 10 - 1053 wait pts/0 00:00:00 pstest <--原进程,PID为41102 0 S 1000 41103 41102 0 90 10 - 1116 wait pts/0 00:00:00 sh <--原进程调用system启动的shell, PPID为41102 0 R 1000 41104 41103 0 90 10 - 2502 - pts/0 00:00:00 ps <--原进程调用system启动的shell里发起的命令,PPID为41103 ps command finished qingsong@db2a:~/linuxc$NAME fork - create a child process SYNOPSIS #include <unistd.h> pid_t fork(void); DESCRIPTION fork() creates a new process by duplicating the calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent, except for the following points: * The child has its own unique process ID, and this PID does not match the ID of any existing process group (setpgid(2)). * The child's parent process ID is the same as the parent's process ID. * The child does not inherit its parent's memory locks (mlock(2), mlockall(2)). .... 下面的程序,使用fork产生了子进程,父进程和子进程各自做不同的事情: qingsong@db2a:~/linuxc$ cat forktest.c /* filename forktest.c */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main() { pid_t pid; char * msg="This is a fork test program"; pid=fork(); if (pid < 0) printf("Fork error\n"); else if (pid == 0) { sleep(5); printf("This is child begin\n"); printf("%s\n",msg); printf("This is child end\n"); } else { printf("This is parent begin\n"); printf("%s\n",msg); system("ps -al"); printf("This is parent end\n"); } return 0; } qingsong@db2a:~/linuxc$ gcc -o forktest forktest.c qingsong@db2a:~/linuxc$ ./forktest This is parent begin This is a fork test program F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 T 1000 2876 58189 0 80 0 - 1054 signal pts/0 00:00:00 1.9.1 0 S 1000 39703 58189 0 90 10 - 1054 wait pts/0 00:00:00 forktest <<--最原始的进程 1 S 1000 39704 39703 0 90 10 - 1053 hrtime pts/0 00:00:00 forktest <<--由原进程fork出来的新进程 0 S 1000 39705 39703 0 90 10 - 1116 wait pts/0 00:00:00 sh <<--由原进程调用system函数产生的shell 0 R 1000 39706 39705 0 90 10 - 2502 - pts/0 00:00:00 ps <<--由原进程调用system函数产生的shell里执行的命令 This is parent end qingsong@db2a:~/linuxc$ This is child begin This is a fork test program This is child end qingsong@db2a:~/linuxc$ 1. 子进程是由父进程复制过来的,所以,都能打印出消息msg 2. ps -al的输出中,有两个forktest,其中PID为的 39704 是子进程,可以看到它的PPID为 39703 3. 子进程要比父进程慢5秒,如果在父进程结束后的5s之内,在另外一个shell里查看ps -al的输出,如下,能够看到由于父进程已经结束,子进程的父进程变为1. qingsong@db2a:~$ ps -al F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 T 1000 2876 58189 0 80 0 - 1054 signal pts/0 00:00:00 1.9.1 1 S 1000 39704 1 0 90 10 - 1053 hrtime pts/0 00:00:00 forktest 0 R 1000 39712 39666 0 80 0 - 2502 - pts/2 00:00:00 ps