cosmopolitan/examples/forkrand.c

46 lines
1.6 KiB
C
Raw Permalink Normal View History

2020-06-15 14:18:57 +00:00
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
#include "libc/calls/calls.h"
#include "libc/log/check.h"
2020-06-15 14:18:57 +00:00
#include "libc/log/log.h"
#include "libc/nt/nt/process.h"
#include "libc/rand/rand.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/time/time.h"
2020-12-01 11:43:40 +00:00
noinline void dostuff(const char *s) {
int i, us;
2020-06-15 14:18:57 +00:00
srand(rand64()); /* seeds rand() w/ intel rdrnd, auxv, etc. */
for (i = 0; i < 5; ++i) {
us = rand() % 500000;
2020-06-15 14:18:57 +00:00
usleep(us);
2020-12-01 11:43:40 +00:00
printf("hello no. %u from %s %u [us=%d]\n", i, s, getpid(), us);
2020-06-15 14:18:57 +00:00
fflush(stdout);
}
}
int main(int argc, char *argv[]) {
int rc, child, wstatus;
CHECK_NE(-1, (child = fork()));
2020-06-15 14:18:57 +00:00
if (!child) {
/* child process */
2020-12-01 11:43:40 +00:00
dostuff("child");
2020-06-15 14:18:57 +00:00
return 0;
} else {
/* parent process */
2020-12-01 11:43:40 +00:00
dostuff("parent");
2020-06-15 14:18:57 +00:00
/* note: abandoned children become zombies */
CHECK_NE(-1, (rc = wait(&wstatus)));
2020-12-01 11:43:40 +00:00
CHECK_EQ(0, WEXITSTATUS(wstatus));
return 0;
2020-06-15 14:18:57 +00:00
}
}