How collect thread exit status(using join) when cancelled - c

I am trying to cancel thread from caller or calle, but both are crashing the program
But if I join I am getting the exit status correct.
how to collect the exit status properly on pthread_cancel
man page says below
After a canceled thread has terminated, a join with that thread using
pthread_join(3) obtains PTHREAD_CANCELED as the thread's exit status.
(Joining with a thread is the only way to know that cancellation has
completed.)
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg);
int errNum = 3;
int main()
{
pthread_t t_id;
void *status;
// on success pthread_create return zero
if(pthread_create(&t_id,NULL,thread_func,NULL) != 0){
printf("thread creation failed\n");
return 0;
}
printf("thread created with id %u successfully\n",t_id);
// status will be collecting the pthread_exit value
// error numberis returned incase of error
// pthread_cancel(t_id);
if(pthread_join(t_id,&status) != 0){
printf("join failed\n");
}
printf("thread %u exited with code %d\n", t_id, *(int *)status);
return 0;
}
void *thread_func(void *arg)
{
printf("Inside thread_func :%u\n",pthread_self());
//the arguments of pthread_exit should not be from local space, as it will be collected in caller using join
//pthread_exit(&errNum);
// if we return it may cause seg fault as we are trying to print the value from ptr(status)
//return ;
pthread_cancel(pthread_self());
}

If a thread is cancelled (before it has terminated normally), then when you join it, you will receive PTHREAD_CANCELED as the thread's return value / exit status. That macro expands to the actual void * value that is returned, so you can compare the value you receive directly to that to judge whether the thread was cancelled. It generally is not a valid pointer, so you must not try to dereference it.
Example:
void *status;
// ...
if (pthread_join(t_id, &status) != 0) {
// pthread_join failed
} else if (status == PTHREAD_CANCELED) {
// successfully joined a thread that was cancelled
// 'status' MUST NOT be dereferenced
} else {
// successfully joined a thread that terminated normally
// whether 'status' may be dereferenced or how else it may be
// used depends on the thread
}
It is worth noting that the wording of the Linux manual page is a bit fast and loose. Threads do not have an "exit status" in the sense that processes do, and the actual POSIX specifications do not use the term in the context of threads. For example, the POSIX specifications for pthread_join() say:
On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr.
That's a bit of a mouthful compared to the Linux wording, but it is chosen to be very precise.
Note also that the choice of type void * here is intentional and useful. It is not merely an obtuse way to package an int. Through such a pointer, a thread can provide access to an object of any type, as may be useful for communicating information about the outcome of its computations. On the other hand, it is fairly common for threads to eschew that possibility and just return NULL. But if a thread did want to provide an integer code that way, then it would most likely provide an intvalue cast to type void *, rather than a pointer to an object of type int containing the chosen value. In that case, one would obtain the value by casting back to int, not by dereferencing the pointer.

Related

is there a isAlive method in C to check the status of a thread? [duplicate]

In my destructor I want to destroy a thread cleanly.
My goal is to wait for a thread to finish executing and THEN destroy the thread.
The only thing I found about querying the state of a pthread is pthread_attr_setdetachstate but this only tells you if your thread is:
PTHREAD_CREATE_DETACHED
PTHREAD_CREATE_JOINABLE
Both of those have nothing to do with whether the thread is still running or not.
How do you query a pthread to see if it is still running?
It sounds like you have two questions here:
How can I wait until my thread completes?
Answer: This is directly supported by pthreads -- make your thread-to-be-stopped JOINABLE (when it is first started), and use pthread_join() to block your current thread until the thread-to-be-stopped is no longer running.
How can I tell if my thread is still running?
Answer: You can add a "thread_complete" flag to do the trick:
Scenario: Thread A wants to know if Thread B is still alive.
When Thread B is created, it is given a pointer to the "thread_complete" flag address. The "thread_complete" flag should be initialized to NOT_COMPLETED before the thread is created. Thread B's entry point function should immediately call pthread_cleanup_push() to push a "cleanup handler" which sets the "thread_complete" flag to COMPLETED.
See details about cleanup handlers here: pthread cleanup handlers
You'll want to include a corresponding pthread_cleanup_pop(1) call to ensure that the cleanup handler gets called no matter what (i.e. if the thread exits normally OR due to cancellation, etc.).
Then, Thread A can simply check the "thread_complete" flag to see if Thread B has exited yet.
NOTE: Your "thread_complete" flag should be declared "volatile" and should be an atomic type -- the GNU compilers provide the sig_atomic_t for this purpose. This allows the two threads consistent access the same data without the need for synchronization constructs (mutexes/semaphores).
pthread_kill(tid, 0);
No signal is sent, but error checking is still performed so you can use that to check
existence of tid.
CAUTION: This answer is incorrect. The standard specifically prohibits passing the ID of a thread whose lifetime has ended. That ID might now specify a different thread or, worse, it might refer to memory that has been freed, causing a crash.
I think all you really need is to call pthread_join(). That call won't return until the thread has exited.
If you only want to poll to see whether the thread is still running or not (and note that is usually not what you should be wanting to do!), you could have the thread set a volatile boolean to false just before it exits... then your main-thread could read the boolean and if it's still true, you know the thread is still running. (if it's false, on the other hand, you know the thread is at least almost gone; it may still be running cleanup code that occurs after it sets the boolean to false, though, so even in this case you should still call pthread_join before trying to free any resources the thread might have access to)
There is not fully portable solution, look if your platform supports pthread_tryjoin_np or pthread_timedjoin_np. So you just check if thread can be joined (of course created with PTHREAD_CREATE_JOINABLE).
Let me note on the "winning" answer, which has a huge hidden flaw, and in some contexts it can lead to crashes. Unless you use pthread_join, it will coming up again and again. Assume you are having a process and a shared library. Call the library lib.so.
You dlopen it, you start a thread in it. Assume you don't want it join to it, so you set it detachable.
Process and shared lib's logic doing its work, etc...
You want to load out lib.so, because you don't need it any more.
You call a shutdown on the thread and you say, that you want to read a flag afterwards from your lib.so's thread, that it have finished.
You continue on another thread with dlclose, because you see, that you have saw, that the flag is now showing the thread as "finished"
dlclose will load out all stack and code related memory.
Whops, but dlclose does not stop threads. And you know, even when you are in the last line of the cleanup handler to set the "thread is finished" volatile atomic flag variable, you still have to return from a lot of methods on the stack, giving back values, etc. If a huge thread priority was given to #5+#6's thread, you will receive dlclose before you could REALLY stop on the thread. You will have some nice crashes sometimes.
Let me point out, that this is not a hipothetical problem, I had the same issue on our project.
I believe I've come up with a solution that at least works for Linux. Whenever I create a thread I have it save it's LWP (Light Weight Process ID) and assign it a unique name, eg.
int lwp = syscall(SYS_gettid);
prctl(PR_SET_NAME, (long)"unique name", 0, 0, 0);
Then, to check if the thread exists later I open /proc/pid/task/lwp/comm and read it. If the file exists and it's contents match the unique name I assigned, the thread exists. Note that this does NOT pass a possibly defunct/reused TID to any library function, so no crashes.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <pthread.h>
#include <sys/prctl.h>
#include <sys/file.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <syscall.h>
pthread_t subthread_tid;
int subthread_lwp;
#define UNIQUE_NAME "unique name"
bool thread_exists (pthread_t thread_id)
{
char path[100];
char thread_name[16];
FILE *fp;
bool thread_exists = false;
// If the /proc/<pid>/task/<lwp>/comm file exists and it's contents match the "unique name" the
// thread exists, and it's the original thread (TID has NOT been reused).
sprintf(path, "/proc/%d/task/%d/comm", getpid(), subthread_lwp);
fp = fopen(path, "r");
if( fp != NULL ) {
fgets(thread_name, 16, fp);
fclose(fp);
// Need to trim off the newline
thread_name[strlen(thread_name)-1] = '\0';
if( strcmp(UNIQUE_NAME, thread_name) == 0 ) {
thread_exists = true;
}
}
if( thread_exists ) {
printf("thread exists\n");
} else {
printf("thread does NOT exist\n");
}
return thread_exists;
}
void *subthread (void *unused)
{
subthread_lwp = syscall(SYS_gettid);
prctl(PR_SET_NAME, (long)UNIQUE_NAME, 0, 0, 0);
sleep(10000);
return NULL;
}
int main (int argc, char *argv[], char *envp[])
{
int error_number;
pthread_create(&subthread_tid, NULL, subthread, NULL);
printf("pthread_create()\n");
sleep(1);
thread_exists(subthread_tid);
pthread_cancel(subthread_tid);
printf("pthread_cancel()\n");
sleep(1);
thread_exists(subthread_tid);
error_number = pthread_join(subthread_tid, NULL);
if( error_number == 0 ) {
printf("pthread_join() successful\n");
} else {
printf("pthread_join() failed, %d\n", error_number);
}
thread_exists(subthread_tid);
exit(0);
}
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
void* thread1 (void* arg);
void* thread2 (void* arg);
int main()
{
pthread_t thr_id;
pthread_create(&thr_id, NULL, thread1, NULL);
sleep(10);
}
void* thread1 (void* arg)
{
pthread_t thr_id = 0;
pthread_create(&thr_id, NULL, thread2, NULL);
sleep(5);
int ret = 0;
if( (ret = pthread_kill(thr_id, 0)) == 0)
{
printf("still running\n");
pthread_join(thr_id, NULL);
}
else
{
printf("RIP Thread = %d\n",ret);
}
}
void* thread2 (void* arg)
{
// sleep(5);
printf("I am done\n");
}

pthread_join success = thread entirely executed?

I have a question about pthreads whith this little C source:
int calc = 0;
void func(void* data){
calc = 2 * 2;
return NULL;
}
int main(){
pthread_t t;
if(0==pthread_create(&t,NULL,func,NULL)){
if(0==pthread_join(t,NULL)){
printf("Result: %d\n",calc); // 4 ?
}
}
}
If pthread_join return success, is "func" always executed entirely ? (calc always equal 4 on printf ?).
The function pthread_join returns zero on success.
The documentation says that pthread_join blocks until the thread ends, so, with some applied logic one can easily conclude that the thread has ended.
On the other side, pthread_join fails in different ways:
When the handle is invalid: EINVAL
When a deadlock has been detected: EDEADLK
There is another possible error (recommended by the open group, but depending on the implementation): ESRCH, when it detects that the thread handle is being used past the end of the thread.
If you want to know more you may want to take a look at the documentation.

How do I get the error code from pthread_join()?

The following code fails to join pthreads and the message "join failed" is printed. How do I get more information about the failure and its cause?
pthread_t aThread[MAX_LENGTH];
int errCode[MAX_LENGTH];
char returnVal;
for(int i = 0; i < MAX_LENGTH; i++)
{
if((errCode[i] = pthread_create(&aThread[i], NULL, &findMatch, &fpArgs)) != 0)
printf("error creating thread %d\n", errCode[i]);
if(!pthread_join(aThread[i], (void**)&returnVal))
printf("join failed\n i is %d", i);
}
EDIT: actually join returned no error and I made a mistake. The if statment shouldn't have the ! because join returns a non-zero number if there is a problem which evaluates to true.
I pointed this out in comment, but it deserves amplification.
Your returnVal usage is wrong
The pthread_join api expects a void**, that is a pointer to a void*. Unlike void*, a void** is not equally universal. It is a pointer of specific type and as such you should only pass a likewise typed address. However, you're not using it anyway, so I would suggest for now you simply pass NULL. As-written, it is undefined behavior. And I can all-but-guarantee you sizeof(char), the writable size of the address you giving it, and sizeof(void*), the size it expects to have available, are not the same. Consider this instead for now:
pthread_join(aThread[i], NULL);
In case you're wondering what the use for that void** parameter is, it is a place to store void* return value from your thread-proc. Recall a pthread thread-proc looks like this:
void* thread_proc(void* args)
// ^----- this is what is stashed in the pthread_join second parameter
You're logic for failure testing is backwards
The pthread_join function returns 0 on success; not on failure.
You're not actually running concurrent threads
Thread concurrency simply means your threads run simultaneously. But yours do not. You start a thread, then wait for it to end, then start a thread, then wait for it to end, etc. This is literally no better (and in fact, actually worse) than simply calling a function. If you want your threads to run concurrently your logic should be styled like this:
pthread_t aThread[MAX_LENGTH];
int errCode[MAX_LENGTH] = {0};
for (int i = 0; i < MAX_LENGTH; i++)
{
if((errCode[i] = pthread_create(&aThread[i], NULL, &findMatch, &fpArgs)) != 0)
printf("error creating thread %d, error=%d\n", i, errCode[i]);
}
for (int i = 0; i < MAX_LENGTH; i++)
{
// note the check for errCode[i], which is only non-zero
// if the i'th thread failed to start
if(errCode[i] == 0)
{
errCode[i] = pthread_join(aThread[i], NULL))
if (errCode[i] != 0)
printf("error joining thread %d, error=%d\n", i, errCode[i]);
}
}
When the function fails (i.e. in any pthread call, a return code that is not equal to zero) it will set errno to the value of the reason for failure. There are a couple of ways to get the textual explanation of failure code.
int returnval;
if((returnval = pthread_join(aThread[i], (void**)&returnVal)) != 0)
{
printf("error joining thread: %s\n", strerror(returnval)); //1st optiop
perror("error joining thread:"); //2nd option
printf("error joining thread: %m\n"); //3rd option
}
(1) strerror will print the error string of the error value you pass it and is convenient for placing in printf statements.
(2) perror allows you to pass a little string that will print first and then it will automatically print the error description of whatever value errno is set to. You don't need to explicitly pass errno.
(3) There is a glibc extension to printf that provide a %m conversion specifier that acts like strerror but with a little less muss and fuss. This would be the least portable.
Once you get the description you can easily look into the man pages of the call that failed and they will provide greater hints as to why the call failed. Charlie Burns has posted the reasons pthread_join might fail.
Am I missing something? The return value tells you the error:
RETURN VALUES
If successful, the pthread_join() function will return zero. Otherwise,
an error number will be returned to indicate the error.
ERRORS
pthread_join() will fail if:
[EDEADLK] A deadlock was detected or the value of thread speci-
fies the calling thread.
[EINVAL] The implementation has detected that the value speci-
fied by thread does not refer to a joinable thread.
[ESRCH] No thread could be found corresponding to that speci-
fied by the given thread ID, thread.
More specifically::
int retVal = pthread_create(&myThread, NULL,myThreadFn, NULL);
printf("error joining thread: %d\n", retVal);
The pthread library does not set the errno variable upon error. The error code is returned by the function instead.
The online manual under Linux is quite clear for the pthread functions (e.g. man pthread_join) as the "RETURN VALUE" section generally contains something like:
RETURN VALUE
On success, pthread_join() returns 0; on error, it returns an error number.
If you need to output the error through functions like strerror(), strerror_r() or %m printf format (the latter is a GLIBC extension), you must use the return code of the failing service or update errno in the error branch:
if ((rc = pthread_join(...)) != 0) {
errno = rc;
fprintf(stderr, "pthread_join(): %m\n");
OR
fprintf(stderr, "pthread_join(): %m\n", strerror(errno)); // rc could be used without errno
OR
char err_buf[128];
errno = rc;
fprintf(stderr, "pthread_join(): %m\n", strerror_r(errno, err_buf, sizeof(err_buf))); // rc could be used without errno
Notes:
errno is thread-safe (it is located in the thread local storage). So, it is local to each thread
strerror_r() and %m should be used in multi-threaded environment as they are thread-safe (strerror() is not)

About pthread_kill() behavior

I have a question about pthread_kill() behavior.
Here's a small code I'm trying out:
void my_handler1(int sig)
{
printf("my_handle1: Got signal %d, tid: %lu\n",sig,pthread_self());
//exit(0);
}
void *thread_func1(void *arg)
{
struct sigaction my_action;
my_action.sa_handler = my_handler1;
my_action.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &my_action, NULL);
printf("thread_func1 exit\n");
}
void *thread_func2(void *arg)
{
int s;
s = pthread_kill(tid1_g,SIGUSR1);
if(s)
handle_error(s,"tfunc2: pthread_kill");
printf("thread_func2 exit\n");
}
int main()
{
int s = 0;
pthread_t tid1;
s = pthread_create(&tid1,NULL,thread_func1,NULL);
if(s)
handle_error(s,"pthread_create1");
tid1_g = tid1;
printf("tid1: %lu\n",tid1);
s = pthread_join(tid1,NULL);
if(s)
handle_error(s, "pthread_join");
printf("After join tid1\n");
pthread_t tid3;
s = pthread_create(&tid3,NULL,thread_func2,NULL);
if(s)
handle_error(s,"pthread_create3");
s = pthread_join(tid3,NULL);
if(s)
handle_error(s, "pthread_join3");
printf("After join tid3\n");
return 0;
}
The output I'm getting is:
tid1: 140269627565824
thread_func1 exit
After join tid1
my_handle1: Got signal 10, tid: 140269627565824
thread_func2 exit
After join tid3
So, even though I'm calling pthread_kill() on a thread that has already finished, the handler for that thread is still getting called. Isn't pthread_kill() supposed to return error(ESRCH) in case the thread doesn't exist?
Any use (*) of the pthread_t for a thread after its lifetime (i.e. after pthread_join successfully returns, or after the thread terminates in the detached state) results in undefined behavior. You should only expect ESRCH if the pthread_t is still valid, i.e. if you haven't joined the thread yet. Otherwise all bets are off.
Note: By "use" (*), I mean passing it to a pthread_ function in the standard library. As far as I can tell, merely assigning it to another pthread_t variable or otherwise passing it around between your own functions without "using" it doesn't result in UB.
According this SO thread says that passing a signal to an already dead thread (Only if the thread was joined or exited ) results in undefined behavior!
EDIT: Found a thread which clearly quotes the latest POSIX spec which indicates the behavior to be undefined. Thanks R.. for the correct pointers!
The question asked here (How to determine if a pthread is still alive) has been marked as duplicate as this question.
But I believe this post just clarifies the behavior of pthread_kill and confirms that it does not guarantee the correct behavior if pthread_kill is called with the ID which is no more valid. Hence pthread_kill can not be used to know if thread is alive or not as if the thread was joined earlier, the ID would not have been valid or would have been re-used and same is the case if its been detached as the resources may have got reclaimed if thread was terminated.
So to determine if thread is alive (question is specifically asked for joinable threads), I could think of only one solution as below:
Use some global data/memory which can be accessed by both the threads and store the return/exit status of thread-whose-status-needs-to-be-determined there. Other threads can check this data/locatin to get its status. (Obviously this assumes that thread exited normally i.e either joined or detached).
For e.g:
Have a global bool named as "bTerminated" initialized with "FALSE" and in
the handler function of this thread either make it as "TRUE" before
returning or modify it once it is returned to the caller (i.e where you have
called `pthread_join` for this thread). Check for this variable in any other
threads where you want to know if this thread is alive. Probably it will be
straight to implement such a logic which fits into your original code.

How do you query a pthread to see if it is still running?

In my destructor I want to destroy a thread cleanly.
My goal is to wait for a thread to finish executing and THEN destroy the thread.
The only thing I found about querying the state of a pthread is pthread_attr_setdetachstate but this only tells you if your thread is:
PTHREAD_CREATE_DETACHED
PTHREAD_CREATE_JOINABLE
Both of those have nothing to do with whether the thread is still running or not.
How do you query a pthread to see if it is still running?
It sounds like you have two questions here:
How can I wait until my thread completes?
Answer: This is directly supported by pthreads -- make your thread-to-be-stopped JOINABLE (when it is first started), and use pthread_join() to block your current thread until the thread-to-be-stopped is no longer running.
How can I tell if my thread is still running?
Answer: You can add a "thread_complete" flag to do the trick:
Scenario: Thread A wants to know if Thread B is still alive.
When Thread B is created, it is given a pointer to the "thread_complete" flag address. The "thread_complete" flag should be initialized to NOT_COMPLETED before the thread is created. Thread B's entry point function should immediately call pthread_cleanup_push() to push a "cleanup handler" which sets the "thread_complete" flag to COMPLETED.
See details about cleanup handlers here: pthread cleanup handlers
You'll want to include a corresponding pthread_cleanup_pop(1) call to ensure that the cleanup handler gets called no matter what (i.e. if the thread exits normally OR due to cancellation, etc.).
Then, Thread A can simply check the "thread_complete" flag to see if Thread B has exited yet.
NOTE: Your "thread_complete" flag should be declared "volatile" and should be an atomic type -- the GNU compilers provide the sig_atomic_t for this purpose. This allows the two threads consistent access the same data without the need for synchronization constructs (mutexes/semaphores).
pthread_kill(tid, 0);
No signal is sent, but error checking is still performed so you can use that to check
existence of tid.
CAUTION: This answer is incorrect. The standard specifically prohibits passing the ID of a thread whose lifetime has ended. That ID might now specify a different thread or, worse, it might refer to memory that has been freed, causing a crash.
I think all you really need is to call pthread_join(). That call won't return until the thread has exited.
If you only want to poll to see whether the thread is still running or not (and note that is usually not what you should be wanting to do!), you could have the thread set a volatile boolean to false just before it exits... then your main-thread could read the boolean and if it's still true, you know the thread is still running. (if it's false, on the other hand, you know the thread is at least almost gone; it may still be running cleanup code that occurs after it sets the boolean to false, though, so even in this case you should still call pthread_join before trying to free any resources the thread might have access to)
There is not fully portable solution, look if your platform supports pthread_tryjoin_np or pthread_timedjoin_np. So you just check if thread can be joined (of course created with PTHREAD_CREATE_JOINABLE).
Let me note on the "winning" answer, which has a huge hidden flaw, and in some contexts it can lead to crashes. Unless you use pthread_join, it will coming up again and again. Assume you are having a process and a shared library. Call the library lib.so.
You dlopen it, you start a thread in it. Assume you don't want it join to it, so you set it detachable.
Process and shared lib's logic doing its work, etc...
You want to load out lib.so, because you don't need it any more.
You call a shutdown on the thread and you say, that you want to read a flag afterwards from your lib.so's thread, that it have finished.
You continue on another thread with dlclose, because you see, that you have saw, that the flag is now showing the thread as "finished"
dlclose will load out all stack and code related memory.
Whops, but dlclose does not stop threads. And you know, even when you are in the last line of the cleanup handler to set the "thread is finished" volatile atomic flag variable, you still have to return from a lot of methods on the stack, giving back values, etc. If a huge thread priority was given to #5+#6's thread, you will receive dlclose before you could REALLY stop on the thread. You will have some nice crashes sometimes.
Let me point out, that this is not a hipothetical problem, I had the same issue on our project.
I believe I've come up with a solution that at least works for Linux. Whenever I create a thread I have it save it's LWP (Light Weight Process ID) and assign it a unique name, eg.
int lwp = syscall(SYS_gettid);
prctl(PR_SET_NAME, (long)"unique name", 0, 0, 0);
Then, to check if the thread exists later I open /proc/pid/task/lwp/comm and read it. If the file exists and it's contents match the unique name I assigned, the thread exists. Note that this does NOT pass a possibly defunct/reused TID to any library function, so no crashes.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <pthread.h>
#include <sys/prctl.h>
#include <sys/file.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <syscall.h>
pthread_t subthread_tid;
int subthread_lwp;
#define UNIQUE_NAME "unique name"
bool thread_exists (pthread_t thread_id)
{
char path[100];
char thread_name[16];
FILE *fp;
bool thread_exists = false;
// If the /proc/<pid>/task/<lwp>/comm file exists and it's contents match the "unique name" the
// thread exists, and it's the original thread (TID has NOT been reused).
sprintf(path, "/proc/%d/task/%d/comm", getpid(), subthread_lwp);
fp = fopen(path, "r");
if( fp != NULL ) {
fgets(thread_name, 16, fp);
fclose(fp);
// Need to trim off the newline
thread_name[strlen(thread_name)-1] = '\0';
if( strcmp(UNIQUE_NAME, thread_name) == 0 ) {
thread_exists = true;
}
}
if( thread_exists ) {
printf("thread exists\n");
} else {
printf("thread does NOT exist\n");
}
return thread_exists;
}
void *subthread (void *unused)
{
subthread_lwp = syscall(SYS_gettid);
prctl(PR_SET_NAME, (long)UNIQUE_NAME, 0, 0, 0);
sleep(10000);
return NULL;
}
int main (int argc, char *argv[], char *envp[])
{
int error_number;
pthread_create(&subthread_tid, NULL, subthread, NULL);
printf("pthread_create()\n");
sleep(1);
thread_exists(subthread_tid);
pthread_cancel(subthread_tid);
printf("pthread_cancel()\n");
sleep(1);
thread_exists(subthread_tid);
error_number = pthread_join(subthread_tid, NULL);
if( error_number == 0 ) {
printf("pthread_join() successful\n");
} else {
printf("pthread_join() failed, %d\n", error_number);
}
thread_exists(subthread_tid);
exit(0);
}
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
void* thread1 (void* arg);
void* thread2 (void* arg);
int main()
{
pthread_t thr_id;
pthread_create(&thr_id, NULL, thread1, NULL);
sleep(10);
}
void* thread1 (void* arg)
{
pthread_t thr_id = 0;
pthread_create(&thr_id, NULL, thread2, NULL);
sleep(5);
int ret = 0;
if( (ret = pthread_kill(thr_id, 0)) == 0)
{
printf("still running\n");
pthread_join(thr_id, NULL);
}
else
{
printf("RIP Thread = %d\n",ret);
}
}
void* thread2 (void* arg)
{
// sleep(5);
printf("I am done\n");
}

Resources