初学linux 遇到fork 有些不解,求指教
发表于 : 2013-11-22 15:36
不知道怎么说,先上个程序,学过的人应该都熟悉,好像每本linux书都有类似的程序:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t child1,child2,child;
/*创建两个子进程*/
child1 = fork();
child2 = fork();
/*子进程1的出错处理*/
if( child1 == -1 ){
perror("child1 fork");
exit(1);
}
/*在子进程1中调用execlp函数*/
else if( child1 == 0 ){
printf("In child1: execute 'ls -l'\n");
if(execlp("ls","ls","-l",NULL)<0)
perror("child1 execlp");
}
/*子进程2的出错处理*/
if( child2 == -1 ){
perror("child2 fork");
exit(1);
}
/*在子进程2中使其暂停5s*/
else if( child2 == 0 ){
printf("In child2: sleep for 5 seconds and then exit\n");
sleep(5);
exit(0);
}
/*在父进程中等待子进程2的退出*/
else{
printf("In father process:\n");
do{
child = waitpid( child2, NULL, WNOHANG );
if( child ==0 ){
printf("The child2 process has not exited!\n");
sleep(1);
}
}while( child == 0 );
if( child == child2 )
printf("Get child2\n");
else
printf("Error occured!\n");
}
}
书上有一段话是这样说的:
新进程和原有进程的可执行程序是同一个程序;上下文和数据,绝大部分就是原进程(父进程)的拷贝,但它们是两个相互独立的进程!此时程序寄存器pc,在父、子进程的上下文中都声称,这个进程目前执行到fork调用即将返回(此时子进程不占有CPU,子进程的pc不是真正保存在寄存器中,而是作为进程上下文保存在进程表中的对应表项内)。
我的理解是子进程会完全复制父进程的程序,同时复制了父进程程序寄存器。那么问题来了,父进程一共创建了两个子进程:child1和child2,且child1先创建,那么对应child1子进程的程序寄存器PC就是指向“child2 = fork();“这条语句。 那么按照这么理解,child1进程在运行的时候就会再次运行“child2 = fork()”,也就是在子进程中又创建了一个子进程。我知道我的理解肯定是错的,求指教。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t child1,child2,child;
/*创建两个子进程*/
child1 = fork();
child2 = fork();
/*子进程1的出错处理*/
if( child1 == -1 ){
perror("child1 fork");
exit(1);
}
/*在子进程1中调用execlp函数*/
else if( child1 == 0 ){
printf("In child1: execute 'ls -l'\n");
if(execlp("ls","ls","-l",NULL)<0)
perror("child1 execlp");
}
/*子进程2的出错处理*/
if( child2 == -1 ){
perror("child2 fork");
exit(1);
}
/*在子进程2中使其暂停5s*/
else if( child2 == 0 ){
printf("In child2: sleep for 5 seconds and then exit\n");
sleep(5);
exit(0);
}
/*在父进程中等待子进程2的退出*/
else{
printf("In father process:\n");
do{
child = waitpid( child2, NULL, WNOHANG );
if( child ==0 ){
printf("The child2 process has not exited!\n");
sleep(1);
}
}while( child == 0 );
if( child == child2 )
printf("Get child2\n");
else
printf("Error occured!\n");
}
}
书上有一段话是这样说的:
新进程和原有进程的可执行程序是同一个程序;上下文和数据,绝大部分就是原进程(父进程)的拷贝,但它们是两个相互独立的进程!此时程序寄存器pc,在父、子进程的上下文中都声称,这个进程目前执行到fork调用即将返回(此时子进程不占有CPU,子进程的pc不是真正保存在寄存器中,而是作为进程上下文保存在进程表中的对应表项内)。
我的理解是子进程会完全复制父进程的程序,同时复制了父进程程序寄存器。那么问题来了,父进程一共创建了两个子进程:child1和child2,且child1先创建,那么对应child1子进程的程序寄存器PC就是指向“child2 = fork();“这条语句。 那么按照这么理解,child1进程在运行的时候就会再次运行“child2 = fork()”,也就是在子进程中又创建了一个子进程。我知道我的理解肯定是错的,求指教。