454545

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <sys/sem.h>

#define BUFFER_SIZE 10

typedef struct {

    int buffer[BUFFER_SIZE];

    int in;

    int out;

    int count;

} Buffer;

int main() {

    int shmid, semid;

    key_t key = ftok(".", 'S');

    Buffer *buffer;

    // 创建共享内存

    shmid = shmget(key, sizeof(Buffer), IPC_CREAT | 0666);

    if (shmid == -1) {

        perror("shmget");

        exit(1);

    }

    // 连接共享内存

    buffer = (Buffer *)shmat(shmid, NULL, 0);

    if (buffer == (Buffer *)(-1)) {

        perror("shmat");

        exit(1);

    }

    // 创建信号量集

    semid = semget(key, 1, IPC_CREAT | 0666);

    if (semid == -1) {

        perror("semget");

        exit(1);

    }

    // 初始化信号量

    semctl(semid, 0, SETVAL, 1);

    // 生产数据

    int data;

    printf("Enter data: ");

    scanf("%d", &data);

    // 获取互斥信号量

    struct sembuf sem_op;

    sem_op.sem_num = 0;

    sem_op.sem_op = -1;

    sem_op.sem_flg = 0;

    semop(semid, &sem_op, 1);

    // 放入缓冲区

    buffer->buffer[buffer->in] = data;

    buffer->in = (buffer->in + 1) % BUFFER_SIZE;

    buffer->count++;

    // 释放互斥信号量

    sem_op.sem_op = 1;

    semop(semid, &sem_op, 1);

    // 断开共享内存连接

    shmdt(buffer);

    return 0;

}

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <sys/sem.h>

#define BUFFER_SIZE 10

typedef struct {

    int buffer[BUFFER_SIZE];

    int in;

    int out;

    int count;

} Buffer;

int main() {

    int shmid, semid;

    key_t key = ftok(".", 'S');

    Buffer *buffer;

    // 创建共享内存

    shmid = shmget(key, sizeof(Buffer), IPC_CREAT | 0666);

    if (shmid == -1) {

        perror("shmget");

        exit(1);

    }

    // 连接共享内存

    buffer = (Buffer *)shmat(shmid, NULL, 0);

    if (buffer == (Buffer *)(-1)) {

        perror("shmat");

        exit(1);

    }

    // 创建信号量集

    semid = semget(key, 1, IPC_CREAT | 0666);

    if (semid == -1) {

        perror("semget");

        exit(1);

    }

    // 消费数据

    // 获取互斥信号量

    struct sembuf sem_op;

    sem_op.sem_num = 0;

    sem_op.sem_op = -1;

    sem_op.sem_flg = 0;

    semop(semid, &sem_op, 1);

    // 取出缓冲区数据

    int data = buffer->buffer[buffer->out];

    buffer->out = (buffer->out + 1) % BUFFER_SIZE;

    buffer->count--;

    // 释放互斥信号量

    sem_op.sem_op = 1;

    semop(semid, &sem_op, 1);

    // 打印数据

    printf("Data: %d\n", data);

    // 断开共享内存连接

    shmdt(buffer);

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值