#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"
fork()函数浅析
最新推荐文章于 2021-05-04 11:43:19 发布
本文通过一个简单的示例程序解释了`fork()`函数的工作原理。当`fork()`创建子进程时,它会复制父进程的数据段、BSS段、代码段、堆和栈空间。在示例中,变量`i`在父子进程中独立。同时,文件描述符被复制,但其关联的内核文件表示以共享方式实现。子进程从`fork()`返回的位置继续执行,因此不会再次执行文件打开和写入操作。
摘要由CSDN通过智能技术生成