// 生产者 #include #include #include #include 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; }