Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/ipc.h>
  5. #include <sys/sem.h>
  6. #include <stdlib.h>
  7. #include <sys/shm.h>
  8. #include <errno.h>
  9. #include <sys/wait.h>
  10. #include <fcntl.h>
  11.  
  12. enum { BASE = 10, INIT = 123456 };
  13. int main(int argc, char *argv[]) {
  14. setbuf(stdin, NULL);
  15. int nproc = strtol(argv[2], NULL, BASE);
  16. key_t key = INIT;
  17. int semid = semget(key, nproc, 0666 | IPC_CREAT);
  18. if (semid < 0) {
  19. exit(errno);
  20. }
  21. pid_t p;
  22. u_int32_t x;
  23. int fd = open(argv[1], O_RDONLY);
  24. for (int i = 0; i < nproc; ++i) {
  25. if ((p = fork()) == -1) {
  26. exit(errno);
  27. }
  28. if (!p) {
  29. u_int32_t sum = 0;
  30. off_t offset = lseek(fd, 0, SEEK_END);
  31. off_t cur = i * sizeof(x);
  32. while (cur < offset) {
  33. lseek(fd, cur, SEEK_SET);
  34. cur += nproc * sizeof(x);
  35. read(fd, &x, sizeof(x));
  36. sum += x;
  37. }
  38. semop(semid, (struct sembuf[]){{i, -1, 0}}, 1);
  39. printf("%u\n", sum);
  40. fflush(stdout);
  41. if (i < nproc - 1) {
  42. semop(semid, (struct sembuf[]){{i + 1, 1, 0}}, 1);
  43. }
  44. _exit(0);
  45. }
  46. }
  47. semop(semid, (struct sembuf[]) {{0, 1, 0}}, 1);
  48. while(wait(NULL) > 0) {
  49. }
  50. semctl(semid, 0, IPC_RMID);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement