Index: res/res_musiconhold.c =================================================================== --- res/res_musiconhold.c (revision 226780) +++ res/res_musiconhold.c (working copy) @@ -1368,9 +1368,20 @@ { struct mohclass *class = obj; struct mohdata *member; + pthread_t tid = 0; ast_debug(1, "Destroying MOH class '%s'\n", class->name); + /* Kill the thread first, so it cannot restart the child process while the + * class is being destroyed */ + if (class->thread > 0) { + tid = class->thread; + class->thread = AST_PTHREADT_NULL; + pthread_cancel(tid); + /* We'll collect the exit status later, after we ensure all the readers + * are dead. */ + } + if (class->pid > 1) { char buff[8192]; int bytes, tbytes = 0, stime = 0, pid = 0; @@ -1404,12 +1415,6 @@ free(member); } - if (class->thread) { - pthread_cancel(class->thread); - pthread_join(class->thread, NULL); - class->thread = AST_PTHREADT_NULL; - } - if (class->filearray) { int i; for (i = 0; i < class->total_files; i++) { @@ -1418,6 +1423,11 @@ free(class->filearray); class->filearray = NULL; } + + /* Finally, collect the exit status of the monitor thread */ + if (tid > 0) { + pthread_join(tid, NULL); + } } static int moh_class_mark(void *obj, void *arg, int flags)