← 返回首页
Linux高级程序设计(六十八)
发表时间:2021-12-20 23:54:36
共享内存控制

1.共享内存控制

shmctl函数实现共享内存属性的控制。

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

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

参数:

返回值:

实例:

#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;  
    int ret;

    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");

    //删除共享内存
    shmctl(shmid, IPC_RMID, NULL);
    system("ipcs -m"); //查看共享内存

    return 0;  
}  

运行结果:

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

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


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