Linux -- inter-process communication -- shared memory

黄舟
Release: 2023-03-04 22:40:01
Original
1824 people have browsed it

一、共享内存
共享内存是最高效的通信方式,因为不需要一个进程先拷贝到内核,另一个进程在存内核中读取。

二、 ipcs -m 查看共享内存
ipcrm -m 删除共享内存

三、主要函数
shmget 创建

shmctl 删除

shmat 挂接

shmdt 取消挂接

********* man 函数名 查看*****
四、代码实现
comm.h

1 #pragma once  
  2 #include<stdio.h>  
  3 #include<stdlib.h>  
  4 #include<unistd.h>  
  5 #include<sys/ipc.h>  
  6 #include<sys/shm.h>  
  7 #define _PATH_ "."  
  8 #define _PROJID_ 0x666  
  9 #define _SHM_SIZE_ 4096  
 10 int getShmget();  
 11 int destoryShm(int shm_id);  
 12 char* at_shm(int shm_id);  
 13 int delete_Shm(char *addr);
Copy after login

comm.c

1 #include"comm.h"  
  2 int getShmget()  
  3 {  
  4     key_t key=ftok(_PATH_,_PROJID_);  
  5   
  6     int shmflg=IPC_CREAT |0666;  
  7     int shm_id=shmget(key,_SHM_SIZE_,shmflg);  
  8     if(shm_id<0)  
  9     {  
 10         perror("shmget");  
 11         return -1;  
 12     }     
 13     return shm_id;  
 14 }     
 15   
 16 int destoryShm(int shm_id)  
 17 {  
 18     return shmctl(shm_id,IPC_RMID,NULL);  
 19 }     
 20   
 21 char* at_shm(int shm_id)  
 22 {  
 23     return (char*)shmat(shm_id,NULL,0);  
 24 }  
 25 int delete_Shm(char *addr)  
 26 {  
 27     return shmdt(addr);  
 28 }
Copy after login

client.c

1 #include"comm.h"  
  2 int main()  
  3 {  
  4     int shm_id=getShmget();  
  5     char *addr=at_shm(shm_id);  
  6     int i=0;  
  7     for(;i<_SHM_SIZE_;i++)  
  8     {  
  9         addr[i ]=&#39;A&#39;;  
 10         addr[i+1]=&#39;\0&#39;;  
 11         sleep(1);  
 12     }     
 13     delete_Shm(addr);  
 14     return 0;  
 15 }
Copy after login

server.c

1 #include"comm.h"  
  2 int main()  
  3 {  
  4     int shm_id=getShmget();  
  5     char * addr=at_shm(shm_id);  
  6     int i=0;  
  7     for(;i<_SHM_SIZE_;i++)  
  8     {  
  9         printf("%s\n",addr);  
 10         sleep(1);  
 11     }  
 12     delete_Shm(addr);  
 13     destoryShm(shm_id);  
 14     return 0;  
 15 }
Copy after login

运行结果

Linux -- inter-process communication -- shared memory

以上就是Linux --进程间通信--共享内存的内容,更多相关内容请关注PHP中文网(www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template