<pre> #include <sys/ipc.h> #include <sys/shm.h> #include <unistd.h> #include <stdio.h> void myexit(int ret); struct shared { char data[256]; }; struct shared *s = (void *)-1; int shm_id = -1; int main() { pid_t pid; if ((shm_id = shmget(IPC_PRIVATE, sizeof(struct shared), 0777)) == -1) { perror("shmget"); myexit(5); } printf("Shared memory id %d\n",shm_id); if ( (s = shmat(shm_id, NULL , 0)) == (void *)-1) { perror("shmat"); myexit(5); } printf("Shared memory attached at %p\n",s); if ( (pid = fork()) == -1 ) { perror("fork"); myexit(5); } if (pid == 0) { /* child -> process 0 */ sprintf(s->data,"Message from child"); printf("Child: Message sent\n"); myexit(0); } else { /* parent */ sleep(1); printf("Parent: s->data == %s\n",s->data); myexit(0); } } void myexit(int ret) { struct shmid_ds shds; /* detach shared memory (exit() do this automatically) */ if (s != (void *)-1) shmdt(s); /* mark shared memory segment as destroyed */ if (shm_id != -1) { shmctl(shm_id,IPC_RMID,&shds); } exit(ret); } </pre> -- Users.AntonioValletta - 10 Dec 2001 <br>
This topic: Sistemioperativi1
>
EsempioShared
Topic revision: r1 - 2001-12-10 - AntonioValletta
Copyright © 2008-2025 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki?
Send feedback