父子进程全局变量不共享(写时复制,读时共享)
文件父子共享,而且关闭时父子进程都要close(fd),我的理解是:虽然fork前的代码只执行一次,但是创建子进程时复制用户空间,此时文件的状态一同复制了
代码验证父子进程,文件共享:
int main(int argc,char *argv[])
{
int fd = open(argv[1],O_RDWR | O_CREAT | O_APPEND,0777);
//创建子进程
pid_t pid = fork();
if(pid<0) //fork失败的情况
{
perror("fork error");
}
else if(pid>0)//父进程
{
printf("father: pid==[%d],fpid==[%d]\n",getpid(),getppid());
if(fd<0)
{
perror("open error");
}
else
{
char *str="hello world";
write(fd,str,strlen(str));
close(fd);
}
int wstatus;
while(1)
{
pid_t wpid=waitpid(-1,&wstatus,WNOHANG);
if(wpid>0) //回收了一个子进程,返回子进程id
{
if(WIFEXITED(wstatus)) //正常退出
{
printf("child normal exit,status==[%d]\n" ,WEXITSTATUS(wstatus));
}
else if(WIFSIGNALED(wstatus)) //子进程被信号杀死
{
printf("child killed by signal ,signo == [%d]\n",WTERMSIG(wstatus));
}
}
else if(wpid==-1)
{
printf("no child is living ,wpid==[%d]\n",wpid);
break;
}
}
}
else if(pid==0)//子进程
{
sleep(3);
printf("child: pid==[%d,fpid==[%d]\n",getpid(),getppid());
char buf[138];
memset(buf,0,sizeof(buf));
lseek(fd,0,SEEK_SET);
read(fd,buf,sizeof(buf));
printf("%s\n",buf);
close(fd);
return 9;
}
close(fd);
return 0;
}