1.创建编辑hdpark.c文件如下
#include<stdio.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
int main()
{
int segment_id;#进程号
char *shared_memory;
const int size=4096;
segment_id =shmget(IPC_PRIVATE,size,S_IRUSR | S_IWUSR);
//进程号,私有,S_IRUSR | S_IWUS表明权限为读和写
shared_memory=(char*)shmat(segment_id,NULL,0);
// shared_memory是堆上的动态内存,这里是将内存和这个进程绑定
pid_t pid=fork();
if(pid==0)
{
shared_memory=(char*)shmat(segment_id,NULL,0);
//与子进程绑定
printf("Child Write:Hi There!\n");
sprintf(shared_memory,"Hi There!");
//将"Hi There!"写入shared_memory
}
else{
wait(NULL);
printf("Parant Read: %s\n", shared_memory);
shmdt(shared_memory);
shmctl(segment_id,IPC_RMID,NULL);
//释放这个动态的内存空间
}
return 0;
}
2.gcc -o hdpark hdpark.c 将其编译
3.运行 hdpark
输出:
Child Write:Hi There!
Parant Read: Hi There!
Parant Read: Hi There!表明父进程读到了子进程写在程序里面的数据,
说明父子进程共享一块内存。
Q:如果去掉wait(NULL)会怎么样
父进程会读不到子进程写的: Hi There!
即
Parant Read:
Child Write:Hi There!
交替输出,先后顺序不一定。