As alk said, if you use CLONE_THREAD
you can not use wait()
to wait for your thread to finish.
A new thread created with CLONE_THREAD has the same parent process as the caller of clone() (i.e., like CLONE_PARENT), so that calls to getppid(2) return the same value for all of the threads in a thread group. When a CLONE_THREAD thread terminates, the thread that created it using clone() is not sent a SIGCHLD (or other termination) signal; nor can the status of such a thread be obtained using wait(2). (The thread is said to be detached.)
The man page also tells us:
After all of the threads in a thread group terminate the parent process of the thread group is sent a SIGCHLD (or other termination) signal.
So if you have to use CLONE_THREAD
you could use pause()
or some other signal handling mechanism to wait for the whole thread group to finish.
...
ctid = clone(childfun , stackptr+getpagesize() , CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND| CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID,NULL);
pause();
printf("exit\n");
}
If you dont need to create a new thread group (e.g. don't use CLONE_THREAD
), you can use wait()
as you are used to from 'normal' process handling:
...
ctid = clone(childfun , stackptr+getpagesize() , CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND |CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID,NULL);
ctid = waitpid( ctid, 0, 0 );
if ( ctid == -1 ){
perror( "waitpid" );
exit( 3 );
}
}
Hope this helps!