fork()函数浅析

来源:互联网 发布:知乎长期光头 编辑:程序博客网 时间:2024/06/05 13:28

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
int main()
{
 int i=1;
 pid_t pid;
 int  fd;
 int  status;
 char *ch1="asd";
 char *ch2="bnm";
 char *ch3="opl";
 fd=open("text.txt",O_RDWR|O_CREAT,0777);
 if(fd==-1)
 {
  perror("open");
  exit(1);
 }
 if(write(fd,ch1,3)==-1)
 {
  perror("write");
  exit(1);
 }
 pid=fork();
 if(pid==-1)
 {
  perror("fork");
  exit(1);
 }
 else if(pid==0)
 {
  i++;
  printf("in the child process:%d\n",i);
  if(write(fd,"in the child",strlen("in the child"))==-1)
  {
   perror("write");
   exit(1);
  }
 }
 else
 {
  printf("in the parent process:%d\n",i);
  if(write(fd,"in the parent",strlen("in the parent"))==-1)
  {
   perror("write");
   exit(1);
  }
 }
 return 0;
}

 

1、fork()函数创建子进程后,子进程将复制父进程的数据段,BSS段,代码段,堆空间,栈空间。在上面的变量i可以看出,父子进程操作的是各自的i数据;

2、同时也复制了文件描述符,但是对于文件描述符关联的内核文件表现,则是采用共享的方式进行实现。

3、子进程执行位置为fork()函数的返回位置,虽然子进程完全复制了父进程的代码段,但是从fork()的返回位置向下执行。所以在子进程中是不会再执行

fd=open("text.txt",O_RDWR|O_CREAT,0777);
 if(fd==-1)
 {
  perror("open");
  exit(1);
 }
 if(write(fd,ch1,3)==-1)
 {
  perror("write");
  exit(1);
 }

 

原创粉丝点击