1 /*
2  * %CopyrightBegin%
3  *
4  * Copyright Ericsson AB 1997-2016. All Rights Reserved.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * %CopyrightEnd%
19  */
20 #ifndef _ERL_TIMEOUT_H
21 #define _ERL_TIMEOUT_H
22 
23 #if !defined (__WIN32__) && !defined (VXWORKS)
24 
25 #include <setjmp.h>
26 
27 /*
28   use timeout like this (delay in ms):
29 
30   if (timeout(delay,fun(a,b,c))) {
31       printf("timeout occurred\n");
32   }
33   else {
34       ...
35   }
36 
37 If the call to fun() has not returned before 'delay' ms, it will be
38 interrupted and and timeout() will return a non-zero value.
39 
40 If fun() finishes before 'delay' ms, then timeout will return 0.
41 
42 If you need the return value from fun then assign it like this:
43 
44   if (timeout(delay,(x = fun(...)))) {
45   }
46 
47 These functions work by setting and catching SIGALRM, and although it
48 saves and restores the signal handler, it may not work in situations
49 where you are already using SIGALRM (this includes calls to sleep(3)).
50 
51 Note that although recursive calls to timeout will not fail, they may
52 not give the expected results. All invocations of timeout use the same
53 timer, which is set on entrance to timeout and restored on exit from
54 timeout. So although an inner call to timeout will restart the timer
55 for any pending outer call when it exits, any time that has already
56 elapsed against the outer timeout is forgotten. In addition, the alarm
57 signal will always go to the innermost (last called) timeout, which
58 may or may not be the intention in recursive cases.
59 
60 */
61 
62 #define JMPVAL 997 /* magic */
63 
64 #define timeout(ms,funcall) \
65       (setjmp(*timeout_setup(ms)) == JMPVAL ? -1: \
66        ((void)(funcall), timeout_cancel()))
67 
68 
69 /* don't call any of these directly - use the macro! see above! */
70 jmp_buf *timeout_setup(int ms);
71 int timeout_cancel(void);
72 
73 #endif /* WIN32 && VXWORKS */
74 
75 #endif  /* _ERL_TIMEOUT_H */
76