linux-共享内存

来源:互联网 发布:淘宝客免费建站 编辑:程序博客网 时间:2024/05/22 23:58

//shm_consumer.c

#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <sys/shm.h>#include "shm_com.h"/*this file is the consumer process*/int main(){int running = 1;void * shared_memory = (void*)0;struct shared_use_st * shared_stuff;int shm_id;srand((unsigned int)getpid());/* 1. creat share memory */shm_id = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);if(-1 == shm_id){fprintf(stderr, "shmget failed\n"); exit(EXIT_FAILURE);}/* 2. attach shared memory addredd in current process address space */shared_memory = shmat(shm_id, (void*)0, 0);if((void*)-1 == shared_memory){fprintf(stderr, "shmat failed\n"); exit(EXIT_FAILURE);}/* 3. converse shared memory to struct shared_use_st*/shared_stuff = (struct shared_use_st*)shared_memory;shared_stuff->written_by_you = 0;/* should use other synchron system*/while(running){if(shared_stuff->written_by_you){printf("[Consumer says] You wrote:%s", shared_stuff->some_text );sleep(rand() % 4);shared_stuff->written_by_you = 0;if(strncmp(shared_stuff->some_text, "end", 3) == 0){running = 0;}}}/* 4. detach shared memory*/if(shmdt(shared_memory) == -1){fprintf(stderr, "shmdt failed\n");exit(EXIT_FAILURE);}/*5. delete shared memory , "shmctl" not "shmctrl"*/if(shmctl(shm_id, IPC_RMID, 0) ==-1){        fprintf(stderr, "shmctrl(IPC_RMID) failed\n");exit(EXIT_FAILURE);}exit(EXIT_SUCCESS);}

//shm_producer.c

#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <sys/shm.h>#include "shm_com.h"/*this file is the Producer process*/int main(){int running = 1;void * shared_memory = (void*)0;struct shared_use_st * shared_stuff;int shm_id;char some_text[128] = {0};srand((unsigned int)getpid());/* 1. creat share memory */shm_id = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);if(-1 == shm_id){fprintf(stderr, "shmget failed\n"); exit(EXIT_FAILURE);}/* 2. attach shared memory addredd in current process address space */shared_memory = shmat(shm_id, (void*)0, 0);if((void*)-1 == shared_memory){fprintf(stderr, "shmat failed\n"); exit(EXIT_FAILURE);}/* 3. converse shared memory to struct shared_use_st*/shared_stuff = (struct shared_use_st*)shared_memory;shared_stuff->written_by_you = 0;while(running){while(shared_stuff->written_by_you){printf("wait for consumer to read...\n");sleep(1);}printf("[Producer]:Enter some text: ");fgets(some_text, 128, stdin);strncpy(shared_stuff->some_text, some_text, 128);shared_stuff->written_by_you = 1;if(strncmp(some_text, "end", 3) == 0){running = 0;}}/* 4. detach shared memory*/if(shmdt(shared_memory) == -1){fprintf(stderr, "shmdt failed\n");exit(EXIT_FAILURE);}exit(EXIT_SUCCESS);}



0 0