【Linux】System V 共享内存
    		       		warning:
    		            这篇文章距离上次修改已过443天,其中的内容可能已经有所变动。
    		        
        		                
                System V 共享内存是一种在多个进程之间提供内存共享的机制。以下是使用System V共享内存的基本步骤和示例代码:
- 创建共享内存区:使用shmget()函数。
- 连接共享内存区:使用shmat()函数。
- 断开共享内存区:使用shmdt()函数。
- 控制共享内存区:使用shmctl()函数。
示例代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
 
int main() {
    int shm_id;
    char* shm_addr;
    const int SIZE = 1024;
 
    // 创建共享内存区
    if ((shm_id = shmget(IPC_PRIVATE, SIZE, 0666)) < 0) {
        perror("shmget");
        return -1;
    }
 
    // 连接共享内存区
    if ((shm_addr = (char*)shmat(shm_id, NULL, 0)) < 0) {
        perror("shmat");
        return -1;
    }
 
    // 使用共享内存区(例如,写入数据)
    strcpy(shm_addr, "Hello, shared memory!");
 
    // 断开共享内存区
    if (shmdt(shm_addr) < 0) {
        perror("shmdt");
        return -1;
    }
 
    // 删除共享内存区(可选)
    if (shmctl(shm_id, IPC_RMID, NULL) < 0) {
        perror("shmctl");
        return -1;
    }
 
    printf("Data written to shared memory with ID: %d\n", shm_id);
    return 0;
}这段代码创建了一个共享内存区,写入了一段文本,然后断开并删除了共享内存区。在实际应用中,可以通过键值key来共享内存区,或者在多个进程之间通过该key来连接相同的共享内存区。
评论已关闭