1 /*
2  * Copyright (c) 2002, Intel Corporation. All rights reserved.
3  * Created by:  rolla.n.selbak REMOVE-THIS AT intel DOT com
4  * This file is licensed under the GPL license.  For the full content
5  * of this license, see the COPYING file at the top level of this
6  * source tree.
7  *
8  *  void pthread_cleanup_pop(int execution);
9  *
10  * Shall remove the routine at the top of the calling thread's cancelation cleanup stack and
11  * optionally invoke it (if execute is non-zero).
12  *
13  * STEPS:
14  * 1. Create a thread
15  * 2. The thread will push a cleanup handler routine, then call pthread_cleanup_pop, setting
16  *    'execution' to a non-zero value (meaning the cleanup handler should be executed)
17  * 3. Verify that the cleanup handler was called.
18  *
19  */
20 
21 #include <pthread.h>
22 #include <stdio.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include "posixtest.h"
26 
27 # define CLEANUP_NOTCALLED 0
28 # define CLEANUP_CALLED 1
29 
30 # define INTHREAD 0
31 # define INMAIN 1
32 
33 int sem1; 			/* Manual semaphore */
34 int cleanup_flag;
35 
36 /* Cleanup handler */
a_cleanup_func(void * flag_val)37 void a_cleanup_func(void *flag_val)
38 {
39 	cleanup_flag = (long)flag_val;
40 	return;
41 }
42 
43 /* Function that the thread executes upon its creation */
a_thread_func()44 void *a_thread_func()
45 {
46 	pthread_cleanup_push(a_cleanup_func, (void*) CLEANUP_CALLED);
47 	pthread_cleanup_pop(1);
48 
49 	/* Tell main that the thread has called the pop function */
50 	sem1 = INMAIN;
51 
52 	/* Wait for main to say it's ok to continue (as it checks to make sure that
53 	 * the cleanup handler was called */
54 	while (sem1 == INMAIN)
55 		sleep(1);
56 
57 	pthread_exit(0);
58 	return NULL;
59 }
60 
main()61 int main()
62 {
63 	pthread_t new_th;
64 
65 	/* Initializing values */
66 	sem1=INTHREAD;
67 	cleanup_flag = CLEANUP_NOTCALLED;
68 
69 	/* Create a new thread. */
70 	if(pthread_create(&new_th, NULL, a_thread_func, NULL) != 0)
71 	{
72 		perror("Error creating thread\n");
73 		return PTS_UNRESOLVED;
74 	}
75 
76 	/* Wait for thread to call the pthread_cleanup_pop */
77 	while(sem1==INTHREAD)
78 		sleep(1);
79 
80 	/* Check to verify that the cleanup handler was called */
81 	if(cleanup_flag != CLEANUP_CALLED)
82 	{
83 		printf("Test FAILED: Cleanup handler was not called\n");
84 		return PTS_FAIL;
85 	}
86 
87 	/* Tell thread it can keep going now */
88 	sem1=INTHREAD;
89 
90 	/* Wait for thread to end execution */
91 	if(pthread_join(new_th, NULL) != 0)
92 	{
93 		perror("Error in pthread_join()\n");
94 		return PTS_UNRESOLVED;
95 	}
96 
97 	printf("Test PASSED\n");
98 	return PTS_PASS;
99 }
100 
101 
102