| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
#include <usual/signal.h> |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
#ifdef WIN32 |
| 26 |
|
| 27 |
struct AlarmCtx { |
| 28 |
struct sigaction sa; |
| 29 |
HANDLE event; |
| 30 |
HANDLE thread; |
| 31 |
int secs; |
| 32 |
|
| 33 |
}; |
| 34 |
static volatile struct AlarmCtx actx; |
| 35 |
|
| 36 |
static DWORD WINAPI w32_alarm_thread(LPVOID arg) |
| 37 |
{ |
| 38 |
DWORD wres; |
| 39 |
unsigned msecs; |
| 40 |
|
| 41 |
loop: |
| 42 |
if (actx.secs > 0) { |
| 43 |
msecs = actx.secs * 1000; |
| 44 |
} else { |
| 45 |
msecs = INFINITE; |
| 46 |
} |
| 47 |
|
| 48 |
wres = WaitForSingleObject(actx.event, msecs); |
| 49 |
if (wres == WAIT_OBJECT_0) { |
| 50 |
goto loop; |
| 51 |
} else if (wres == WAIT_TIMEOUT) { |
| 52 |
actx.secs = 0; |
| 53 |
if (actx.sa.sa_handler) |
| 54 |
actx.sa.sa_handler(SIGALRM); |
| 55 |
goto loop; |
| 56 |
} else { |
| 57 |
Sleep(1000); |
| 58 |
goto loop; |
| 59 |
} |
| 60 |
return 0; |
| 61 |
} |
| 62 |
|
| 63 |
unsigned int alarm(unsigned int secs) |
| 64 |
{ |
| 65 |
actx.secs = secs; |
| 66 |
|
| 67 |
|
| 68 |
if (!actx.event) { |
| 69 |
actx.event = CreateEvent(NULL, FALSE, FALSE, NULL); |
| 70 |
if (!actx.event) |
| 71 |
return 0; |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
if (!actx.thread) { |
| 76 |
actx.thread = CreateThread(NULL, 0, w32_alarm_thread, NULL, 0, NULL); |
| 77 |
} else { |
| 78 |
SetEvent(actx.event); |
| 79 |
} |
| 80 |
return 0; |
| 81 |
} |
| 82 |
|
| 83 |
#endif |
| 84 |
|
| 85 |
#ifndef HAVE_SIGACTION |
| 86 |
int sigaction(int sig, const struct sigaction *sa, struct sigaction *old) |
| 87 |
{ |
| 88 |
#ifdef WIN32 |
| 89 |
if (sig == SIGALRM) { |
| 90 |
if (old) |
| 91 |
*old = actx.sa; |
| 92 |
if (sa) |
| 93 |
actx.sa = *sa; |
| 94 |
else |
| 95 |
actx.sa.sa_handler = NULL; |
| 96 |
return 0; |
| 97 |
} |
| 98 |
#endif |
| 99 |
old->sa_handler = signal(sig, sa->sa_handler); |
| 100 |
if (old->sa_handler == SIG_ERR) |
| 101 |
return -1; |
| 102 |
return 0; |
| 103 |
} |
| 104 |
#endif |
| 105 |
|
| 106 |
#ifdef WIN32 |
| 107 |
|
| 108 |
int kill(int pid, int sig) |
| 109 |
{ |
| 110 |
HANDLE hProcess; |
| 111 |
DWORD exitCode; |
| 112 |
int ret = 0; |
| 113 |
|
| 114 |
|
| 115 |
if (sig != 0) { |
| 116 |
errno = EINVAL; |
| 117 |
return -1; |
| 118 |
} |
| 119 |
|
| 120 |
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); |
| 121 |
if (hProcess == NULL) { |
| 122 |
if (GetLastError() == ERROR_INVALID_PARAMETER) |
| 123 |
ret = ESRCH; |
| 124 |
else |
| 125 |
ret = EPERM; |
| 126 |
} else { |
| 127 |
|
| 128 |
if (GetExitCodeProcess(hProcess, &exitCode)) { |
| 129 |
if (exitCode != STILL_ACTIVE) |
| 130 |
ret = ESRCH; |
| 131 |
} |
| 132 |
CloseHandle(hProcess); |
| 133 |
} |
| 134 |
|
| 135 |
if (ret) { |
| 136 |
errno = ret; |
| 137 |
return -1; |
| 138 |
} else |
| 139 |
return 0; |
| 140 |
} |
| 141 |
#endif |