Linux进程通信-共享内存

该代码示例展示了如何在C语言中通过shmget创建共享内存,sem_open创建信号量,实现发送端与接收端之间的数据传输。发送端读取用户输入并存储到共享内存,接收端则从共享内存读取数据并打印,直到接收到exit为止。整个过程利用信号量进行同步,确保读写操作的互斥。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

发送端

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

int main()
{
    char* shmaddr;

    int shmgetId;

    shmgetId = shmget(100, 4096, IPC_CREAT | 0666);
    if(shmgetId == -1)
    {
        printf("shmget fail!\n");
        exit(-1);
    }
    printf("shmget success!\n");

    shmaddr = (char*)shmat(shmgetId, 0, 0);
    printf("shmat success!\n");

    sem_t* semr = sem_open("mysem_r", O_CREAT | O_RDWR, 0666, 1);
    if(semr == SEM_FAILED)
    {
        printf("sem_r open fail!\n");
        exit(-1);
    }

    sem_t* semw = sem_open("mysem_w", O_CREAT | O_RDWR, 0666, 1);
    if(semw == SEM_FAILED)
    {
        printf("sem_w open fail!\n");
        exit(-1);
    }

    while(1)
    {
        sem_wait(semw);
        printf(">");
        fgets(shmaddr, 1024, stdin);
        sem_post(semr);
        if(strncmp(shmaddr, "exit", 4) == 0)
        {
            break;
        }
    }

    shmdt(shmaddr);
    shmctl(shmgetId, IPC_RMID, 0);
    return 0;
}

接收端

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

int main()
{
    char* shmaddr;

    int shmgetId;
    shmgetId = shmget(100, 4096, 0);

    if(shmgetId == -1)
    {
        printf("shmget fail! \n");
        exit(-1);
    }

    printf("shmget success!\n");

    shmaddr = (char*)shmat(shmgetId, 0, 0);
    printf("shmat success!");

    sem_t* semr = sem_open("mysem_r", O_CREAT | O_RDWR, 0666, 1);
    if(semr == SEM_FAILED)
    {
        printf("sem_r open fail!\n");
        exit(-1);
    }

    sem_t* semw = sem_open("mysem_w", O_CREAT | O_RDWR, 0666, 1);
    if(semw == SEM_FAILED)
    {
        printf("sem_w open fail!\n");
        exit(-1);
    }

    while (1)
    {
        sem_wait(semr);// 阻塞等待读信号量的值为1后,减1返回
        printf("%s\n", shmaddr);
        sem_post(semw); // 读完之后设置写信号量,加1返回
        if(strncmp(shmaddr, "exit", 4) == 0)
        {
            break;
        }
    }

    shmdt(shmaddr);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值