#include #include #include #include #include #include #include #include static void print_exit_status (int status) { if(WIFEXITED(status)) { printf("killed normal : status = %d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("killed by signal: status = %d\n", WEXITSTATUS(status)); } } static void * sleep_mostly (void * arg) { printf("thread starts spinning\n"); while (1) { sleep (1); printf ("thread alive\n"); } /* NOTREACHED */ return NULL; } static int do_fork (void) { pid_t pid = fork (); if (pid == 0) { /* child */ pthread_t th; int cr = pthread_create (&th, NULL, sleep_mostly, (void*)NULL); if (cr != 0) { fprintf (stderr, "Thread creation failed %s\n", strerror(cr)); exit (1); } sleep(3); pthread_exit (NULL); } else if (pid < 0) { fprintf (stderr, "Cannot fork!\n"); exit (1); } return pid; } static int test_wait_pid(void) { int pid = do_fork(); sleep(2); fprintf (stderr, "try to kill pid %d\n", pid); kill (pid, SIGKILL); int killed; int status; int n; for (n = 1; n < 9999; n++) { killed = waitpid (pid, &status, WNOHANG|WUNTRACED); if (killed != 0) break; } fprintf (stderr, "killed after %d waitpid calls\n", n); print_exit_status(status); if (killed != 0 && killed != pid) { fprintf (stderr, "Kill failed! waitpid returned %d\n", killed); exit (1); } return 0; } int main (int argc, char* argv[]) { int i = 0; do { printf ("test %d --------------------------------\n", i); test_wait_pid(); i++; } while ( i < 10); return 0; }