← 返回首页
Linux高级程序设计(六十五)
发表时间:2021-12-20 18:37:08
创建共享内存

使用shmget函数创建共享内存。

1.shmget函数

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

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

参数: - key:进程间通信键值,ftok() 的返回值。 - size:该共享存储段的长度(字节)。 - shmflg:标识函数的行为及共享内存的权限,其取值如下: IPC_CREAT:如果不存在就创建 IPC_EXCL: 如果已经存在则返回失败 位或权限位:共享内存位或权限位后可以设置共享内存的访问权限,格式和 open() 函数的 mode_t 一样(open() 的使用请点此链接),但可执行权限未使用。

返回值: - 成功:共享内存标识符。 - 失败:-1。

可以使用ulimit -a 命令查看共享内存的限制:

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 14517
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 65535
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 65536
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

2.实例

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <unistd.h>  
#include <sys/types.h>  
#include <sys/ipc.h>  
#include <sys/shm.h>  

#define BUFF_SIZE 1024  

int main(int argc, char *argv[])  
{  
    int shmid;  
    key_t key;  

    key = ftok("./", 2021);   
    if(key == -1)  
    {  
        perror("error to ftok:");
        exit(-1);  
    }  

    //创建共享内存  
    shmid = shmget(key, BUFF_SIZE, IPC_CREAT|0666);   
    if(shmid == -1)   
    {   
        perror("error to shmget:");   
        exit(-1);   
    }

    printf("shmid=%d\n",shmid);
    system("ipcs -m");

    return 0;  
}  

运行结果:

[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
shmid=32769

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000072 0          root       444        1          5                       
0xe5010131 32769      root       666        1024       0