Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <sys/types.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <string.h>
- #include <ctype.h>
- #include <stdint.h>
- #include <signal.h>
- // анонимные каналы - средство взаимодействия РОДСТВЕННЫХ процессов
- // именованные каналы mkfifo "name" (ls -la)
- // int pipe(int fd[2]); // fd[0] - read, fd[1] - write
- // канал - буфер, по умолчания размера 4096
- // PIPE_BUF
- // ls -l|wc
- sig_atomic_t flag = -1;
- void handler(int s) {
- if (s == SIGTERM) {
- flag = -2;
- } else {
- flag = s - SIGRTMIN;
- }
- }
- int main(int argc, char *argv[]) {
- int n = 20;
- sigaction(SIGTERM, &(struct sigaction){ .sa_handler = handler,
- .sa_flags = SA_RESTART }, NULL);
- int fd[20];
- long long sum[20];
- for (int i = 0; i < 20; ++i) {
- fd[i] = open(argv[i + 1], O_RDONLY, 0600);
- sum[i] = 0;
- sigaction(SIGRTMIN + i, &(struct sigaction){ .sa_handler = handler,
- .sa_flags = SA_RESTART }, NULL);
- }
- char buf[16];
- long long cur;
- printf("%d\n", getpid());
- fflush(stdout);
- while (42) {
- if (flag == -1) {
- pause();
- }
- if (flag == -2) {
- for (int i = 0; i < n; ++i) {
- printf("%lld\n", sum[i]);
- if (fd[i] >= 0) {
- close(fd[i]);
- }
- }
- fflush(stdout);
- exit(0);
- }
- if (fd[flag] >= 0) {
- while (read(fd[flag], &buf, 16) == 16) {
- sscanf(buf, "%lld", &cur);
- sum[flag] += cur;
- }
- close(fd[flag]);
- fd[flag] = -1;
- flag = -1;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement