《操作系统》的实验代码。
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.

64 lines
933 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()
  9. {
  10. int shmid;
  11. key_t key;
  12. char *shm, *s;
  13. /*
  14. * We need to get the segment named
  15. * "1234", created by the server.
  16. */
  17. key = 1234;
  18. /*
  19. * Locate the segment.
  20. */
  21. if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
  22. perror("shmget");
  23. return 1;
  24. }
  25. /*
  26. * Now we attach the segment to our data space.
  27. */
  28. if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
  29. perror("shmat");
  30. return 1;
  31. }
  32. /*
  33. * Zero out memory segment
  34. */
  35. memset(shm,0,SHMSZ);
  36. s = shm;
  37. /*
  38. * Client writes user input character to memory
  39. * for server to read.
  40. */
  41. for(;;){
  42. char tmp = getchar();
  43. // Eat the enter key
  44. getchar();
  45. if(tmp == 'q'){
  46. *shm = 'q';
  47. break;
  48. }
  49. *shm = tmp;
  50. }
  51. if(shmdt(shm) != 0)
  52. fprintf(stderr, "Could not close memory segment.\n");
  53. return 0;
  54. }