|
| 1 | +// Copyright 2024 Justine Alexandra Roberts Tunney |
| 2 | +// |
| 3 | +// Permission to use, copy, modify, and/or distribute this software for |
| 4 | +// any purpose with or without fee is hereby granted, provided that the |
| 5 | +// above copyright notice and this permission notice appear in all copies. |
| 6 | +// |
| 7 | +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL |
| 8 | +// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED |
| 9 | +// WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE |
| 10 | +// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL |
| 11 | +// DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR |
| 12 | +// PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER |
| 13 | +// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR |
| 14 | +// PERFORMANCE OF THIS SOFTWARE. |
| 15 | + |
| 16 | +#include <errno.h> |
| 17 | +#include <stdatomic.h> |
| 18 | +#include <stdio.h> |
| 19 | +#include <stdlib.h> |
| 20 | +#include <sys/mman.h> |
| 21 | +#include <sys/wait.h> |
| 22 | +#include <unistd.h> |
| 23 | + |
| 24 | +int main(int argc, char *argv[]) { |
| 25 | + int ws, rc; |
| 26 | + |
| 27 | + // create shared memory for synchronization |
| 28 | + atomic_int *ready = |
| 29 | + mmap(0, 4, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); |
| 30 | + |
| 31 | + if ((rc = waitpid(-1, &ws, WNOHANG)) != -1) |
| 32 | + return 1; |
| 33 | + if (errno != ECHILD) |
| 34 | + return 2; |
| 35 | + |
| 36 | + // create process |
| 37 | + int pid = fork(); |
| 38 | + if (pid == -1) |
| 39 | + return 3; |
| 40 | + if (!pid) { |
| 41 | + for (;;) |
| 42 | + if (*ready) |
| 43 | + break; |
| 44 | + _Exit(0); |
| 45 | + } |
| 46 | + |
| 47 | + // wait on process |
| 48 | + if ((rc = waitpid(pid, &ws, WNOHANG)) == -1) |
| 49 | + return 4; |
| 50 | + if (rc != 0) |
| 51 | + return 5; |
| 52 | + if (ws) |
| 53 | + return 6; |
| 54 | + |
| 55 | + // signal subprocess |
| 56 | + *ready = 1; |
| 57 | + |
| 58 | + if ((rc = waitpid(pid, &ws, 0)) == -1) |
| 59 | + return 7; |
| 60 | + if (rc != pid) |
| 61 | + return 8; |
| 62 | + if (ws) |
| 63 | + return 9; |
| 64 | + |
| 65 | + // wait again |
| 66 | + if ((rc = waitpid(pid, &ws, WNOHANG)) != -1) |
| 67 | + return 10; |
| 68 | + if (errno != ECHILD) |
| 69 | + return 11; |
| 70 | +} |
0 commit comments