AmidamaruZXC

Untitled

Jun 2nd, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.10 KB | None | 0 0
  1. #include <sys/types.h>
  2.  
  3. #include <sys/ipc.h>
  4.  
  5. #include <sys/shm.h>
  6.  
  7. #include <stdio.h>
  8.  
  9. #include <errno.h>
  10.  
  11. #include <stdlib.h>
  12.  
  13. int main()
  14.  
  15. {
  16.  
  17. char* code;
  18.  
  19. int shmid;
  20.  
  21. int len;
  22.  
  23. char pathname[] = "task2_w.c";
  24.  
  25. key_t key;
  26.  
  27. FILE *file;
  28.  
  29. file = fopen(pathname, "r");
  30.  
  31. fseek(file, 0L, SEEK_END);
  32.  
  33. len = ftell(file);
  34.  
  35. rewind(file);
  36.  
  37. int *size;
  38.  
  39. if((key = ftok(pathname,0)) < 0){
  40.  
  41. printf("Can\'t generate key\n");
  42.  
  43. exit(-1);
  44.  
  45. }
  46.  
  47. if((shmid = shmget(key, sizeof(int) + len * sizeof(char), 0666|IPC_CREAT|IPC_EXCL)) < 0){
  48.  
  49. if(errno != EEXIST){
  50.  
  51. printf("Can\'t create shared memory\n");
  52.  
  53. exit(-1);
  54.  
  55. } else {
  56.  
  57. if((shmid = shmget(key, sizeof(int) + len * sizeof(char), 0)) < 0){
  58.  
  59. printf("Can\'t find shared memory\n");
  60.  
  61. exit(-1);
  62.  
  63. }
  64.  
  65. }
  66.  
  67. }
  68.  
  69. if((size = (int *)shmat(shmid, NULL, 0)) == (int *)(-1)){
  70.  
  71. printf("Can't attach shared memory\n");
  72.  
  73. exit(-1);
  74.  
  75. }
  76.  
  77. *size = len;
  78.  
  79. code = (char*)(size + 1);
  80.  
  81. for (int i = 0; i < len; ++i) {
  82.  
  83. code[i] = fgetc(file);
  84.  
  85. }
  86.  
  87. if(shmdt(size) < 0){
  88.  
  89. printf("Can't detach shared memory\n");
  90.  
  91. exit(-1);
  92.  
  93. }
  94.  
  95. return 0;
  96.  
  97. }
Add Comment
Please, Sign In to add comment