Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <stdlib.h>
- #include <sys/shm.h>
- #include <errno.h>
- #include <sys/wait.h>
- #include <fcntl.h>
- enum { BASE = 10, INIT = 123456 };
- int main(int argc, char *argv[]) {
- setbuf(stdin, NULL);
- int nproc = strtol(argv[2], NULL, BASE);
- key_t key = INIT;
- int semid = semget(key, nproc, 0666 | IPC_CREAT);
- if (semid < 0) {
- exit(errno);
- }
- pid_t p;
- u_int32_t x;
- int fd = open(argv[1], O_RDONLY);
- for (int i = 0; i < nproc; ++i) {
- if ((p = fork()) == -1) {
- exit(errno);
- }
- if (!p) {
- u_int32_t sum = 0;
- off_t offset = lseek(fd, 0, SEEK_END);
- off_t cur = i * sizeof(x);
- while (cur < offset) {
- lseek(fd, cur, SEEK_SET);
- cur += nproc * sizeof(x);
- read(fd, &x, sizeof(x));
- sum += x;
- }
- semop(semid, (struct sembuf[]){{i, -1, 0}}, 1);
- printf("%u\n", sum);
- fflush(stdout);
- if (i < nproc - 1) {
- semop(semid, (struct sembuf[]){{i + 1, 1, 0}}, 1);
- }
- _exit(0);
- }
- }
- semop(semid, (struct sembuf[]) {{0, 1, 0}}, 1);
- while(wait(NULL) > 0) {
- }
- semctl(semid, 0, IPC_RMID);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement