父子进程的资源访问
父子进程的资源访问
6.1.内存资源
6.2.文件资源
案例: procmem.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> #include <signal.h> #include <sys/mman.h> main() { //int *a = malloc(4); /* int *a=mmap(0,4,PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE,0,0); //匿名映射 */ int *a=sbrk(4); //映射到不同物理内存 *a=40; if(fork()) { printf("parent:%d\n",*a); *a=90; } else { printf("child:%d\n",*a); sleep(3); printf("child:%d\n",*a); } }
说明:子进程克隆整个内存区域(全局区,局部区,堆等整个内存区域),
子进程的虚拟地址重新映射。。。。(映射是独立的)
但内存区域指向不同的物理空间
尽管克隆,但内存独立. 不能相互访问.
多进程实现多任务,进程之间的数据交换是大问题.(IPC)
Inter-Process Commucation
比如:剪切板 网络等
映射内存:
MAP_SHARED:映射到同一物理内存
MAP_PRIVATE:映射到不同的物理内存.int *a=mma(0,4,PROT_READ|
PROT_WRITE,
MAP_ANONYMOUS|MAP_PRIVATE,0,0); //匿名映射
之后会花大量时间解决IPC (父子进程间、平行进程间)
案例: procfile.c
两个进程之间,文件描述符号指向的是同一个文件内核对象. 。。。文件要关闭两次,父进程关闭一次,子进程关闭一次。。。父进程 的文件偏移值会影响
子进程
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> #include <signal.h> #include <sys/mman.h> #include <fcntl.h> main() { //int fd=open("test.txt",O_RDWR);//打开一个文件 if(fork()) { int fd=open("test.txt",O_RDWR);//打开一个文件 printf("%d\n",fd); sleep(5); write(fd,"Killer",6); close(fd);//一定要做两次 ,这是第一次 } else { int fd=open("test.txt",O_RDWR); printf("%d\n",fd); write(fd,"Clinton",7); sleep(8); close(fd);//一定要做两次 ,这是第二次 } }
结论:
进程的数据交换,基于两种方式:
内存:有序/无序:mmap
文件:有序/无序:普通文件
基于内核对象:文件.内存.队列

浙公网安备 33010602011771号