一个fork的小例子
来源:互联网 发布:什么电视软件好 编辑:程序博客网 时间:2024/04/28 08:48
fork() creates a child process that differs from the parent process only in its PID and PPID, and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited.
Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.
1. 这个例子用于证明fork的父子进程共享文件描述符
#include <stdio.h>#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
int tmain(void){
int fd = 0;
pid_t pid = 0;
fd = open("./a.txt", O_CREAT|O_RDWR);
if(pid = fork()){
int status = 0;
char buf[1024] = {0};
wait( &status);
lseek(fd, 0 , 0);
read(fd, buf, 1024);
printf("%s\n", buf);
close(fd);
printf("Done\n");
}else{
char* buf = "Hello World";
write(fd, buf, strlen(buf));
}
return pid;
}
int main()
{
int res = tmain();
printf("In main, %d\n", res);
return 0;
}
=============================================================================================================
root@bogon /tmp # ./a.out
In main, 0
Hello World
Done
In main, 26506
- 一个fork的小例子
- fork的一个例子
- 一个小的例子
- 关于fork 的一个小问题
- linux 下的fork,exec 等函数的一个例子
- 一个验证的小例子
- spss的一个小例子
- 一个JNI的小例子
- 一个JDBC的小例子
- SwingWorker的一个小例子
- 一个dwr的小例子
- wstring的一个小例子
- python的一个小例子
- ScrollableResults的一个小例子
- RSS的一个小例子
- 一个jQ的小例子
- 多线程的一个小例子
- 一个ExpandableListActivity的小例子
- MFC 实现手形工具--用鼠标拖动CScrollView(类似手形工具)
- 在windows和linux用samba共享中遇到的问题
- 《火球——UML大战需求分析》(第3章 分析业务模型-类图)——3.2 类图的基本知识
- Android动画开发——Animation动画效果
- C#窗口特效
- 一个fork的小例子
- 10,标准C
- 理解本真的REST架构风格
- GCC 编译使用动态链接库和静态链接库
- 数据库连接
- LoadRunner中的参数与变量
- LeetCode 95: Unique Binary Search Trees II
- yum安装过程图文详解
- js跨域