AmidamaruZXC

Untitled

Jun 2nd, 2020
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 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 new = 1;
  22.  
  23. char pathname[] = "task2_w.c";
  24.  
  25. key_t key;
  26.  
  27. FILE *file = fopen(pathname, "r");
  28.  
  29. fseek(file, 0L, SEEK_END);
  30.  
  31. int len = ftell(file);
  32.  
  33. int* size;
  34.  
  35. if((key = ftok(pathname,0)) < 0){
  36.  
  37. printf("Can\'t generate key\n");
  38.  
  39. exit(-1);
  40.  
  41. }
  42.  
  43. if((shmid = shmget(key, sizeof(int) + len * sizeof(char), 0)) < 0) {
  44.  
  45. printf("Can\'t find shared memory\n");
  46.  
  47. exit(-1);
  48.  
  49. }
  50.  
  51. if((size = (int *)shmat(shmid, NULL, 0)) == (int *)(-1)){
  52.  
  53. printf("Can't attach shared memory\n");
  54.  
  55. exit(-1);
  56.  
  57. }
  58.  
  59. len = *size;
  60.  
  61. code = (char*)(size + 1);
  62.  
  63. for (int i = 0; i < len; ++i) {
  64.  
  65. putchar(code[i]);
  66.  
  67. }
  68.  
  69. if(shmdt(size) < 0){
  70.  
  71. printf("Can't detach shared memory\n");
  72.  
  73. exit(-1);
  74.  
  75. }
  76.  
  77. if (shmctl(shmid, IPC_RMID, NULL) < 0) {
  78.  
  79. printf("Can't delete shared memory\n");
  80.  
  81. }
  82.  
  83. return 0;
  84.  
  85. }
Add Comment
Please, Sign In to add comment