《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1006 B

  1. #include <sys/types.h>
  2. #include <sys/ipc.h>
  3. #include <sys/shm.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <string.h>
  7. #define SHMSZ 1024
  8. main(int argc, char **argv)
  9. {
  10. char c, tmp;
  11. int shmid;
  12. key_t key;
  13. char *shm, *s;
  14. /*
  15. * Shared memory segment at 1234
  16. * "1234".
  17. */
  18. key = 1234;
  19. /*
  20. * Create the segment and set permissions.
  21. */
  22. if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
  23. perror("shmget");
  24. return 1;
  25. }
  26. /*
  27. * Now we attach the segment to our data space.
  28. */
  29. if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
  30. perror("shmat");
  31. return 1;
  32. }
  33. /*
  34. * Zero out memory segment
  35. */
  36. memset(shm,0,SHMSZ);
  37. s = shm;
  38. /*
  39. * Read user input from client code and tell
  40. * the user what was written.
  41. */
  42. while (*shm != 'q'){
  43. sleep(1);
  44. if(tmp == *shm)
  45. continue;
  46. fprintf(stdout, "You pressed %c\n",*shm);
  47. tmp = *shm;
  48. }
  49. if(shmdt(shm) != 0)
  50. fprintf(stderr, "Could not close memory segment.\n");
  51. return 0;
  52. }