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