-rw-r--r-- | lib/scoreboard.cc | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/lib/scoreboard.cc b/lib/scoreboard.cc new file mode 100644 index 0000000..370cd93 --- a/dev/null +++ b/lib/scoreboard.cc | |||
@@ -0,0 +1,71 @@ | |||
1 | #ifdef USE_PCH | ||
2 | #include "pch.h" | ||
3 | #else | ||
4 | #include <sys/types.h> | ||
5 | #include <unistd.h> | ||
6 | #include <sys/ipc.h> | ||
7 | #include <sys/shm.h> | ||
8 | #include <cassert> | ||
9 | #include <string> | ||
10 | #include <konforka/exception.h> | ||
11 | using namespace std; | ||
12 | #include "sitecing/scoreboard.h" | ||
13 | #endif | ||
14 | |||
15 | namespace sitecing { | ||
16 | |||
17 | scoreboard::scoreboard() | ||
18 | : shmid(-1), slots(NULL) { | ||
19 | shmid = shmget(IPC_PRIVATE,MAX_SITECING_SCOREBOARD_SLOTS*sizeof(scoreboard_slot),IPC_CREAT|0600); | ||
20 | if(shmid<0) | ||
21 | throw konforka::exception(CODEPOINT,"failed to shmget()"); | ||
22 | slots = (scoreboard_slot*)shmat(shmid,NULL,0); | ||
23 | if(shmctl(shmid,IPC_RMID,NULL)) | ||
24 | throw konforka::exception(CODEPOINT,"failed to shmctl()"); | ||
25 | if(!slots) | ||
26 | throw konforka::exception(CODEPOINT,"failed to shmat()"); | ||
27 | for(int tmp=0;tmp<MAX_SITECING_SCOREBOARD_SLOTS;tmp++) | ||
28 | slots[tmp].state=scoreboard_slot::state_free; | ||
29 | } | ||
30 | scoreboard::~scoreboard() { | ||
31 | shmdt(slots); | ||
32 | } | ||
33 | |||
34 | int scoreboard::allocate_slot() { | ||
35 | for(int tmp=0;tmp<MAX_SITECING_SCOREBOARD_SLOTS;tmp++) { | ||
36 | if(slots[tmp].state==scoreboard_slot::state_free) { | ||
37 | slots[tmp].state=scoreboard_slot::state_allocated; | ||
38 | slots[tmp].pid=0; | ||
39 | return tmp; | ||
40 | } | ||
41 | } | ||
42 | throw konforka::exception(CODEPOINT,"out of scoreboard slots"); | ||
43 | } | ||
44 | void scoreboard::free_slot(int slot) { | ||
45 | assert(slot>=0 && slot<MAX_SITECING_SCOREBOARD_SLOTS); | ||
46 | if(slots[slot].state==scoreboard_slot::state_free) | ||
47 | throw konforka::exception(CODEPOINT,"freeing unallocated slot"); | ||
48 | slots[slot].state=scoreboard_slot::state_free; | ||
49 | } | ||
50 | |||
51 | scoreboard_slot *scoreboard::get_slot(int slot) { | ||
52 | assert(slot>=0 && slot<MAX_SITECING_SCOREBOARD_SLOTS); | ||
53 | return &slots[slot]; | ||
54 | } | ||
55 | int scoreboard::get_slot_by_pid(pid_t pid) { | ||
56 | for(int rv=0;rv<MAX_SITECING_SCOREBOARD_SLOTS;rv++) | ||
57 | if( (slots[rv].state!=scoreboard_slot::state_free) && (slots[rv].pid == pid) ) | ||
58 | return rv; | ||
59 | throw konforka::exception(CODEPOINT,"no such process"); | ||
60 | } | ||
61 | |||
62 | int scoreboard::count_slots(enum scoreboard_slot::_state state) { | ||
63 | int rv = 0; | ||
64 | for(int tmp=0;tmp<MAX_SITECING_SCOREBOARD_SLOTS;tmp++) { | ||
65 | if(slots[tmp].state==state) | ||
66 | rv++; | ||
67 | } | ||
68 | return rv; | ||
69 | } | ||
70 | |||
71 | } | ||