tst-shmctl.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. if (clock_settime(CLOCK_REALTIME, &ts) == -1) { // Set the time to after 2038
  27. perror("Error setting time");
  28. return 1;
  29. }
  30. key_t key = ftok(".", 'S');
  31. int shmid = shmget(key, 1024, IPC_CREAT | 0666);
  32. if (shmid == -1) {
  33. perror("shmget");
  34. exit(1);
  35. }
  36. struct shmid_ds buf;
  37. if (shmctl(shmid, IPC_STAT, &buf) == -1) {
  38. perror("shmctl");
  39. exit(1);
  40. }
  41. printf("Shared Memory Segment Info:\n");
  42. print_shmid_ds(&buf);
  43. // Change to new permissions
  44. buf.shm_perm.mode = 0600;
  45. if (shmctl(shmid, IPC_SET, &buf) == -1) {
  46. perror("shmctl IPC_SET failed");
  47. shmctl(shmid, IPC_RMID, NULL);
  48. exit(EXIT_FAILURE);
  49. }
  50. if ((buf.shm_ctime - ts.tv_sec > 60) || (ts.tv_sec - buf.shm_ctime > 60)) {
  51. printf("\nShmctl get a error time! \n");
  52. exit(EXIT_FAILURE);
  53. }
  54. printf("Shared Memory Segment Info:\n");
  55. print_shmid_ds(&buf);
  56. shmctl(shmid, IPC_RMID, NULL);
  57. return 0;
  58. }