Today, a new question about "fork() function" is interesting. This process-level function can return values twices, which makes me wonder : HOW DID IT MAKE IT?!!! Following is the test code from internet, and should be a good example.
执行结果:
[root@localhost c]# ./a.out
i am the child process, my process id is 4286
i am the parent process, my process id is 4285
从这个程序执行结果可以看出,fork() 在执行的时候,是返回了两次。当fork执行时,产生子进程,子进程和父进程共享代码段,并发执行。但是二者并不共享临时数据堆栈,而是子进程保存父进程的数据堆栈副本,这点值得注意!!
- #include <unistd.h>
- #include <sys/types.h>
- void main()
- {
- pid_t pid;
- pid = fork();
- if (pid < 0)
- printf("error in fork");
- else if (pid == 0)
- printf(" i am the child process, my process id is %d\n", getid())
- else
- printf(" i am the parent process, my process id %d\n", getid());
- }
执行结果:
[root@localhost c]# ./a.out
i am the child process, my process id is 4286
i am the parent process, my process id is 4285
从这个程序执行结果可以看出,fork() 在执行的时候,是返回了两次。当fork执行时,产生子进程,子进程和父进程共享代码段,并发执行。但是二者并不共享临时数据堆栈,而是子进程保存父进程的数据堆栈副本,这点值得注意!!