tst-shmctl.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/ipc.h>
  4. #include <sys/shm.h>
  5. #include <time.h>
  6. #include <unistd.h>
  7. struct timespec ts = {
  8. .tv_sec = 3468960000, // 2075-12-05 Destination timestamp
  9. .tv_nsec = 0
  10. };
  11. void print_shmid_ds(struct shmid_ds *buf) {
  12. printf("shm_perm.uid: %d \n", buf->shm_perm.uid);
  13. printf("shm_perm.gid: %d \n", buf->shm_perm.gid);
  14. printf("shm_perm.cuid: %d \n", buf->shm_perm.cuid);
  15. printf("shm_perm.cgid: %d \n", buf->shm_perm.cgid);
  16. printf("shm_perm.mode: %o \n", buf->shm_perm.mode);
  17. printf("shm_segsz: %lu \n", buf->shm_segsz);
  18. printf("shm_lpid: %d \n", buf->shm_lpid);
  19. printf("shm_cpid: %d \n", buf->shm_cpid);
  20. printf("shm_nattch: %lu \n", buf->shm_nattch);
  21. printf("shm_atime: %s", buf->shm_atime ? ctime(&buf->shm_atime) : "Not set\n");
  22. printf("shm_dtime: %s", buf->shm_dtime ? ctime(&buf->shm_dtime) : "Not set\n");
  23. printf("shm_ctime: %s\n", ctime(&buf->shm_ctime));
  24. }
  25. int main() {
  26. struct timespec ts_init, ts_final;
  27. // Save system time
  28. if (clock_gettime(CLOCK_REALTIME, &ts_init) == -1) {
  29. perror("Error getting time");
  30. return 1;
  31. }
  32. if (clock_settime(CLOCK_REALTIME, &ts) == -1) { // Set the time to after 2038
  33. perror("Error setting time");
  34. return 1;
  35. }
  36. key_t key = ftok(".", 'S');
  37. int shmid = shmget(key, 1024, IPC_CREAT | 0666);
  38. if (shmid == -1) {
  39. perror("shmget");
  40. exit(1);
  41. }
  42. struct shmid_ds buf;
  43. if (shmctl(shmid, IPC_STAT, &buf) == -1) {
  44. perror("shmctl");
  45. exit(1);
  46. }
  47. printf("Shared Memory Segment Info:\n");
  48. print_shmid_ds(&buf);
  49. // Change to new permissions
  50. buf.shm_perm.mode = 0600;
  51. if (shmctl(shmid, IPC_SET, &buf) == -1) {
  52. perror("shmctl IPC_SET failed");
  53. shmctl(shmid, IPC_RMID, NULL);
  54. exit(EXIT_FAILURE);
  55. }
  56. if ((buf.shm_ctime - ts.tv_sec > 60) || (ts.tv_sec - buf.shm_ctime > 60)) {
  57. printf("\nShmctl get a error time! \n");
  58. exit(EXIT_FAILURE);
  59. }
  60. printf("Shared Memory Segment Info:\n");
  61. print_shmid_ds(&buf);
  62. shmctl(shmid, IPC_RMID, NULL);
  63. // Restore system time
  64. clock_gettime(CLOCK_REALTIME, &ts_final);
  65. ts_init.tv_sec = ts_init.tv_sec + ts_final.tv_sec - ts.tv_sec;
  66. clock_settime(CLOCK_REALTIME, &ts_init);
  67. return 0;
  68. }