3e98d05eede0be3bb50655a448939d9a683d1c1e
[ossec-hids.git] / src / shared / wait_op.c
1 /* @(#) $Id$ */
2
3 /* Copyright (C) 2009 Trend Micro Inc.
4  * All rights reserved.
5  *
6  * This program is a free software; you can redistribute it
7  * and/or modify it under the terms of the GNU General Public
8  * License (version 2) as published by the FSF - Free Software
9  * Foundation
10  */
11
12
13 #include "shared.h"
14 #define LOCK_LOOP   5
15 int __wait_lock = 0;
16
17
18 /* Creates global lock */
19 void os_setwait()
20 {
21     FILE *fp = NULL;
22
23     /* For same threads. */
24     __wait_lock = 1;
25
26     
27     if(isChroot())
28     {
29         fp = fopen(WAIT_FILE, "w");
30     }
31     else
32     {
33         fp = fopen(WAIT_FILE_PATH, "w");
34     }
35
36     if(fp)
37     {
38         fprintf(fp, "l");
39         fclose(fp);
40     }
41
42     return;
43 }
44
45
46 /* Removes global lock */
47 void os_delwait()
48 {
49     __wait_lock = 0;
50     
51     if(isChroot())
52     {
53         unlink(WAIT_FILE);
54     }
55     else
56     {
57         unlink(WAIT_FILE_PATH);
58     }
59     return;
60 }
61
62
63
64 /* Check for the wait file. If present, wait.
65  * Works as a simple inter process lock (only the main
66  * process is allowed to lock).
67  */
68 #ifdef WIN32 
69 void os_wait()
70 {
71     if(!__wait_lock)
72         return;
73
74
75     /* Wait until the lock is gone. */
76     verbose(WAITING_MSG, __local_name);
77     while(1)
78     {
79         if(!__wait_lock)
80             break;
81
82         /* Sleep LOCK_LOOP seconds and check it lock is gone. */
83         sleep(LOCK_LOOP);
84     }
85
86
87     verbose(WAITING_FREE, __local_name);
88     return;
89
90 }
91 #else
92
93
94 void os_wait()
95 {
96     struct stat file_status;
97     
98
99     /* If the wait file is not present, keep going.
100      */
101     if(isChroot())
102     {
103         if(stat(WAIT_FILE, &file_status) == -1)
104             return;
105     }
106     else
107     {
108         if(stat(WAIT_FILE_PATH, &file_status) == -1)
109             return;
110     }
111     
112
113     /* Wait until the lock is gone. */
114     verbose(WAITING_MSG, __local_name);
115     while(1)
116     {
117         if(isChroot())
118         {
119             if(stat(WAIT_FILE, &file_status) == -1)
120                 break;
121         }
122         else
123         {
124             if(stat(WAIT_FILE_PATH, &file_status) == -1)
125                 break;
126         }
127
128         /* Sleep LOCK_LOOP seconds and check it lock is gone. */
129         sleep(LOCK_LOOP);
130     }
131
132     verbose(WAITING_FREE, __local_name);
133     return;
134 }
135 #endif
136
137
138 /* EOF */