【Linux】进程间通信3——system V共享内存
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
 
#define SHM_SIZE 1024
 
int main() {
    key_t key = ftok("shmkey", 65); // 生成key
    int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666); // 创建共享内存
    if (shmid < 0) {
        perror("shmget");
        exit(1);
    }
 
    char *shmaddr = (char *)shmat(shmid, NULL, 0); // 映射共享内存
    if ((int)shmaddr == -1) {
        perror("shmat");
        exit(1);
    }
 
    printf("Attached shared memory at address %p\n", shmaddr);
    strcpy(shmaddr, "Hello from shared memory"); // 写入数据
 
    sleep(10); // 保持进程运行,等待另一个进程访问共享内存
 
    if (shmctl(shmid, IPC_RMID, NULL) == -1) { // 删除共享内存
        perror("shmctl");
        exit(1);
    }
 
    shmdt(shmaddr); // 断开共享内存映射
    return 0;
}这段代码首先使用ftok生成key,然后通过shmget创建共享内存,并通过shmat将其映射到当前进程的地址空间。然后,它将一个字符串复制到共享内存中。最后,代码使用shmctl删除共享内存,并使用shmdt断开映射。这个例子展示了如何使用System V共享内存进行简单的进程间通信。
评论已关闭