#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;
}