共享内存:
用于进程间数据传输,是最高效的,并不提供同步,互斥
shm.h:
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<sys/ipc.h>
4 #include<sys/shm.h>
5 #include<string.h>
6 #include<sys/wait.h>
7 #include <unistd.h>
8
9
10 #define _PATH_ "."
11 #define _PROJ_ID 0x666
12 #define SIZE 4096
13
14 int shm_create();
15 int shm_get();
16 void* at_shm(int shm_id);
17 int destroy_shm(int );
18 int delete_shm(void*);
shm.c:
1 #include "shm.h"
2 int com_shm_create(int flags)
3 {
4 key_t key=ftok(_PATH_,_PROJ_ID);
5 if(key<0)
6 {
7 perror("ftok");
8 return -1;
9 }
10 int _shm_id=shmget(key,SIZE,flags);
11 if(_shm_id<0)
12 {
13 perror("shmget");
14 return -1;
15 }
16 return _shm_id;
17 }
18 int shm_create()
19 {
20 return com_shm_create(IPC_CREAT|IPC_EXCL|0666);
21 }
22 int shm_get()
23 {
24
25 return com_shm_create(IPC_CREAT);
26
27 }
28 void* at_shm(int _shm_id)
29 {
30 return shmat(_shm_id,NULL,0);
31 }
32 int destroy_shm(int _shm_id)
33 {
34 return shmctl(_shm_id,IPC_RMID,NULL);
35 }
36 int delete_shm(void* addr)
37 {
38 return shmdt(addr);
39 }
test.c:
1 #include "shm.h"
2 int main()
3 {
4 int _shm_id=shm_create();
5 pid_t pid=fork();
6 if(pid<0)
7 {
8 perror("fork");
9 return -1;
10 }
11 else if(pid ==0)
12 {
13 int _shm_id=shm_get();
14 char* str=(char*)at_shm(_shm_id);
15 char* s="we are young";
16 strcpy(str,s);
17 sleep(5);
18 delete_shm(str);
19 }
20 else
21 {
22 char* str=(char*)at_shm(_shm_id);
23 sleep(5);
24 printf("%s",str);
25
26 delete_shm(str);
27 waitpid(pid,NULL,0);
28 destroy_shm(_shm_id);
29
30 }
31 return 0;
32 }
Makefile:
1 SHM:shm.c test.c
2 gcc -o $@ $^
3 .PHONY:clean
4 clean:
5 rm -f SHM
结果:
[admin@localhost SHM]$ ./SHM
we are young[admin@localhost SHM]$
本文出自 “liveyoung” 博客,转载请与作者联系!
本文介绍了一个使用共享内存进行进程间通信的例子。通过创建共享内存段并实现数据交换,父进程与子进程能够共享字符串数据。文章提供了从共享内存创建、获取到销毁的完整流程,并附带了源代码及编译指令。
768

被折叠的 条评论
为什么被折叠?



