KAWASHIMA Takahiro | 9180c14 | 2020-03-13 21:54:06 +0900 | [diff] [blame] | 1 | #include <stdatomic.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <sys/mman.h> |
| 4 | #include <sys/types.h> |
| 5 | #include <sys/wait.h> |
| 6 | #include <unistd.h> |
| 7 | |
| 8 | #define CHILDREN 7 |
| 9 | |
| 10 | int main(int argc, char *argv[]) { |
| 11 | _Atomic int *sync = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, |
| 12 | MAP_SHARED | MAP_ANONYMOUS, -1, 0); |
| 13 | if (sync == MAP_FAILED) |
| 14 | return 1; |
| 15 | *sync = 0; |
| 16 | |
| 17 | for (int i = 0; i < CHILDREN; i++) { |
| 18 | pid_t pid = fork(); |
| 19 | if (!pid) { |
| 20 | // child |
| 21 | while (*sync == 0) |
| 22 | ; // wait the parent in order to call execl simultaneously |
| 23 | execl(argv[1], argv[1], NULL); |
| 24 | } else if (pid == -1) { |
| 25 | *sync = 1; // release all children |
| 26 | return 1; |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // parent |
| 31 | *sync = 1; // start the program in all children simultaneously |
| 32 | for (int i = 0; i < CHILDREN; i++) |
| 33 | wait(NULL); |
| 34 | |
| 35 | return 0; |
| 36 | } |