/* testfork.c * * Demonstrates that using area's for shared memory across fork() * fails on BeOS. * * Build using * * gcc -g -O0 -Wall -o testfork testfork.c * */ #include #include #include static int *x = NULL; static sem_id the_lock = -1; static int increment(int n) { snooze(1000); return n + 1; } #define KIDS 5 #define LOOPS 100 static void test_fork(void) { int j = 0; pid_t pids[KIDS]; *x = 0; printf("x is at %p\n", x); for (j = 0; j < KIDS; j++) { pids[j] = fork(); if (pids[j] < 0) { printf("Error in fork()\n"); exit(-1); } else if (pids[j] == 0) { int i; printf("child %8ld started: x = %p, *x = %d\n", find_thread(NULL), x, *x); for (i = 0; i < LOOPS; i++) { if (acquire_sem(the_lock) < 0) { printf("Failed to acquire the lock!\n"); exit(-1); } *x = increment(*x); if (release_sem(the_lock) < 0) { printf("Failed to release the lock!\n"); exit(-1); } } printf("child %8ld exiting: x = %p, *x = %d\n", find_thread(NULL), x, *x); exit(0); } } for (j = 0; j < KIDS; j++) { status_t ec = 0; wait_for_thread(pids[j], &ec); } printf("All children completed OK\n"); if (*x != KIDS * LOOPS) { printf("Test FAILED!\n"); printf("Should have seen *x = %d, instead got %d\n", KIDS * LOOPS, *x); } else printf("Test passed!!!!\n"); } int main(int argc, char **argv) { char *addr = NULL; area_id aid = create_area("x", (void**)&addr, B_ANY_ADDRESS, B_PAGE_SIZE, B_LAZY_LOCK, B_READ_AREA | B_WRITE_AREA); if (aid < 0) { printf("Failed to create an area!\n"); exit(-1); } x = (int *)addr; *x = 0; if ((the_lock = create_sem(1, "the_lock")) < 0) { printf("Failed to create the_lock :-(\n"); exit(-1); } test_fork(); delete_sem(the_lock); delete_area(aid); return 0; }