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

47 lines
825 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("producer\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;
}
int num = 0;
while (1)
{
while (data_buf->flag == 1)
;
sprintf(data_buf->data, "hello, %d", num++);
data_buf->flag = 1;
printf("write data: %s\n", data_buf->data);
}
return 0;
}