LCA2011 version
[tridge/junkcode.git] / zero_sample.c
1 #include <stdlib.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <sys/ipc.h>
6 #include <sys/shm.h>
7
8 /* return a pointer to a anonymous shared memory segment of size "size"
9    which will persist across fork() but will disappear when all processes
10    exit 
11    The memory is not zeroed 
12    */
13 void *shm_setup(int size)
14 {
15         int shmid;
16         void *ret;
17
18         shmid = shmget(IPC_PRIVATE, size, SHM_R | SHM_W);
19         if (shmid == -1) {
20                 printf("can't get shared memory\n");
21                 exit(1);
22         }
23         ret = (void *)shmat(shmid, 0, 0);
24         if (!ret || ret == (void *)-1) {
25                 printf("can't attach to shared memory\n");
26                 return NULL;
27         }
28
29         /* the following releases the ipc, but note that this process
30            and all its children will still have access to the memory, its
31            just that the shmid is no longer valid for other shm calls. This
32            means we don't leave behind lots of shm segments after we exit */
33         shmctl(shmid, IPC_RMID, 0);
34         
35         return ret;
36 }
37
38
39
40 int main(int argc, char *argv[])
41 {
42         char *buf;
43         int size, child;
44
45         if (argc < 2) {
46                 printf("shm_sample <size>\n");
47                 exit(1);
48         }
49
50         size = atoi(argv[1]);
51
52         buf = shm_setup(size);
53
54         if (!buf) {
55                 printf("shm_setup(%d) failed\n", size);
56                 exit(1);
57         }
58         memset(buf, size, 0);
59
60         child = fork();
61
62         /* now just to show it worked we will put the pid of the child
63            at the start of the shared memory segment and read it from
64            the child */
65         if (child) {
66                 *(int *)buf = child;
67         } else {
68                 while (*(int *)buf == 0) ;
69                 printf("pid via shm is %d real pid is %d\n",
70                        *(int *)buf, getpid());
71         }
72
73         return 0;
74 }
75