#include #include #include #include #include #include #define SHM_SIZE 1024 /* make it a 1K shared memory segment */ int GetValue(char *n) { char s[200],*p; FILE *f; int value,len; f=fopen("/proc/meminfo", "r"); while ((p=fgets(s, 200, f)) != NULL) { len=strlen(n); if (strncmp(n, p, len)==0) { p+=len+1; while (isspace(*p)) p++; value=atol(p); fclose(f); return(value); } } fclose(f); return 0; } int main(int argc, char *argv[]) { key_t key; int shmid; char *data,*p; int mode; int memsize,committed_as; int i; if (argc > 3) { fprintf(stderr, "usage: shmdemo [data_to_write] [proj_of_ftok]\n"); exit(1); } committed_as=GetValue("Committed_AS"); printf("The value of Committed_AS is %d KB before attach\n", committed_as); memsize = atol(argv[1]); /* make the key: */ if ((key = ftok("/tmp/shm.tmp", *argv[2])) == -1) { perror("ftok"); exit(1); } /* connect to (and possibly create) the segment: */ if ((shmid = shmget(key, memsize, 0644 | IPC_CREAT)) == -1) { perror("shmget"); exit(1); } /* attach to the segment to get a pointer to it: */ p = data = shmat(shmid, (void *)0, 0); if (data == (char *)(-1)) { perror("shmat"); exit(1); } for (i=0; i< memsize-10; i++) *p++ = 'a'; committed_as=GetValue("Committed_AS"); printf("The value of Committed_AS is %d KB After attach\n", committed_as); /* detach from the segment: */ if (shmdt(data) == -1) { perror("shmdt"); exit(1); } return 0; }