进程通信(共享内存)

来源:互联网 发布:java开源聊天机器人 编辑:程序博客网 时间:2024/06/05 11:40

共享内存:

用于进程间数据传输,是最高效的,并不提供同步,互斥

 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]$ ./SHMwe are young[admin@localhost SHM]$


本文出自 “liveyoung” 博客,转载请与作者联系!

0 0