Operating Systems 173323 (3 cu)

Exercise 6

  1. Shared memory is the fastest way for the communication between the processes: processes have a common area in the memory and they use that to communicate. The following program uses shared memory. Add comment lines before each command line to explain the program code.
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    
    int key=2709;
    
    char *messu[] = { 
            "Hello",
            "Countdown",
            "5", "4","3","1","sorry, 2","1","GO\007",
            "------------------------------"
            };
    
    int n=10;
    
    char *shmat();
    
    main()
    {
      int id,i;
      char *seg;
    
      id = shmget(key,1024,IPC_CREAT | 0777);
      if (id == -1) {perror("shmget"); exit(1);}
    
      seg = shmat(id,(char *)0,0);
    
      for(i=0;;) {
            sprintf(seg,"%s",messu[i]);
            i++; i = i % n;
            sleep(1);
      }
    }
    
  2. The following program also uses shared memory. Add comment lines before each command line to explain the program code.
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    
    char *shmat();
    
    int key=2709;
    
    main()
    {
      int id,i;
      char *seg;
    
      id = shmget(key,1024, SHM_RDONLY);
      if (id == -1) {perror("shmget"); exit(1);}
    
      seg = shmat(id,(char *)0,0);
    
      while(1){
        printf("%s\n",seg);
        sleep(1);
        }
    }
    
  3. Save the programs in task 1 and task 2 in cs-computer and compile them. Start the execution of the program in task 1 in one session and in another session start the execution of the program in task 2. What happens and why ? Use ctrl-c to quit the programs.