Example #1
0
 MutexImpementation::~MutexImpementation(void) {
     pthread_mutex_destroy(&Pmutex);
 }
Example #2
0
 Mutex::~Mutex() {
     pthread_mutex_destroy(&mutex);
 }
Example #3
0
File: mscli.c Project: bigclean/moc
void mssync_destroy(struct mssync *s)
{
    pthread_mutex_destroy(&(s->lock));
}
QMutexPrivate::~QMutexPrivate()
{
    report_error(pthread_cond_destroy(&cond), "QMutex", "cv destroy");
    report_error(pthread_mutex_destroy(&mutex), "QMutex", "mutex destroy");
}
Example #5
0
static void avpacket_queue_end(AVPacketQueue *q)
{
    avpacket_queue_flush(q);
    pthread_mutex_destroy(&q->mutex);
    pthread_cond_destroy(&q->cond);
}
Example #6
0
int main(int argc, char *argv[])
{
	int timeout = 0;
	sp_error error;
	int notify_cmdline = 0;
	int notify_events = 0;
	struct timespec ts;
	
	(void)argc;
	(void)argv;

	pthread_mutex_init(&g_notify_mutex, NULL);
	pthread_cond_init(&g_notify_cond, NULL);
	session_init();
	cmd_init(cmd_notify);
	
	do {
		clock_gettime(CLOCK_REALTIME, &ts);
		ts.tv_sec += timeout / 1000;
		ts.tv_nsec += (timeout % 1000) * 1E6;
		if (ts.tv_nsec > 1E9) {
			ts.tv_sec++;
			ts.tv_nsec -= 1E9;
		}

		pthread_mutex_lock(&g_notify_mutex);
		pthread_cond_timedwait(&g_notify_cond, &g_notify_mutex, &ts);
		notify_cmdline = g_notify_cmdline;
		notify_events = g_notify_events;
		g_notify_cmdline = 0;
		g_notify_events = 0;
		pthread_mutex_unlock(&g_notify_mutex);
		if (notify_cmdline) {
			cmd_process();
		}

		if (notify_events) {
			do {
				error = sp_session_process_events(g_session, &timeout);
				if (error != SP_ERROR_OK)
					fprintf(stderr, "error processing events: %s\n",
							sp_error_message(error));
			} while (timeout == 0);
		}

	} while (!is_program_finished());

	session_logout();
	while (session_is_logged_in()) {
       		clock_gettime(CLOCK_REALTIME, &ts);
		ts.tv_sec += 1;

		pthread_mutex_lock(&g_notify_mutex);
		pthread_cond_timedwait(&g_notify_cond, &g_notify_mutex, &ts);
		notify_events = g_notify_events;
		g_notify_events = 0;
		pthread_mutex_unlock(&g_notify_mutex);
		if (notify_events) {
			do {
				error = sp_session_process_events(g_session, &timeout);
				if (error != SP_ERROR_OK)
					fprintf(stderr, "error processing events: %s\n",
							sp_error_message(error));
			} while (timeout == 0);
		}
	}

	session_release();
	cmd_destroy();

	pthread_mutex_destroy(&g_notify_mutex);
	pthread_cond_destroy(&g_notify_cond);

	return 0;

}
Example #7
0
VCOS_STATUS_T vcos_timer_create(VCOS_TIMER_T *timer,
                                const char *name,
                                void (*expiration_routine)(void *context),
                                void *context)
{
   pthread_mutexattr_t lock_attr;
   VCOS_STATUS_T result = VCOS_SUCCESS;
   int settings_changed_initialized = 0;
   int lock_attr_initialized = 0;
   int lock_initialized = 0;

   (void)name;

   vcos_assert(timer);
   vcos_assert(expiration_routine);

   memset(timer, 0, sizeof(VCOS_TIMER_T));

   timer->orig_expiration_routine = expiration_routine;
   timer->orig_context = context;

   /* Create conditional variable for notifying the timer's thread
    * when settings change.
    */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_cond_init(&timer->settings_changed, NULL);
      if (rc == 0)
         settings_changed_initialized = 1;
      else
         result = vcos_pthreads_map_error(rc);
   }

   /* Create attributes for the lock (we want it to be recursive) */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_mutexattr_init(&lock_attr);
      if (rc == 0)
      {
         pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE);
         lock_attr_initialized = 1;
      }
      else
      {
         result = vcos_pthreads_map_error(rc);
      }
   }

   /* Create lock for the timer structure */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_mutex_init(&timer->lock, &lock_attr);
      if (rc == 0)
         lock_initialized = 1;
      else
         result = vcos_pthreads_map_error(rc);
   }

   /* Lock attributes are no longer needed */
   if (lock_attr_initialized)
      pthread_mutexattr_destroy(&lock_attr);

   /* Create the underlying thread */
   if (result == VCOS_SUCCESS)
   {
      int rc = pthread_create(&timer->thread, NULL, _timer_thread, timer);
      if (rc != 0)
         result = vcos_pthreads_map_error(rc);
   }

   /* Clean up if anything went wrong */
   if (result != VCOS_SUCCESS)
   {
      if (lock_initialized)
         pthread_mutex_destroy(&timer->lock);

      if (settings_changed_initialized)
         pthread_cond_destroy(&timer->settings_changed);
   }

   return result;
}
Example #8
0
/*====================================================================*/
int agent(int curAvatar, int nAvatars, int xlen, int ylen, char *hostname, key_t k,
                uint32_t port, int algo)
{
        int shmid;
        int s;
        char *outstring;
        WorldMap *globalmap;
        AM_Message outMessage;
        AM_Message inMessage;
        XYPos pos[AM_MAX_AVATAR];
        Direction movdir;
        int iterations = 0;
        int i;
        bool firstMove = true;
        int fd_log;
        LogMessage lmsg;
        float pknown;

        /* makes named pipe to logger */
        if (mkfifo(FIFO_NAME, 0666) == -1) {
                if (errno != EEXIST) {
                        perror("mkfifo");
                        return -1;
                }
        }

        fd_log = open(FIFO_NAME, O_WRONLY);
        if (fd_log == -1) {
                fprintf(stderr, "Failed to connect to log process\n");
                perror("open");
                return -1;
        }

        LOG(lmsg, fd_log, LVL_VERB, "%d connected to server", curAvatar);

        /* start with nonsense values to pos so we never assume we have a wall in front
         * of us on the first turn
         */
        for (i = 0; i < nAvatars; i++) {
                pos[i].x = AM_MAX_GRID_SIZE + 1;
                pos[i].y = AM_MAX_GRID_SIZE + 1;
        }

        /* start facing North */
        movdir = N;

        /* get shared memory */
        if ((shmid = shmget(k, sizeof(WorldMap), 0644 | IPC_CREAT)) == -1) {
                perror("shmget");
                LOG(lmsg, fd_log, LVL_FATAL, "Could not get id for shared memory: %s",\
                        strerror(errno));
        }

        /* attach to the segment and get a pointer to it */
        globalmap = shmat(shmid, (void *)0, 0);
        if (globalmap == (WorldMap *)(-1)) {
                perror("shmat");
                shmctl(shmid, IPC_RMID, NULL);
                fprintf(stderr, "Could not attach to shared memory\n");
                return (-1);
        }

        /* Avatar 0 initialize global map */
        if (curAvatar == 0) {
                LOG(lmsg, fd_log, LVL_VERB, "initializing global worldmap%s", "");
                globalmap->xlen = xlen;
                globalmap->ylen = ylen;
                initWorldMap(globalmap);
        } else {
                sleep(1); /* allow time for the log file to be initialized */
        }

        /* connect to the server and send avatar ready message */
        s = connectToServer(hostname, port);
        if (s < 0) {
                LOG(lmsg, fd_log, LVL_INFO, "Avatar %d Could not connect to server",
                                curAvatar+1);
                shmctl(shmid, IPC_RMID, NULL);
                return -1;
        }

        memset(&outMessage, 0, sizeof(outMessage));
        outMessage.type = AM_AVATAR_READY;
        outMessage.avatar_ready.AvatarId = curAvatar;
        sendAMMessage(s, outMessage);

        /* main agent loop */
        do {
                /* Get the next message from the server */
                inMessage = receiveAMMessage(s);
                if (IS_AM_ERROR(inMessage.type)) {
                        if (inMessage.type & AM_AVATAR_OUT_OF_TURN)
                                continue;
                        printAMError(fd_log, inMessage.type);
                        shmctl(shmid, IPC_RMID, NULL);
                        return -1;
                }
                /* if the message is not the right type */
                if (!(inMessage.type & AM_AVATAR_TURN))
                        continue;

                /* if it is our turn */
                if (inMessage.avatar_turn.TurnId == curAvatar) {
                        pthread_mutex_lock(&globalmap->mapMutex);
                        /* Get our next move */
                        movdir = getNextMove(*globalmap, inMessage.avatar_turn.Pos,
                                        movdir, pos[curAvatar], nAvatars, curAvatar,
                                        algo);

                        /* initialize outMessage */
                        memset(&outMessage, 0, sizeof(outMessage));
                        outMessage.type = AM_AVATAR_MOVE;
                        outMessage.avatar_move.AvatarId = curAvatar;
                        outMessage.avatar_move.Direction = dirToMoveDir(movdir);
                        sendAMMessage(s, outMessage);

                        iterations++;
                        /* Avatar 0 counts iterations */
                        if (curAvatar == 0) {
				fprintf(stdout, "\033[2J\033[1;1H");
                                printf("iteration %d\n", iterations);
                                outstring = serializeWorldMap(*globalmap, nAvatars,
                                                inMessage.avatar_turn.Pos);
                                /* Print to stdout */
                                fprintf(stdout, "%s\n", outstring);
                                free(outstring);
                                if (algo == 2) {
                                        if (!(connectedToAll(*globalmap,
                                                                        pos[0], nAvatars))) {
                                                pknown = percentKnown(*globalmap, nAvatars);
                                        }
                                        fprintf(stdout, "percent known %.1f %%\n",
                                                        pknown*100);
                                }

                                for (i = 0; i < nAvatars; i++) {
                                        LOG(lmsg, fd_log, LVL_INFO,
                                                        "avatar %d (% 3d,% 3d) -> "
                                                        "(% 3d,% 3d)", i+1, (int)pos[i].x,
                                                        (int)pos[i].y,
                                                        (int)inMessage.avatar_turn.Pos[i].x,
                                                        (int)inMessage.avatar_turn.Pos[i].y);
                                }
                        }
                        /* Update our position */
                        for (i = 0; i < nAvatars; i++)
                                pos[i] = inMessage.avatar_turn.Pos[i];
                } else if (inMessage.avatar_turn.TurnId ==
                                (curAvatar + 1)%nAvatars && !firstMove) {
                        /* Update with results of previous move */
                        if (inMessage.type & AM_AVATAR_TURN)
                                updateWorldMap(globalmap, pos[curAvatar], movdir, inMessage,
                                                curAvatar, nAvatars, algo);
                        pthread_mutex_unlock(&globalmap->mapMutex);
                }
                firstMove = false;
        } while (!(inMessage.type & AM_MAZE_SOLVED) &&
                        !(inMessage.type == AM_TOO_MANY_MOVES));


        /* Detach and (if no other process is connected) deallocate shared memory */
        shmctl(shmid, IPC_RMID, NULL);
        close(s);

        if (curAvatar == 0) {
                if (inMessage.type & AM_MAZE_SOLVED) {
                        printf("Moves to solve: %" PRIu32, inMessage.maze_solved.nMoves);
                        printf("\n");
                        printf("Size = %dx%d\n", xlen, ylen);
                        printf("Algorithm = %d\n", algo);
                        printf("# of Avatars = %d\n", nAvatars);

                        /* print to log */
                        LOG(lmsg, fd_log, LVL_INFO, "Moves to Solve: %" PRIu32,
                                        inMessage.maze_solved.nMoves);
                        LOG(lmsg, fd_log, LVL_INFO, "Hash: %" PRIu32,
                                        inMessage.maze_solved.Hash);

                } else {
                        LOG(lmsg, fd_log, LVL_INFO, "Maze not solved after ~%d moves",
                                        iterations * nAvatars);
                        memset(&lmsg, 0, sizeof(lmsg));
                }
        }
        sleep(1);
        close(fd_log);
        unlink(FIFO_NAME);
        pthread_mutex_destroy(&globalmap->mapMutex);
        return 0;
}
Example #9
0
 ~PosixMutex() {
   pthread_mutex_destroy(&mutex);
 }
int main (void) {

    int screen;			// which screen

    /* open connection with the server */
    display = XOpenDisplay(NULL);
    if(display == NULL) {
        fprintf(stderr, "cannot open display\n");
        return 0;
    }

    screen = DefaultScreen(display);

    /* set window position */
    int x = 0;
    int y = 0;

    /* border width in pixels */
    int border_width = 0;

    /* create window */
    window = XCreateSimpleWindow(display, RootWindow(display, screen), x, y,
        width, height, border_width,
            BlackPixel(display, screen), WhitePixel(display, screen));

    /* create graph */
    XGCValues values;
    long valuemask = 0;

    gc = XCreateGC(display, window, valuemask, &values);
    //XSetBackground (display, gc, WhitePixel (display, screen));
    XSetForeground (display, gc, BlackPixel (display, screen));
    XSetBackground(display, gc, 0X0000FF00);
    XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound);

    /* map(show) the window */
    XMapWindow(display, window);
    XSync(display, 0);

    pthread_t threads[width];
    pthread_attr_t attr;

    /* 1. Initialize mutex variable objects. */
    pthread_mutex_init(&mutex, NULL);
    pthread_mutex_init(&ptr_mutex, NULL);

    /* For portability, explicitly create threads in a joinable state. */
    struct timespec t1, t2;
    clock_gettime(CLOCK_REALTIME, &t1);

    int i, j;
    long t;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    for (t=0; t<40; t++)
        pthread_create(&threads[t], &attr, draw_mandelbrot, (void *) t);

    /* Wait for all threads to complete. */
    for (i=0; i<40; i++)
        pthread_join(threads[i], NULL);

    /* Clean up and exit. */
    pthread_attr_destroy(&attr);
    pthread_mutex_destroy(&mutex);
    pthread_mutex_destroy(&ptr_mutex);

    /* end of record */
    clock_gettime(CLOCK_REALTIME, &t2);
    double timedif = 1000000*(t2.tv_sec-t1.tv_sec)+(t2.tv_nsec-t1.tv_nsec)/1000;
    printf("It took %.5lf seconds to finish dynamic pthread calculation.\n", timedif/1000000);
    printf("Going into sleep...\n");

    XFlush(display);
    sleep(3);
    return 0;
}
Example #11
0
JNIEXPORT void JNI_OnUnload(JavaVM *jvm, void *reserved)
{
    ijkmp_global_uninit();

    pthread_mutex_destroy(&g_clazz.mutex);
}
Example #12
0
void
sbmtx_free(sbmtx_t *mtx)
{
    pthread_mutex_destroy(&mtx->mtx);
    ckd_free(mtx);
}
Example #13
0
Serial_Port::
~Serial_Port()
{
	// destroy mutex
	pthread_mutex_destroy(&lock);
}
int
dcethread_mutex_destroy(dcethread_mutex *mutex)
{
    return dcethread__set_errno(pthread_mutex_destroy((pthread_mutex_t*) &mutex->mutex));
}
Example #15
0
cMutex::~cMutex()
{
  pthread_mutex_destroy(&mutex);
  printf("mutex destroy returned %d:%s\n",errno,strerror(errno));
}
/**
 * @brief OMX SwVdec queue destructor.
 */
omx_swvdec_queue::~omx_swvdec_queue()
{
    pthread_mutex_destroy(&m_mutex);
}
Example #17
0
unsigned int One2OneChannel::unref()
{
    // atomic variable operation provided by gcc
    unsigned int ref = __sync_sub_and_fetch(&m_uiCount, 1);
    if (0 == ref)
    {
       this->finalize();
       delete this;
    }
    return ref;
}

void One2OneChannel::finalize()
{
    ec_rv_fatal( pthread_mutex_destroy(&m_sync) )
    ec_rv_fatal( pthread_cond_destroy(&m_cond) )
}

int One2OneChannel::init() {
    int rm = -1;
    int rc = -1;
   
    ec_rv( rm = pthread_mutex_init(&m_sync, NULL) )
    ec_rv( rc = pthread_cond_init(&m_cond, NULL) )

    // EC_LOG("success");
    return 0;

EC_CLEANUP_BGN
    if (0 == rm)
Example #18
0
void DestroyQueue(Queue *Q) {
	destroyList(Q->front);
	sem_close(Q->sem);
	pthread_mutex_destroy(&(Q->mutex));
	free(Q);
}
Example #19
0
 TwoQStrategy::~TwoQStrategy() {
     pthread_mutex_destroy(&_preserved_mutex);
     pthread_mutex_destroy(&_fifo_mutex);
     pthread_mutex_destroy(&_lru_mutex);
     pthread_cond_destroy(&_preserved_changed);
 }
Example #20
0
 ~mutex()
 {
     BOOST_VERIFY(!pthread_mutex_destroy(&m));
 }
Example #21
0
PThreadMutex::~PThreadMutex()

{
    pthread_mutex_destroy( hMutex );
    free( hMutex );
}
Example #22
0
 ~mutex_initializer() {  if(mp_mut) pthread_mutex_destroy(mp_mut);  }
int
main(int argc, char* argv[])
{
    pthread_t*     threads;
    int*           tids;
    pthread_attr_t attr;
    int            ret;
    int            mix_sig, i;

    /* Parse arguments */
    if(argc < 2) {
        fprintf(stderr, "%s <numProcesors> <maxLoop>\n", argv[0]);
        exit(1);
    }
    NumProcs = atoi(argv[1]);
    assert(NumProcs > 0 && NumProcs <= 32);
    if (argc >= 3) {
        MaxLoop = atoi(argv[2]);
        assert(MaxLoop > 0);
    }

    /* Initialize the mix array */
    for(i = 0; i < MAX_ELEM; i++) {
        m[i].value = mix(i,i);
    }

    /* Initialize barrier counter */
    startCounter = NumProcs;

    /* Initialize array of thread structures */
    threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs);
    assert(threads != NULL);
    tids = (int *) malloc(sizeof (int) * NumProcs);
    assert(tids != NULL);

    /* Initialize thread attribute */
    pthread_attr_init(&attr);
    pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

    ret = pthread_mutex_init(&threadLock, NULL);
    assert(ret == 0);

    for(i=0; i < NumProcs; i++) {
        /* ************************************************************
         * pthread_create takes 4 parameters
         *  p1: threads(output)
         *  p2: thread attribute
         *  p3: start routine, where new thread begins
         *  p4: arguments to the thread
         * ************************************************************ */
        tids[i] = i+1;
        ret = pthread_create(&threads[i], &attr, ThreadBody, &tids[i]);
        assert(ret == 0);
    }

    /* Wait for each of the threads to terminate */
    for(i=0; i < NumProcs; i++) {
        ret = pthread_join(threads[i], NULL);
        assert(ret == 0);
    }

    /* compute the result */
    mix_sig = sig[0];
    for(i = 1; i < NumProcs ; i++) {
        mix_sig = mix(sig[i], mix_sig);
    }

    /* end of parallel phase */

    /* ************************************************************
     * print results
     *  1. mix_sig  : deterministic race?
     *  2. &mix_sig : deterministic stack layout?
     *  3. malloc   : deterministic heap layout?
     * ************************************************************ */
    printf("\n\nShort signature: %08x @ %p @ %p\n\n\n",
           mix_sig, &mix_sig, (void*)malloc(PAGE_SIZE/5));
    fflush(stdout);
    usleep(5);

    pthread_mutex_destroy(&threadLock);
    pthread_attr_destroy(&attr);

    return 0;
}
Example #24
0
File: httpd.c Project: K1N62/Rhino
int main(int argc, char* argv[]) {

  // Variable declarations
  int i, port, sd_current, addrlen, handlingMethod, fifo, setval, max_fd;
  struct sockaddr_in sin, pin;
  configuration config;
  char error[1024];
  pthread_t handler;
  pthread_attr_t att;
  pid_t pid;
  fd_set rfds;

  // Set execution to true
  execute = true;

  // Clear file creation mask.
  umask(0);

  // Set default handling method to thread
  handlingMethod = _THREAD;

  // Get size of pin ..
  addrlen = sizeof(pin);

  // Signal handlers
  signal(SIGPIPE, SIG_IGN);
  signal(SIGINT, sig_handle_int);
  signal(SIGABRT, sig_handle_int);

  // Set default config
  setDefaultConfig(&config);

  // Set root dir to current running directory
  path_init(&config);
  rootDir(argv[0]);

  // Parse config file
  if (parseConfig(&config) == -1) {
    exit(-1);
  }

  // Check arguments
  if(argc > 1) {
    for(i = 1; i < argc; i++) {
      switch(argv[i][1]) {
        // Help
        case 'h':
          printHelp();
          return 3;
          break;
        // Port
        case 'p':
          i++;
          if(i >= argc) {
            printHelp();
            return 3;
          }
          if(argv[i][0] != '-') {
            if((port = atoi(argv[i])) != 0 && port < 65536) {
              config.listenPort = port;
              printf("Port number: %d\n", port);
            }
            else {
              printHelp();
              return 3;
            }
          }
          else {
            printHelp();
            return 3;
          }
          break;
        // Deamonize
        case 'd':
          // Start daemon if set
          printf("Starting daemon...\n");
          daemonfunc();
          break;
        // Log file
        case 'l':
          i++;
          if(i >= argc) {
            printHelp();
            return 3;
          }
          if(argv[i][0] != '-') {
            strncpy(config.accLogPath, argv[i], sizeof(config.accLogPath));
          }
          else {
            printHelp();
            return 3;
          }
          break;
        // Mode of operation
        case 's':
          i++;
          if(i >= argc) {
            printHelp();
            return 3;
          }
          if(strncmp(argv[i], "thread", 6) == 0)
            handlingMethod = _THREAD;
          else if(strncmp(argv[i], "fork", 4) == 0)
            handlingMethod = _FORK;
          else {
            printHelp();
            return 3;
          }
          break;
        case 'c':
          i++;
          if(i >= argc) {
            printHelp();
            return 3;
          }
          if(argv[i][0] != '-') {
            strncpy(config.configPath, argv[i], sizeof(config.configPath));
          }
          else {
            printHelp();
            return 3;
          }
          break;
      }
    }
  }

  // Init logfunctions
  if (log_init(&config) == -1) {
    exit(-1);
  }

  // Create fifo if prefork is set
  if (handlingMethod == _FORK) {
      // Create the named fifo pipe
      mkfifo(config.fifoPath, 0666);
      // Try opening the pipe
      if((fifo = open(config.fifoPath, O_RDWR)) == -1) {
        sprintf(error, "Unable to open FIFO-pipe, %s", strerror(errno));
        log_server(LOG_CRIT, error);
        execute = false;    // Terminate
      }
  }

  // Check super user
  if (getuid() != 0) {
    perror("You have to be root to run this program");
    exit(-1);
  }

  // Set root directory to document root
  chdir(config.basedir);
  if (chroot(config.basedir) == -1) {
    sprintf(error, "Unable to change root directory, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
  }

  // Drop root privileges
  if (setgid(getgid()) == -1) {
    sprintf(error, "Unable to change user, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
  }
  if (setuid(getuid()) == -1) {
    sprintf(error, "Unable to change user, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
  }

  // Create listening socket
  // Domain -> AF_INET = IPV4
  // Type -> SOCK_STREAM = TCP
  if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      sprintf(error, "Unable to open socket, %s", strerror(errno));
      log_server(LOG_ERR, error);
      execute = false;  // Terminate
  }

  // Zeroize sin
  memset(&sin, 0, sizeof(sin));
  // Set domain
  sin.sin_family = AF_INET;
  // Set any in address
  sin.sin_addr.s_addr = INADDR_ANY;
  // Set port, hton converts byteorder
  sin.sin_port = htons(config.listenPort);

  // Try binding the socket
	if(bind(sd, (struct sockaddr*) &sin, sizeof(sin)) == -1) {
    sprintf(error, "Unable to bind socket, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
	}

  // Start to listen for requests
  if(listen(sd, config.backlog) == -1) {
    sprintf(error, "Too loud unable to listen, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
	}

  // Init thread lock
  pthread_mutex_init(&thread_lock, NULL);

  // If handling method is set to thread
  if(handlingMethod == _THREAD) {

    // Init thread attr
    pthread_attr_init(&att);
    // Set threads to detached state
    pthread_attr_setdetachstate(&att, PTHREAD_CREATE_DETACHED);
    // Set system scope
    pthread_attr_setscope(&att, PTHREAD_SCOPE_SYSTEM);
    // Set RoundRobin scheduling
    pthread_attr_setschedpolicy(&att, SCHED_RR); // Not supported in LINUX pthreads

    // Start accepting requests
    while(execute) {

      // Accept a request from queue, blocking
      if ((sd_current = accept(sd, (struct sockaddr*) &pin, (socklen_t*) &addrlen)) == -1) {
        if (execute) {
          sprintf(error, "Unable to accept request, %s", strerror(errno));
          log_server(LOG_ERR, error);
        }
    		close(sd_current);
        execute = false;    // Terminate
  	  } else {

        // Shit happens, if server is out of memory just skip the request
        _rqhd_args *args = malloc(sizeof(_rqhd_args));
        if (args == NULL) {
          sprintf(error, "Unable to allocate memory, %s", strerror(errno));
          log_server(LOG_CRIT, error);
      		close(sd_current);
        } else {
          // Set arguments
          args->sd      = sd_current;
          args->pin     = pin;
          args->config  = &config;
        }

        // Create thread
        if(pthread_create(&handler, &att, requestHandle, args) != 0) {
          sprintf(error, "Unable to start thread, %s", strerror(errno));
          log_server(LOG_CRIT, error);
          close(sd_current);
          execute = false;    // Terminate
        }
      }
    }

      // Destroy attributes
      pthread_attr_destroy(&att);
    }
  // Else if handling method is set to fork
  else if(handlingMethod == _FORK) {

    max_fd = sd;
    if (fifo > sd)
      max_fd = fifo;

    // Start accepting requests
    while(execute) {

      FD_ZERO(&rfds);
      FD_SET(sd, &rfds);
      FD_SET(fifo, &rfds);

      // Accept request or handle child
      setval = select(max_fd + 1, &rfds, NULL, NULL, NULL);

      if (FD_ISSET(sd, &rfds)) {
        // Accept a request from queue
        if ((sd_current = accept(sd, (struct sockaddr*) &pin, (socklen_t*) &addrlen)) == -1) {
          if (execute) {
            sprintf(error, "Unable to accept request, %s", strerror(errno));
            log_server(LOG_ERR, error);
          }
      		close(sd_current);
          execute = false;    // Terminate
    	  } else {

          // Fork
          if((pid = fork()) == 0) {
            // CHILD ----------------------------------------------------

            // Shit happens, if server is out of memory just skip the request
            _rqhd_args *args = malloc(sizeof(_rqhd_args));
            if (args == NULL) {
              sprintf(error, "Unable to allocate memory, %s", strerror(errno));
              log_server(LOG_CRIT, error);
          		close(sd_current);
            } else {
              // Set arguments
              args->sd      = sd_current;
              args->pin     = pin;
              args->config  = &config;

              // Call request handler
              requestHandle(args);
            }
            // Tell parent I'm done
            pid_t id = getpid();
            if (write(fifo, &id, sizeof(pid_t)) == -1) {
                sprintf(error, "Unable to send pid, %s", strerror(errno));
                log_server(LOG_ERR, error);
            }

            // Done
            execute = false;

          } else if(pid > 0) {
            // PARENT ---------------------------------------------------
            // Parent don't handle dirty work
            close(sd_current);
          } else {
            sprintf(error, "Unable to fork, %s", strerror(errno));
            log_server(LOG_CRIT, error);
            close(sd_current);
            execute = false;    // Terminate
          }
        }
      } else if (FD_ISSET(fifo, &rfds)) {
        // Get child pid from fifo and wait for it
        pid_t child;
        if (read(fifo, &child, sizeof(pid_t)) == -1) {
          sprintf(error, "Unable to read pid, %s", strerror(errno));
          log_server(LOG_ERR, error);
        }
        waitpid(child, NULL, 0);
      } else if (setval == -1){
        // Error
        sprintf(error, "Select failed or was interrupted, %s", strerror(errno));
        log_server(LOG_ERR, error);
        execute = false;    // Terminate
      }

    }

    // Close fifo
    close(fifo);
  }
  // Else not a valid handling method
  else {
    sprintf(error, "Invalid handling method is set");
    log_server(LOG_ERR, error);
  }

  // Clean up
  pthread_mutex_destroy(&thread_lock);
  close(sd);
  log_destroy();
  if (pid != 0)
    printf("Cleanup complete, no one will know I was here.\n");

  return 0;
}
Example #25
0
DeckLinkCaptureDelegate::~DeckLinkCaptureDelegate()
{
    pthread_mutex_destroy(&m_mutex);
}
Example #26
0
 ~Init(){pthread_mutex_destroy(&id_mutex);}
Example #27
0
static void locker_pthread_destroy(Locker* thiz)
{
	PrivInfo* priv = (PrivInfo*)thiz->priv;
    pthread_mutex_destroy(&priv->mutex);
	free(thiz);
}
Example #28
0
/* Destroys table + table lock. Returns 0 on success. */
int sr_arpcache_destroy(struct sr_arpcache *cache) {
    return pthread_mutex_destroy(&(cache->lock)) && pthread_mutexattr_destroy(&(cache->attr));
}
Example #29
0
int OS_MUTEX_DESTROY(OS_MUTEX* mutex)
{
    return (pthread_mutex_destroy(mutex));
}
 virtual void TearDown() {
   ASSERT_EQ(0, pthread_join(thread, NULL));
   ASSERT_EQ(FINISHED, progress);
   ASSERT_EQ(0, pthread_cond_destroy(&cond));
   ASSERT_EQ(0, pthread_mutex_destroy(&mutex));
 }