Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 共享內存四大函式詳解:shmget、shmat、shmdt、shmctl

System V 共享內存是行程間通訊(IPC)裡效率最高的一種方式,核心概念是讓多個行程映射同一片實體記憶體。Linux 為此提供了四個函式,本文逐一拆解其原型、參數與錯誤碼,並附上兩個可執行的范例。

shmget:取得或建立共享內存

所需標頭檔:

#include <sys/ipc.h>
與
#include <sys/shm.h>
。

int shmget(key_t key, size_t size, int shmflg)

參數:

key
為 0(IPC_PRIVATE)時會建立全新的共享內存;為大於 0 的 32 位元整數時,通常取自
ftok
的回傳值,實際行為由
shmflg
決定。
size
大於 0 時表示新建的大小(位元組),僅取得既有共享內存時填 0。
shmflg
取 0 表示只取標識符,不存在則報錯;
IPC_CREAT
表示不存在就新建、存在則回傳既有標識符;
IPC_CREAT|IPC_EXCL
則是存在就報錯。

成功回傳共享內存標識符,失敗回 -1。常見錯誤:

EINVAL
(size 超出 SHMMIN/SHMMAX)、
EEXIST
、
EIDRM
、
ENOSPC
(超出 SHMALL 上限)、
ENOENT
、
EACCES
、
ENOMEM
。

補充一點:新建立的共享內存空間會被初始化為 0x00,並設定

shm_lpid
、
shm_nattach
、
shm_atime
、
shm_dtime
為 0,
shm_ctime
為目前時間,
shm_segsz
為建立時的大小,權限放在
shm_perm.mode
,uid/gid 取自目前行程的有效使用者與群組 ID。

shmat:把共享內存接到自己的位址空間

void *shmat(int shmid, const void *shmaddr, int shmflg)

shmid
是共享內存標識符;
shmaddr
指定映射位置,通常填 NULL 讓核心自行挑選;
shmflg
為
SHM_RDONLY
時是唯讀模式,其他值為讀寫。成功回傳映射後的位址,失敗回 -1。

注意:fork 後子行程會繼承已連接的位址;exec 之後自動脫離;行程結束時也會自動 detach。錯誤碼包括

EACCES
、
EINVAL
、
ENOMEM
。

shmdt:中斷連接

int shmdt(const void *shmaddr)

shmaddr
為先前連接的起始位址。此函式並不會刪除共享內存,只是把它從目前行程脫離。成功回 0,失敗回 -1,錯誤碼
EINVAL
。

shmctl:共享內存管理

int shmctl(int shmid, int cmd, struct shmid_ds *buf)

cmd
有三種:
IPC_STAT
把
shmid_ds
結構複製到 buf 以取得狀態;
IPC_SET
把 buf 中的 uid、gid、mode 寫回共享內存;
IPC_RMID
刪除該片共享內存。錯誤碼有
EACCES
、
EFAULT
、
EIDRM
、
EINVAL
、
EPERM
。

范例一:父子行程通訊

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <error.h>
#define SIZE 1024
int main()
{
 int shmid ;
 char *shmaddr ;
 struct shmid_ds buf ;
 int flag = 0 ;
 int pid ;
 shmid = shmget(IPC_PRIVATE, SIZE, IPC_CREAT|0600 ) ;
 if ( shmid < 0 )
 {
 perror("get shm ipc_id error") ;
 return -1 ;
 }
 pid = fork() ;
 if ( pid == 0 )
 {
 shmaddr = (char *)shmat( shmid, NULL, 0 ) ;
 if ( (int)shmaddr == -1 )
 {
 perror("shmat addr error") ;
 return -1 ;
 }
 strcpy( shmaddr, "Hi, I am child process!\n") ;
 shmdt( shmaddr ) ;
 return 0;
 } else if ( pid > 0) {
 sleep(3 ) ;
 flag = shmctl( shmid, IPC_STAT, &buf) ;
 if ( flag == -1 )
 {
 perror("shmctl shm error") ;
 return -1 ;
 }
 printf("shm_segsz =%d bytes\n", buf.shm_segsz ) ;
 printf("parent pid=%d, shm_cpid = %d \n", getpid(), buf.shm_cpid ) ;
 printf("chlid pid=%d, shm_lpid = %d \n",pid , buf.shm_lpid ) ;
 shmaddr = (char *) shmat(shmid, NULL, 0 ) ;
 if ( (int)shmaddr == -1 )
 {
 perror("shmat addr error") ;
 return -1 ;
 }
 printf("%s", shmaddr) ;
 shmdt( shmaddr ) ;
 shmctl(shmid, IPC_RMID, NULL) ;
 }else{
 perror("fork error") ;
 shmctl(shmid, IPC_RMID, NULL) ;
 }
 return 0 ;
}

編譯

gcc shm.c -o shm
,執行
./shm
後輸出:

shm_segsz =1024 bytes
shm_cpid = 9503
shm_lpid = 9504
Hi, I am child process!

范例二:多行程讀寫

寫入端建立共享內存並填入資料:

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
typedef struct{
 char name[8];
 int age;
} people;
int main(int argc, char** argv)
{
 int shm_id,i;
 key_t key;
 char temp[8];
 people *p_map;
 char pathname[30] ;
 strcpy(pathname,"/tmp") ;
 key = ftok(pathname,0x03);
 if(key==-1)
 {
 perror("ftok error");
 return -1;
 }
 printf("key=%d\n",key) ;
 shm_id=shmget(key,4096,IPC_CREAT|IPC_EXCL|0600);
 if(shm_id==-1)
 {
 perror("shmget error");
 return -1;
 }
 printf("shm_id=%d\n", shm_id) ;
 p_map=(people*)shmat(shm_id,NULL,0);
 memset(temp, 0x00, sizeof(temp)) ;
 strcpy(temp,"test") ;
 temp[4]='0';
 for(i = 0;i<3;i++)
 {
 temp[4]+=1;
 strncpy((p_map+i)->name,temp,5);
 (p_map+i)->age=0+i;
 }
 shmdt(p_map) ;
 return 0 ;
}

讀取端用同一組 key 取得既有共享內存並印出內容:

#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
typedef struct{
 char name[8];
 int age;
} people;
int main(int argc, char** argv)
{
 int shm_id,i;
 key_t key;
 people *p_map;
 char pathname[30] ;
 strcpy(pathname,"/tmp") ;
 key = ftok(pathname,0x03);
 if(key == -1)
 {
 perror("ftok error");
 return -1;
 }
 printf("key=%d\n", key) ;
 shm_id = shmget(key,0, 0);
 if(shm_id == -1)
 {
 perror("shmget error");
 return -1;
 }
 printf("shm_id=%d\n", shm_id) ;
 p_map = (people*)shmat(shm_id,NULL,0);
 for(i = 0;i<3;i++)
 {
 printf( "name:%s\n",(*(p_map+i)).name );
 printf( "age %d\n",(*(p_map+i)).age );
 }
 if(shmdt(p_map) == -1)
 {
 perror("detach error");
 return -1;
 }
 return 0 ;
}

編譯執行

./shmwrite
後,再跑
./shmread
可看到三筆資料:

key=50453281
shm_id=688137
name:test1
age 0
name:test2
age 1
name:test3
age 2

若重複執行 shmwrite,因為使用了

IPC_EXCL
,會得到
shmget error: File exists
,這是預期行為。

Copyright © Linux教程網 All Rights Reserved