qfedu-linux-advanced-level/day5/consumer.c

46 lines
772 B
C
Raw Permalink Normal View History

2023-08-18 16:47:04 +08:00
// 消费者
#include <stdio.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <unistd.h>
typedef struct data
{
char data[32];
int flag;
} Data;
int main()
{
printf("consumer\n");
key_t key = ftok("/", 15);
if (key == -1)
{
perror("ftok");
return 1;
}
int shmid = shmget(key, sizeof(Data), IPC_CREAT | 0666);
if (shmid == -1)
{
perror("shmget");
return 1;
}
Data *data_buf = (Data *)shmat(shmid, NULL, 0);
if (data_buf == (Data *)-1)
{
perror("shmat");
return 1;
}
while (1)
{
while (data_buf->flag == 0)
;
sleep(1);
printf("read data: %s\n", data_buf->data);
data_buf->flag = 0;
}
return 0;
}