#include <stdio.h>
#include <stdlib.h>
int main(void)
{
pid_t pid; //pid_t是typedef定义的类型,表示进程的id,在sys/types.h中定义:typedef short pid_t;
int static count = 5; //static可以保存修改之后的值
printf("process id = %d,old count = %d,address count = 0x%x\n",getpid(),count,&count);
pid = fork();
if(pid < 0) //返回其他值说明fork失败了
printf("error in fork!\n");
else if(pid == 0) //返回0给子进程
{
printf("i am the child process,my process id is %d,pid is %d\n",getpid(),pid);
sleep(15);
count++;
count++;
printf("child process id = %d,old count = %d,address count = 0x%x\n",getpid(),count,&count);
}
else //返回一个大于0的值给父进程,就是子进程的编号
{
printf("i am the parent process,my process id is %d,pid is %d\n",getpid(),pid);
sleep(5);
count++;
printf("parent process id = %d,old count = %d,address count = 0x%x\n",getpid(),count,&count);
}
return 0;
}
[root@localhost labs]# ./lab17
process id = 11498,old count = 5,address count = 0x53c13a28
i am the parent process,my process id is 11498,pid is 11499
i am the child process,my process id is 11499,pid is 0
parent process id = 11498,old count = 6,address count = 0x53c13a28
[root@localhost labs]#
[root@localhost labs]#
[root@localhost labs]# child process id = 11499,old count = 7,address count = 0x53c13a28
#include <stdlib.h>
int main(void)
{
pid_t pid; //pid_t是typedef定义的类型,表示进程的id,在sys/types.h中定义:typedef short pid_t;
int static count = 5; //static可以保存修改之后的值
printf("process id = %d,old count = %d,address count = 0x%x\n",getpid(),count,&count);
pid = fork();
if(pid < 0) //返回其他值说明fork失败了
printf("error in fork!\n");
else if(pid == 0) //返回0给子进程
{
printf("i am the child process,my process id is %d,pid is %d\n",getpid(),pid);
sleep(15);
count++;
count++;
printf("child process id = %d,old count = %d,address count = 0x%x\n",getpid(),count,&count);
}
else //返回一个大于0的值给父进程,就是子进程的编号
{
printf("i am the parent process,my process id is %d,pid is %d\n",getpid(),pid);
sleep(5);
count++;
printf("parent process id = %d,old count = %d,address count = 0x%x\n",getpid(),count,&count);
}
return 0;
}
[root@localhost labs]# ./lab17
process id = 11498,old count = 5,address count = 0x53c13a28
i am the parent process,my process id is 11498,pid is 11499
i am the child process,my process id is 11499,pid is 0
parent process id = 11498,old count = 6,address count = 0x53c13a28
[root@localhost labs]#
[root@localhost labs]#
[root@localhost labs]# child process id = 11499,old count = 7,address count = 0x53c13a28
//变量地址相同为虚拟地址,实际的物理地址不同
在语句fpid=fork()之前,只有一个进程在执行这段代码,但在这条语句之后,就变成两个进程在执行了,这两个进程的几乎完全相同,将要执行的下一条语句都是if(fpid<0)……
为什么两个进程的fpid不同呢,这与fork函数的特性有关。fork调用的一个奇妙之处就是它仅仅被调用一次,却能够返回两次,它可能有三种不同的返回值:
1)在父进程中,fork返回新创建子进程的进程ID;
2)在子进程中,fork返回0;
3)如果出现错误,fork返回一个负值;
在fork函数执行完毕后,如果创建新进程成功,则出现两个进程,一个是子进程,一个是父进程。在子进程中,fork函数返回0,在父进程中,fork返回新创建子进程的进程ID。我们可以通过fork返回的值来判断当前进程是子进程还是父进程。
引用一位网友的话来解释 fpid 的值为什么在父子进程中不同。 “ 其实就相当于链表,进程形成了链表,父进程的 fpid(p 意味 point) 指向子进程的进程 id, 因为子进程没有子进程,所以其 fpid 为 0.