void log_event(char *message) { FILE *file; struct tm *current_info; time_t current; char times[50]; int filedes; time(¤t); current_info = localtime(¤t); current = mktime(current_info); strftime(times,25,"%b %d %Y %H:%M",localtime(¤t)); filedes = open("event.log", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (filedes < 0) { fprintf(stderr, "Cannot Get Event Log File Descriptor\n"); exit(EXIT_FAILURE); } if(get_lock(filedes) < 0) { fprintf(stderr, "Cannot Obtain Event Log File Lock\n"); exit(EXIT_FAILURE); } file = fdopen(filedes, "a"); fprintf(file, "%s %s\n", times,message); release_lock(filedes); fclose(file); close(filedes); }
zx_status_t ProcessDispatcher::Suspend() { canary_.Assert(); LTRACE_ENTRY_OBJ; Guard<fbl::Mutex> guard{get_lock()}; // If we're dying don't try to suspend. if (state_ == State::DYING || state_ == State::DEAD) return ZX_ERR_BAD_STATE; DEBUG_ASSERT(suspend_count_ >= 0); suspend_count_++; if (suspend_count_ == 1) { for (auto& thread : thread_list_) { // Thread suspend can only fail if the thread is already dying, which is fine here // since it will be removed from this process shortly, so continue to suspend whether // the thread suspend succeeds or fails. zx_status_t status = thread.Suspend(); DEBUG_ASSERT(status == ZX_OK || thread.IsDyingOrDead()); } } return ZX_OK; }
zbar_symbol_type_t _zbar_decode_i25 (zbar_decoder_t *dcode) { i25_decoder_t *dcode25 = &dcode->i25; /* update latest character width */ dcode25->s10 -= get_width(dcode, 10); dcode25->s10 += get_width(dcode, 0); if(dcode25->character < 0 && !i25_decode_start(dcode)) return(ZBAR_NONE); if(--dcode25->element == 6 - dcode25->direction) return(i25_decode_end(dcode)); else if(dcode25->element) return(ZBAR_NONE); /* FIXME check current character width against previous */ dcode25->width = dcode25->s10; dprintf(2, " i25[%c%02d+%x]", (dcode25->direction) ? '<' : '>', dcode25->character, dcode25->element); /* lock shared resources */ if(!dcode25->character && get_lock(dcode, ZBAR_I25)) { dcode25->character = -1; dprintf(2, " [locked %d]\n", dcode->lock); return(ZBAR_PARTIAL); } unsigned char c = i25_decode10(dcode, 1); dprintf(2, " c=%x", c); if(c > 9 || ((dcode25->character >= BUFFER_MIN) && size_buf(dcode, dcode25->character + 2))) { dprintf(2, (c > 9) ? " [aborted]\n" : " [overflow]\n"); dcode->lock = 0; dcode25->character = -1; return(ZBAR_NONE); } dcode->buf[dcode25->character++] = c + '0'; c = i25_decode10(dcode, 0); dprintf(2, " c=%x", c); if(c > 9) { dprintf(2, " [aborted]\n"); dcode->lock = 0; dcode25->character = -1; return(ZBAR_NONE); } else { dprintf(2, "\n"); } dcode->buf[dcode25->character++] = c + '0'; dcode25->element = 10; return((dcode25->character == 2) ? ZBAR_PARTIAL : ZBAR_NONE); }
void LogToFile::Log( const openpal::LogEntry& arEntry ) { std::string time_str = platformtime::time_string(); std::lock_guard<std::mutex> get_lock(mMutex); if(!mLogFile.is_open()) { mLogFile.open(mLogName+std::to_string(mFileIndex)+".txt"); if(mLogFile.fail()) throw std::runtime_error("Failed to open log file"); } mLogFile <<time_str<<" - "<< FilterToString(arEntry.GetFilters())<<" - "<<arEntry.GetAlias(); if(mPrintLocation && !arEntry.GetLocation()) mLogFile << " - " << arEntry.GetLocation(); mLogFile << " - " << arEntry.GetMessage(); if(arEntry.GetErrorCode() != -1) mLogFile << " - " << arEntry.GetErrorCode(); mLogFile <<std::endl; if (mLogFile.tellp() > (int)mFileSizekB*1024) { mLogFile.close(); mFileIndex++; mFileIndex %= mNumFiles; } }
void increase_actors(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=NULL; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); while (lock->flags & 3) { pthread_cond_wait(&lock->cond, &lock->mutex); } lock->flags+=4; pthread_mutex_unlock(&lock->mutex); } }
void get_directory_exclusive(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=NULL; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); /* wait for the other actors to quit */ while (lock->flags>>3 > 1) { pthread_cond_wait(&lock->cond, &lock->mutex); } lock->flags+=2; pthread_mutex_unlock(&lock->mutex); } }
void Dispatcher::RemoveObserver(StateObserver* observer) { ZX_DEBUG_ASSERT(is_waitable()); Guard<fbl::Mutex> guard{get_lock()}; DEBUG_ASSERT(observer != nullptr); observers_.erase(*observer); }
/* * start_daemon() - check for jobs queued, check if the lock is free. If * so, start a daemon either by forking and execing or just execing * depending on the flag passed in. */ void start_daemon(int do_fork) { int lock; job_t **jobs = NULL; if ((jobs = job_list_append(NULL, NULL, NULL, SPOOL_DIR)) == NULL) return; list_iterate((void **)jobs, (VFUNC_T)job_free); free(jobs); close(lock = get_lock(MASTER_LOCK, 0)); if (lock < 0) return; if (do_fork == 0) { (void) execle("/usr/bin/lp", MASTER_NAME, NULL, NULL); syslog(LOG_ERR, "start_daemon() - execl: %m"); exit(-1); } else switch (fork()) { case -1: syslog(LOG_ERR, "start_daemon() - fork: %m"); exit(-1); /* NOTREACHED */ case 0: break; default: (void) execl("/usr/bin/lp", MASTER_NAME, NULL); syslog(LOG_ERR, "start_daemon() - execl: %m"); exit(-1); /* NOTREACHED */ } }
void ProcessDispatcher::RemoveThread(ThreadDispatcher* t) { LTRACE_ENTRY_OBJ; // ZX-880: Call RemoveChildProcess outside of |get_lock()|. bool became_dead = false; { // we're going to check for state and possibly transition below Guard<fbl::Mutex> guard{get_lock()}; // remove the thread from our list DEBUG_ASSERT(t != nullptr); thread_list_.erase(*t); // if this was the last thread, transition directly to DEAD state if (thread_list_.is_empty()) { LTRACEF("last thread left the process %p, entering DEAD state\n", this); SetStateLocked(State::DEAD); became_dead = true; } } if (became_dead) FinishDeadTransition(); }
zx_status_t ProcessDispatcher::AddThread(ThreadDispatcher* t, bool initial_thread, bool* suspended) { LTRACE_ENTRY_OBJ; Guard<fbl::Mutex> guard{get_lock()}; if (initial_thread) { if (state_ != State::INITIAL) return ZX_ERR_BAD_STATE; } else { // We must not add a thread when in the DYING or DEAD states. // Also, we want to ensure that this is not the first thread. if (state_ != State::RUNNING) return ZX_ERR_BAD_STATE; } // add the thread to our list DEBUG_ASSERT(thread_list_.is_empty() == initial_thread); thread_list_.push_back(t); DEBUG_ASSERT(t->process() == this); // If we're suspended, start this thread in suspended state as well. *suspended = (suspend_count_ > 0); if (initial_thread) SetStateLocked(State::RUNNING); return ZX_OK; }
void ProcessDispatcher::Kill() { LTRACE_ENTRY_OBJ; // ZX-880: Call RemoveChildProcess outside of |get_lock()|. bool became_dead = false; { Guard<fbl::Mutex> guard{get_lock()}; // we're already dead if (state_ == State::DEAD) return; if (state_ != State::DYING) { // If there isn't an Exit already in progress, set a nonzero exit // status so e.g. crashing tests don't appear to have succeeded. DEBUG_ASSERT(retcode_ == 0); retcode_ = -1; } // if we have no threads, enter the dead state directly if (thread_list_.is_empty()) { SetStateLocked(State::DEAD); became_dead = true; } else { // enter the dying state, which should trigger a thread kill. // the last thread exiting will transition us to DEAD SetStateLocked(State::DYING); } } if (became_dead) FinishDeadTransition(); }
void ProcessDispatcher::Exit(int64_t retcode) { LTRACE_ENTRY_OBJ; DEBUG_ASSERT(ProcessDispatcher::GetCurrent() == this); { Guard<fbl::Mutex> guard{get_lock()}; // check that we're in the RUNNING state or we're racing with something // else that has already pushed us until the DYING state DEBUG_ASSERT_MSG(state_ == State::RUNNING || state_ == State::DYING, "state is %s", StateToString(state_)); // Set the exit status if there isn't already an exit in progress. if (state_ != State::DYING) { DEBUG_ASSERT(retcode_ == 0); retcode_ = retcode; } // enter the dying state, which should kill all threads SetStateLocked(State::DYING); } ThreadDispatcher::GetCurrent()->Exit(); __UNREACHABLE; }
int main(int argc, char** argv) { fl_lock_t lock; int r; lock=0; printf("starting locking basic tests...\n"); r=try_lock(&lock); printf(" try_lock should return 0 ... %d\n", r); printf(" lock should be 1 now ... %d\n", lock); r=try_lock(&lock); printf(" tsl should return -1 ... %d\n", r); printf(" lock should still be 1 now ... %d\n", lock); release_lock(&lock); printf(" release_lock: lock should be 0 now ... %d\n", lock); printf("try_lock once more...\n"); r=try_lock(&lock); printf(" try_lock should return 0 ... %d\n", r); printf(" lock should be 1 now ... %d\n", lock); release_lock(&lock); get_lock(&lock); printf(" get_lock, lock should be 1 now ... %d\n", lock); printf("\ndone.\n"); return 0; }
void process_data() { std::unique_lock<std::mutex> lk( get_lock() ); /* (1) */ do_something(); std::cout << "owns_lock : " << lk.owns_lock() << std::endl; }
/* gateway-txs file contains the transactions we've already injected. */ static int read_gateway_txs(struct thash *thash) { struct protocol_double_sha *sha; struct stat st; int fd, i, num; fd = open("gateway-txs", O_RDWR); if (fd < 0) err(1, "Opening gateway file"); if (!get_lock(fd)) err(1, "Locking gateway file"); if (fstat(fd, &st) == -1) err(1, "Statting gateway file"); if (st.st_size % sizeof(*sha)) errx(1, "Gateway file invalid size %llu", (long long)st.st_size); num = st.st_size / sizeof(*sha); sha = tal_arr(NULL, struct protocol_double_sha, num); if (read(fd, sha, st.st_size) != st.st_size) err(1, "Reading gateway file"); for (i = 0; i < num; i++) thash_add(thash, sha + i); return fd; }
zx_status_t ProcessDispatcher::GetInfo(zx_info_process_t* info) { memset(info, 0, sizeof(*info)); State state; // retcode_ depends on the state: make sure they're consistent. { Guard<fbl::Mutex> guard{get_lock()}; state = state_; info->return_code = retcode_; // TODO: Protect with rights if necessary. info->debugger_attached = debugger_exception_port_ != nullptr; } switch (state) { case State::DEAD: case State::DYING: info->exited = true; __FALLTHROUGH; case State::RUNNING: info->started = true; break; case State::INITIAL: default: break; } return ZX_OK; }
static int svc_acquire(struct mutex *mutex) { int ret; if (get_lock(mutex)) { /* Success */ ret = 1; } else { /* Failure */ ret = 0; if (task_runnable(mutex->held_by) && (task_compare(mutex->held_by, curr_task) <= 0)) { task_switch(mutex->held_by); } else { /* If task was not runnable, it was either a period task * between runs, or it recently ended without releasing * the mutex. In that case, the kernel task will * release the mutex on its next run. */ task_switch(NULL); } } return ret; }
zx_status_t ProcessDispatcher::GetVmos( user_out_ptr<zx_info_vmo_t> vmos, size_t max, size_t* actual_out, size_t* available_out) { Guard<fbl::Mutex> guard{get_lock()}; if (state_ != State::RUNNING) { return ZX_ERR_BAD_STATE; } size_t actual = 0; size_t available = 0; zx_status_t s = GetProcessVmosViaHandles(this, vmos, max, &actual, &available); if (s != ZX_OK) { return s; } size_t actual2 = 0; size_t available2 = 0; DEBUG_ASSERT(max >= actual); s = GetVmAspaceVmos(aspace_, vmos.element_offset(actual), max - actual, &actual2, &available2); if (s != ZX_OK) { return s; } *actual_out = actual + actual2; *available_out = available + available2; return ZX_OK; }
/** * Open and lock the given file, ensuring that no deadlock will occur now or in the future over contention for this file. * If opening this file immediately would cause a deadlock, this method will block until the file can be safely opened and locked. * If the file cannot be opened, NULL is returned. * * Parameters: path - path to the file you wish to open and lock * mode - mode in which to open the file (same as the argument to fopen()) * Returns: A file pointer to the opened file or NULL on error */ FILE *sfs_fopen(char *path, char *mode) { mutex_lock(memory); // Turn claim edge to assignment edge node *resource = find_file_node(memory, path); node *process = find_process_node(memory, getpid()); if(resource == NULL || process == NULL) {\ mutex_unlock(memory); return NULL; } delete_out_edge(memory, process, resource); add_out_edge(memory, resource, process); // While a cycle exists while(cycle_exists(memory)) { // Convert back to claim edge delete_out_edge(memory, resource, process); add_out_edge(memory, process, resource); // Wait pthread_cond_wait(get_cycle_cond(memory), get_lock(memory)); // Add edge back delete_out_edge(memory, process, resource); add_out_edge(memory, resource, process); } // Upon getting the lock and assuring no cycle, open the file FILE *res = fopen(path, mode); resource->fp = res; mutex_unlock(memory); return res; }
zx_status_t ProcessDispatcher::SetExceptionPort(fbl::RefPtr<ExceptionPort> eport) { LTRACE_ENTRY_OBJ; bool debugger = false; switch (eport->type()) { case ExceptionPort::Type::DEBUGGER: debugger = true; break; case ExceptionPort::Type::PROCESS: break; default: DEBUG_ASSERT_MSG(false, "unexpected port type: %d", static_cast<int>(eport->type())); break; } // Lock |get_lock()| to ensure the process doesn't transition to dead // while we're setting the exception handler. Guard<fbl::Mutex> guard{get_lock()}; if (state_ == State::DEAD) return ZX_ERR_NOT_FOUND; if (debugger) { if (debugger_exception_port_) return ZX_ERR_ALREADY_BOUND; debugger_exception_port_ = eport; } else { if (exception_port_) return ZX_ERR_ALREADY_BOUND; exception_port_ = eport; } return ZX_OK; }
bool SqliteDatabase::execute(String sql, void *object, Sqlite3Callback callback, bool nothrow, String *err) const { if (!isLoaded()) throw std::runtime_error("db is not loaded"); boost::trim(sql); // lock always for now ScopedFileLock lock(get_lock(fullName), std::defer_lock); if (!read_only) lock.lock(); LOG_TRACE(logger, "Executing sql statement: " << sql); char *errmsg; String error; sqlite3_exec(db, sql.c_str(), callback, object, &errmsg); if (errmsg) { auto s = sql.substr(0, MAX_ERROR_SQL_LENGTH); if (sql.size() > MAX_ERROR_SQL_LENGTH) s += "..."; error = "Error executing sql statement:\n" + s + "\nError: " + errmsg; sqlite3_free(errmsg); if (nothrow) { if (errmsg && err) *err = error; } else throw std::runtime_error(error); } return error.empty(); }
void ProcessDispatcher::OnExceptionPortRemoval( const fbl::RefPtr<ExceptionPort>& eport) { Guard<fbl::Mutex> guard{get_lock()}; for (auto& thread : thread_list_) { thread.OnExceptionPortRemoval(eport); } }
void unlock_directory_exclusive(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=NULL; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); /* unset the first two bits */ if (lock->flags & 1) lock->flags-=1; if (lock->flags & 2) lock->flags-=2; pthread_cond_broadcast(&lock->cond); pthread_mutex_unlock(&lock->mutex); } }
fbl::RefPtr<ThreadDispatcher> ProcessDispatcher::LookupThreadById(zx_koid_t koid) { LTRACE_ENTRY_OBJ; Guard<fbl::Mutex> guard{get_lock()}; auto iter = thread_list_.find_if([koid](const ThreadDispatcher& t) { return t.get_koid() == koid; }); return fbl::WrapRefPtr(iter.CopyPointer()); }
void decrease_actors(struct notifyfshm_directory_struct *directory) { struct notifyfshm_lock_struct *lock=NULL; if (directory->shared_lock==(unsigned short) -1) { lock=notifyfshm_malloc_lock(); if (lock) directory->shared_lock=lock->index; } else { lock=get_lock(directory->shared_lock); } if (lock) { pthread_mutex_lock(&lock->mutex); lock->flags-=4; pthread_cond_broadcast(&lock->cond); pthread_mutex_unlock(&lock->mutex); } }
void nrnbbs_post_string(const char* key, const char* sval) { history("post", key, sval); get_lock(); FILE* f = fopen(fname(NRNBBS), "a"); fprintf(f, "%s\n%s\n", key, sval); FILE* f2 = fopen(fname(NOTIFY), "r"); char name[256]; int i, n, id[10]; n = 0; if (f2) { while( fgets(name, 256, f2) && n < 10) { name[strlen(name) - 1] = '\0'; fscanf(f2, "%d\n", &i); if (strcmp(name, key) == 0) { id[n++] = i; fprintf(f, "nrnbbs_notifying %s\n\n", key); } } fclose(f2); } fclose(f); release_lock(); for (i=0; i < n; ++i) { history(" notify", id[i]); kill(id[i], NOTIFY_SIGNAL); } }
void test_unique_lock_move_from_rvalue_on_construction() { boost::mutex m; boost::unique_lock<boost::mutex> l(get_lock(m)); BOOST_CHECK(l.owns_lock()); BOOST_CHECK(l.mutex()==&m); }
boolean nrnbbs_take_string(const char* key, char* sval) { history("take", key); get_lock(); boolean b = false; FILE* f = fopen(fname(NRNBBS), "r"); if (f != (FILE*)0) { char name[256], val[256]; FILE* f2 = fopen(fname(TMPFILE), "w"); while (fgets(name, 256, f)) { name[strlen(name) -1] = '\0'; if (name[0] == '\0') { continue; } fgets(val, 256, f); val[strlen(val) - 1] = '\0'; if (!b && strcmp(name, key) == 0) { history(" found", val); b = true; strcpy(sval, val); continue; } fprintf(f2, "%s\n%s\n", name, val); } fclose(f2); fclose(f); if (b) { rename(fname(TMPFILE), fname(NRNBBS)); } }else{ b = false; } release_lock(); return b; }
::DDS::InstanceHandle_t FooDataWriterImpl::register_w_timestamp ( const Foo & instance_data, ::DDS::InstanceHandle_t , const ::DDS::Time_t & source_timestamp ) { ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, guard, get_lock (), ::DDS::RETCODE_ERROR); ACE_Message_Block* marshalled; int is_new = 0; ::DDS::InstanceHandle_t handle; ::DDS::ReturnCode_t ret = this->get_or_create_instance_handle(handle, instance_data, is_new, marshalled, source_timestamp); if (ret != ::DDS::RETCODE_OK) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) ") ACE_TEXT("FooDataWriterImpl::register_w_timestamp, ") ACE_TEXT("register failed error=%d.\n"), ret)); } return handle; }
void IThread::awake() { MutexLock get_lock(this->_mutex); pthread_cond_signal(&(this->_cond)); //Logger::getInstance() << Logger::Info << Logger::PrintStdOut << "Removing thread " << this->m_pid << " from bed" << Logger::Flush; this->_asleep = false; }