- 论坛徽章:
- 1
|
这是下面我的测试代码,开辟了另一个子进程,子进程又开辟另一个子进程。结束前,一共是3个进程,可是运行后,用另一个终端,用ps观察,只能看到2个a.out进程!这是怎么回事呢?我的环境是RH8。
- [yangwl:/home/users50/yangwl/test/undone/tfork]$ cat tfork.c
- #include <stdio.h>;
- #include <stdlib.h>;
- #include <sys/types.h>;
- #include <sys/wait.h>;
- #include <unistd.h>;
- int main(void) {
- pid_t pid;
- int status;
- pid = fork();
- if (pid == -1) {
- printf("fork error!\n");
- exit(1);
- }
- if (pid == 0) { // child.
- pid_t pid;
- pid = fork();
- if (pid == -1) {
- printf("fork error!\n");
- exit(1);
- }
- if (pid == 0) { // child's child.
- pid_t cc_pid,
- cc_ppid;
- cc_pid = getpid();
- cc_ppid = getppid();
- printf("child's child!\n");
- printf("%d:pid = %d\n",cc_pid,cc_pid);
- printf("%d:ppid = %d\n",cc_pid,cc_ppid);
- sleep(10);
- exit(0);
- }
- else { // fork twice, child exit.
- pid_t c_pid,
- c_ppid;
- c_pid = getpid();
- c_ppid = getppid();
- printf("child!\n");
- printf("%d:pid = %d\n",c_pid,c_pid);
- printf("%d:ppid = %d\n",c_pid,c_ppid);
- if ( wait(&status) != pid ) {
- printf("wait error!\n");
- exit(1);
- }
- printf("\n%d exit!\n",pid);
- printf("status: %d\n",status);
- sleep(10);
- exit(0);
- }
- }
- else { // father.
- pid_t f_pid;
- f_pid = getpid();
- printf("father!\n");
- printf("%d:pid = %d\n",f_pid,f_pid);
- if ( wait(&status) != pid ) {
- printf("wait error!\n");
- exit(1);
- }
- printf("\n%d exit!\n",pid);
- printf("status: %d\n",status);
- sleep(10);
- printf("\n%d father exit!\n", f_pid);
- exit(0);
- }
- }
- [yangwl:/home/users50/yangwl/test/undone/tfork]$ gcc tfork.c ; ./a.out
- father!
- 25449:pid = 25449
- child!
- 25450:pid = 25450
- 25450:ppid = 25449
- child's child!
- 25451:pid = 25451
- 25451:ppid = 25450
- 25451 exit!
- status: 0
- 25450 exit!
- status: 0
- 25449 father exit!
- [yangwl:/home/users50/yangwl/test/undone/tfork]$
复制代码 |
|