1 #include<stdio.h>
2 #include<unistd.h>
3 int main(void)
4 {
5 pid_t pid_0=-1;
6 pid_t pid_1=-1;
7 if((pid_0=fork())<0){
8 perror("fork error\n");
9 }
10 else if(pid_0==0){
11 if((pid_1=fork())<0){
12 perror("child fork error\n");
13 }else if(pid_1==0){
14 printf("hello i am gra son\n");
15 }else{
16 printf("i am son\n");
17 }
18 }else{
19 printf("i am parent\n");
20 }
21 return 0;
22 }
为啥会打印提示符
还有那个光标卡住了
我是不是创建了两个进程,加上父进程一共三个进程?
*
**[alex@localhost ~]$ ./a.out
i am parent
[alex@localhost ~]$ i am son
hello i am gra son
**
是三个进程父子孙,你这个理解是对的。
光标卡住是因为你的父进程最先退出了,就是你执行的这个程序进程,这样光标提示符自然就出来了,然后你的子进程和孙进程才退出,所以继续打印"i am son"和"iam gra son",而你的子进程和孙进程由于父进程已退出,就不属于当前的终端了,所以当结束后也退不回当前终端进程,所以光标卡在那里
你可以尝试加些sleep到不同的进程,感受一下不同退出顺序时的打印情况