Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4. #include <sys/types.h>
  5. #include <stdlib.h>
  6. #include <fcntl.h>
  7. #include <string.h>
  8. #include <ctype.h>
  9. #include <stdint.h>
  10. #include <signal.h>
  11.  
  12. // анонимные каналы - средство взаимодействия РОДСТВЕННЫХ процессов
  13. // именованные каналы mkfifo "name" (ls -la)
  14. // int pipe(int fd[2]); // fd[0] - read, fd[1] - write
  15. // канал - буфер, по умолчания размера 4096
  16. // PIPE_BUF
  17. // ls -l|wc
  18.  
  19. sig_atomic_t flag = -1;
  20. void handler(int s) {
  21. if (s == SIGTERM) {
  22. flag = -2;
  23. } else {
  24. flag = s - SIGRTMIN;
  25. }
  26. }
  27.  
  28. int main(int argc, char *argv[]) {
  29. int n = 20;
  30. sigaction(SIGTERM, &(struct sigaction){ .sa_handler = handler,
  31. .sa_flags = SA_RESTART }, NULL);
  32.  
  33. int fd[20];
  34. long long sum[20];
  35. for (int i = 0; i < 20; ++i) {
  36. fd[i] = open(argv[i + 1], O_RDONLY, 0600);
  37. sum[i] = 0;
  38. sigaction(SIGRTMIN + i, &(struct sigaction){ .sa_handler = handler,
  39. .sa_flags = SA_RESTART }, NULL);
  40. }
  41.  
  42. char buf[16];
  43. long long cur;
  44. printf("%d\n", getpid());
  45. fflush(stdout);
  46. while (42) {
  47. if (flag == -1) {
  48. pause();
  49. }
  50. if (flag == -2) {
  51. for (int i = 0; i < n; ++i) {
  52. printf("%lld\n", sum[i]);
  53. if (fd[i] >= 0) {
  54. close(fd[i]);
  55. }
  56. }
  57. fflush(stdout);
  58. exit(0);
  59. }
  60. if (fd[flag] >= 0) {
  61. while (read(fd[flag], &buf, 16) == 16) {
  62. sscanf(buf, "%lld", &cur);
  63. sum[flag] += cur;
  64. }
  65. close(fd[flag]);
  66. fd[flag] = -1;
  67. flag = -1;
  68. }
  69. }
  70.  
  71. return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement