Advertisement
Guest User

Untitled

a guest
Dec 16th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <unistd.h>
  5. #include <sys/wait.h>
  6. #include <limits.h>
  7. #include <stdlib.h>
  8. #include <sys/msg.h>
  9. #include <sys/ipc.h>
  10. #include <sys/types.h>
  11. #include <sys/sem.h>
  12. #include <sys/shm.h>
  13.  
  14. int main(int argc, char const *argv[])
  15. {
  16.     if (argc < 2) {
  17.         return 1;
  18.     }
  19.     int *children = calloc(argc - 1, sizeof(int));
  20.     int shmid = shmget(IPC_PRIVATE, sizeof(unsigned long long) * (argc - 1), 0666);
  21.     unsigned long long *shmaddr = shmat(shmid, NULL, 0);
  22.     for (int i = 0; i < argc - 1; ++i) {
  23.         pid_t pid = fork();
  24.         if (pid > 0) {
  25.             children[i] = pid;
  26.         } else if (!pid) {
  27.             long long cur1 = strtoll(argv[i + 1], NULL, 10);
  28.             unsigned long long sum = 0;
  29.             unsigned long long cur = cur1;
  30.             if (cur1 < 0) {
  31.                 cur *= (-1);
  32.             }
  33.             while (cur) {
  34.                 sum += (cur % 4);
  35.                 cur /= 4;
  36.             }
  37.             shmaddr[i] = sum;
  38.             exit(0);
  39.         }
  40.     }
  41.     for (int i = 0; i < argc - 1; ++i) {
  42.         wait(NULL);
  43.     }
  44.     for (int i = 0; i < argc - 1; ++i) {
  45.         printf("%lld\n", shmaddr[i]);
  46.         fflush(stdout);
  47.     }
  48.     free(children);
  49.     shmdt(shmaddr);
  50.     shmctl(shmid, IPC_RMID, NULL);
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement