#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);
}
本文通过一个简单的示例程序解释了`fork()`函数的工作原理。当`fork()`创建子进程时,它会复制父进程的数据段、BSS段、代码段、堆和栈空间。在示例中,变量`i`在父子进程中独立。同时,文件描述符被复制,但其关联的内核文件表示以共享方式实现。子进程从`fork()`返回的位置继续执行,因此不会再次执行文件打开和写入操作。

被折叠的 条评论
为什么被折叠?



