Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* basic memory sharing, UNIX-native */
- /* NEEDS TO BE COMPILED WITH -c */
- /* pointer arithmetics:
- *
- * push(pointer, v) INDICATES *(pointer++) = v
- * pop(pointer) INDICATES *(--pointer)
- * (*++v)[0] INDICATES (**++v)
- * INDICATES first char in v
- * INDICATES name of string/vector v
- * likewise, *v[0] INDICATES **v
- * and *v[n] INDICATES **(v + n)
- * returntype (*funct)(args) INDICATES a function funct with arguments args which returns...
- * char **argv INDICATES pointer to char pointer
- * int(*v)[len] INDICATES pointer "v" to a vector of "len" int elements
- * int *v[len] INDICATES vector "v" of "len" pointers to int elements
- * void *funct() INDICATES function "funct" that returns a pointer-to-void
- * void (*funct)() INDICATES pointer to a function "funct" that returns void
- *
- */
- /* useful characters: [] # */
- # include <stdio.h>
- # include <stdlib.h> // for exit
- # include <sys/ipc.h>
- # include <sys/shm.h> // for shmdet
- # include <sys/types.h> // for shmdet
- # include <string.h> // for strcpy
- # define SIZE 1024 // message size
- # define exception(x) { puts(x); exit(1); }
- int main(int argc, char * argv[])
- {
- /* initialisation */
- int shm, success; // SHaredMemory ID and flag
- key_t key = 30;
- shm = shmget(key, SIZE, IPC_CREAT|IPC_EXCL|0666); // allocates memory
- if(shm == -1)
- exception("Call shmget() unsuccessful");
- /* management */
- // SHM and SUCCESS will be used without being reinstanced
- void * memAddr; // memory address
- /* the shared memory will now be associated to the running process */
- memAddr = shmat(shm, 0, 0); // memaddr = 0, start of memory; mode: RW
- if(memAddr == (void *) -1) exception("Call shmat() unsuccessful"); // what's in the "if" clause?
- strcpy(memAddr, "Hello world!"); // writes to SHARED memory
- printf("Message: %s", memAddr);
- /* now, the process will release the memory */
- success = shmdet(memAddr);
- success = shmctl(shm, IPC_RMID, NULL); // always use null!
- if(success == -1) exception("Memory deallocation unsuccessful");
- /* Sample at: pg. 45
- * One function for the memory writer, one for the reader, both in a do-while(!quit)
- *
- * writer() contains shmat(), puts("please input"), scanf() and strcpy() (last two in do-while)
- * reader() contains shmat(), printf() (in do-while)
- *
- * main() contains: shmget(), and then
- * if(fork()) wait(&status); else writer(shm_descriptor);
- * if(fork()) wait(&status); else reader(shm_descriptor);
- *
- * ...And then shmctl(IPC_RMID).
- */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement