标签:
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<string.h> #include<sys/shm.h> #define TEXT_SZ 2048 struct shared_use_st { int written_by_you; char some_text[TEXT_SZ]; }; int main() { int running = 1; void *shared_memory =(void *)NULL; struct shared_use_st *shared_stuff; int shmid; srand((unsigned int)getpid()); shmid = shmget((key_t)1234,sizeof(struct shared_use_st),0666 | IPC_CREAT); if(shmid == -1) { fprintf(stderr,"shmget error"); exit(1); } shared_memory = shmat(shmid,NULL,NULL); if(shared_memory == (void *)-1){ fprintf(stderr,"shmat error"); exit(1); } printf("Memory attached at %x\n",(int)(shared_memory)); shared_stuff = (struct shared_use_st *)shared_memory; shared_stuff->written_by_you = 0; while(running) { if(shared_stuff->written_by_you) { printf("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; } } } if(shmdt(shared_memory) == -1){ fprintf(stderr,"shmdt failed\n"); exit(EXIT_FAILURE); } if(shmctl(shmid, IPC_RMID, 0) == -1) { fprintf(stderr,"shmctl IPC_RMID failed!\n"); exit(1); } exit(0); }
#include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/shm.h> #define BUFSIZE 2048 struct shared_use_st { int written_by_you; char some_text[BUFSIZE]; }; int main() { int running; void *shared_memory = NULL; struct shared_use_st *shared_stuff; char buffer[BUFSIZE]; int shmid; if( shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT) == -1){ fprintf(stderr,"shmget error"); exit(1); } shared_memory = shmat(shmid, NULL,NULL); if(shared_memory == (void *)-1){ fprintf(stderr,"shmat error"); exit(1); } printf("Memory attached at %X\n",(int)shared_memory); shared_stuff = (struct shared_use_st *)shared_memory; while(1){ while(shared_stuff->written_by_you == 1){ sleep(1); printf("Waiting for client ...\n"); } printf("Enter some text: "); fgets(buffer, BUFSIZE,stdin); strncpy(shared_stuff->some_text,buffer,BUFSIZE); shared_stuff->written_by_you = 1; if(strncmp(buffer,"end",3) == 0) break; } if(shmdt(shared_memory) == -1){ fprintf(stderr,"shmdt error"); exit(1); } exit(0); }
标签:
原文地址:http://www.cnblogs.com/farbeyond/p/4542735.html