【Linux】进程间通信之System V共享内存
    		       		warning:
    		            这篇文章距离上次修改已过438天,其中的内容可能已经有所变动。
    		        
        		                
                
#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);
    }
 
    // 写入数据
    strcpy(shmaddr, "Hello, shared memory!");
 
    // 等待其他进程读取数据
    printf("Waiting for other process to read the data...\n");
    sleep(10);
 
    // 断开共享内存连接
    if (shmdt(shmaddr) < 0) {
        perror("shmdt");
        exit(1);
    }
 
    // 删除共享内存
    shmctl(shmid, IPC_RMID, NULL);
 
    return 0;
}这段代码展示了如何使用System V共享内存进行进程间通信。首先,我们通过ftok函数生成一个key,然后使用shmget创建一个共享内存段。接着,使用shmat函数将这个段连接到我们的地址空间。之后,我们向共享内存中写入一个字符串,并等待其他进程读取这个数据。最后,通过shmdt断开共享内存连接,并通过shmctl删除共享内存。
评论已关闭