Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Jan 31st, 2009 | Syntax: None | Size: 2.00 KB | Hits: 152 | Expires: Never
Copy text to clipboard
  1. /*
  2.     PUBLIC DOMAIN
  3.  
  4.     Fuck GNU, Fuck Creative Commons, Fuck BSD.
  5.     Attribution are for tards.
  6.                                                    */
  7.  
  8.  
  9. #include <sys/types.h>
  10. #include <sys/ipc.h>
  11. #include <sys/shm.h>
  12. #include <stdio.h>
  13.  
  14. const key_t SHM_KEY = 0x42385;              /* random number known by all processes, somehow */
  15. const int SHM_SIZE = 16*1024*1024;          /* 16MB get allocated.. */
  16. const int SHM_FLAGS = IPC_CREAT | 0666;     /* It does not work unless you supply IPC_CREAT (!?),
  17.                                                0666 are the permissions. */
  18.  
  19. /* Allocate does not allocate anything, it just returns an *identifier* to be used by attach() */
  20. int allocate()
  21. {
  22.    int shmid;
  23.    
  24.    if (( shmid = shmget( SHM_KEY, SHM_SIZE, SHM_FLAGS )) == -1 )
  25.    {
  26.       perror("shmget: shmget failed");
  27.       exit(1);
  28.    }
  29.    return shmid;
  30. }
  31.  
  32.  
  33. /* Returns a pointer to the shared memory, takes an identifier created by shmget() or allocate() */
  34. void *attach(int shmid)
  35. {
  36.    void *shm;
  37.    if(( shm = shmat( shmid, NULL, 0 )) == (void*) -1 )
  38.    {
  39.       perror("shmat");
  40.       exit(1);
  41.    }
  42.    return shm;
  43. }
  44.  
  45.  
  46. /* Child writes "Hello world.\n" to the shared memory, sleeps for one second and the dies. */
  47. void child()
  48. {
  49.    char *str = "Hello world.\n";
  50.    void *shared_mem;
  51.    
  52.    shared_mem = attach( allocate() );
  53.    
  54.    strncpy( shared_mem, str, strlen(str)+1 );
  55.    sleep(1);
  56.    
  57.    printf("The child has written to shared memory. Goodbye ;)\n");
  58.    _exit(0);
  59. }
  60.  
  61.  
  62. /* Mother reads from the shared memory after 2 seconds and prints the content. */
  63. void mother()
  64. {
  65.    void *shared_mem;
  66.  
  67.    shared_mem = attach( allocate() );
  68.    sleep(2);
  69.    printf("Mother reads from shared memory: %s", shared_mem);
  70.  
  71.    exit(0);
  72. }
  73.  
  74.  
  75. /* Creates two processes. */
  76. void forkoff()
  77. {
  78.    if( fork() == 0 )
  79.       child();
  80.    else mother();
  81. }
  82.  
  83.  
  84. /* bla bla blaa bla-bla blabla blabla-bla bla */
  85. int main()
  86. {
  87.    forkoff();
  88.    return -1;  /* should never return */
  89. }