/* Filename: dictionary.cpp Compile: g++ -O3 -o dictionary dictionary.cpp -lpthread * search for existence of a word in the dictionary * insert a word in the dictionary if it doesn't exist * delete a word from the dictionary ./dictionary {-insert | -search | -delete } The first execution of dictionary will act as a master for now. TODO: * modify the specs to handle how to terminate the program so we can clean up the lock file and FIFO file. author: tuan t. pham last update: 01/07/11 */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define LOCK(x) pthread_mutex_lock(&x) #define UNLOCK(x) pthread_mutex_unlock(&x) pthread_mutex_t mux0 = PTHREAD_MUTEX_INITIALIZER; #define FILE_LOCK "dictionary.lock" #define FILE_MODE O_WRONLY | O_CREAT | O_EXCL #define FIFO_NAME "dictionary.fifo" #define FIFO_MODE S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH // 0644 #define FIFO_WMODE O_WRONLY #define FIFO_RMODE O_RDONLY | O_NONBLOCK #define BUF_LEN (sizeof (struct inotify_event) + 16) bool checkFirstRun(); void processCmd(char** argv); void sendCmd(char** argv); void* sendCmdThr(void* arg); void setSigHandler(); // setup SIGUSR1 and SIGINT handler void sigHandler(int signo, siginfo_t *info, void* context); int main(int argc, char** argv) { // first run? if (checkFirstRun()) { setSigHandler(); // set USR1 handler processCmd(argv); } else { sendCmd(argv); } return 0; } /* checkFirstRun() * check whether we are the first execution by checking if the FILE_LOCK exists * ------------------------------------------------------- * errno | fd | wtd (what to do) * X | != -1 | return true * EEXIST| == -1 | return false * X | == -1 | print error to stderr and return false */ bool checkFirstRun() { bool ret = false; int fd = open(FILE_LOCK, FILE_MODE); if (-1 != fd) { if (-1 == mkfifo(FIFO_NAME, FIFO_MODE)) { cerr<<"Failed to create FIFO \""<