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);
}
- linux fork函数浅析
- linux fork函数浅析
- fork函数浅析
- linux fork函数浅析
- linux fork函数浅析
- linux fork函数浅析
- fork()函数浅析
- fork()函数浅析
- linux fork函数浅析
- linux fork函数浅析
- linux fork函数浅析
- fork()函数浅析
- 浅析fork()函数
- linux fork()函数浅析
- fork函数浅析(转)
- 浅析linux中fork函数
- 【linux进程】fork函数浅析
- linux之fork函数浅析
- C#中利用ODP实现瞬间导入百万级数据详解
- People Name Memo
- 设计模式原则(2)开闭原则
- Portal-Basic Java Web 应用开发框架 v2.6.1(源码、示例及文档)
- 和菜鸟一起学c之函数中堆栈及运行内存情况
- fork()函数浅析
- 我看懂的设计模式 Strategy策略模式
- Linux添加环境变量与GCC编译器添加INCLUDE与LIB环境变量
- 编码转换之iconv批量转换
- Android AsyncTask异步处理
- Applet实例
- C#实现100万条数据导入SQL SERVER数据库仅用4秒 (附源码)
- Linux多进程编程学习笔记一
- ListView BaseAdapter 简单分析