Esempio n. 1
0
int
mono_gc_pthread_detach (pthread_t thread)
{
	return pthread_detach (thread);
}
Esempio n. 2
0
static void *_working(void *arg) {
	pthread_detach(pthread_self());

	__lock;
	_connection_num++;
	__unlock;

	struct connection_info *ci = (struct connection_info *) arg;
	ci->is_connected = 0;

	struct sockaddr_in server_addr;
	bzero(&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(ci->port);

	if (0 == inet_aton(ci->ip, &server_addr.sin_addr)) {
		log_fatal("failed to initialize socket ip");
		exit(1);
	}

	while (ci->is_running) {
		int ret = connect(ci->socket, (struct sockaddr *) &server_addr,
				sizeof(server_addr));

		if (0 == ret) {
			ci->callback_funs.on_connected(ci->id);
			ci->is_connected = 1;
		} else if (0 > ret && EINPROGRESS != errno) {
			log_info("failed to connect to destination");
			goo_sleep(ci->reconnect_interval, 0);
			_fini_socket(ci);
			_init_socket(ci);

			continue;
		}

		ci->needs_reconnect = 0;
		struct epoll_event events[EPOLL_EVENT_NUM];
		int ret_fds = 0;

		while (ci->is_running && !ci->needs_reconnect) {
			ret_fds = epoll_wait(ci->epoll_container, events, EPOLL_EVENT_NUM,
					ci->reconnect_interval);

			if (-1 == ret_fds) {
				switch (errno) {
				case EBADF:
					log_fatal("failed to call epoll_wait - EBADF");
					exit(1);
				case EFAULT:
					log_fatal("failed to call epoll_wait - EFAULT");
					exit(1);
				case EINTR:
					continue;
				case EINVAL:
					log_fatal("failed to call epoll_wait - EINVAL");
					exit(1);
				default:
					log_fatal("failed to call epoll_wait - Unknown");
					exit(1);
				}
			}

			int i = 0;

			for (; i < ret_fds; i++) {
				if ((events[i].events & EPOLLERR) && EINPROGRESS != errno) {
					ci->is_connected = 0;
					ci->needs_reconnect = 1;
					ci->callback_funs.on_error(ci->id, errno, strerror(errno));
					goo_sleep(ci->reconnect_interval, 0);
					_fini_socket(ci);
					_init_socket(ci);
					break;
				}

				if (events[i].events & EPOLLRDHUP) {
					ci->is_connected = 0;
					ci->needs_reconnect = 1;
					ci->callback_funs.on_closed(ci->id);
					goo_sleep(ci->reconnect_interval, 0);
					_fini_socket(ci);
					_init_socket(ci);
					break;
				}

				if (events[i].events & EPOLLOUT) {
					if (!ci->is_connected) {
						ci->is_connected = 1;
						ci->callback_funs.on_connected(ci->id);
						continue;
					}
				}

				if (events[i].events & EPOLLIN) {
					unsigned char buffer[RECEIVE_BUFFER_SIZE];
					int offset = 0;

					for (;;) {
						unsigned char tmp_buf[512];
						int len = recv(events[i].data.fd, tmp_buf, 512, 0);

						if (0 < len) { // read data from socket buffer
							if (len + offset > RECEIVE_BUFFER_SIZE) {
								log_fatal("the socket receiving buffer is too "
										"small");
								exit(1);
							}

							memcpy(buffer + offset, tmp_buf, len);
							offset += len;
						} else if (0 > len) {
							if (EAGAIN == errno || EWOULDBLOCK == errno) {
								// socket read buffer is empty
								if (0 < offset) {
									buffer[offset] = 0;
									ci->callback_funs.on_received(ci->id,
											buffer, offset);
									offset = 0;
								}
							} else {
								// error happened
							}

							break;
						} else {
							// the socket has been closed
							break;
						}
					}
				}
			}
		}
	}

	ci->is_connected = 0;
	ci->callback_funs.on_closed(ci->id);
	_fini_socket(ci);

	__lock;
	_connection_num--;
	__unlock;

	ci->tid = 0;

	return NULL;
}
Esempio n. 3
0
/*
 * main
 */
int main(int argc, char **argv)
{
	int ret = 0;
	void *status;

	/* Parse arguments */
	progname = argv[0];
	parse_args(argc, argv);

	/* Daemonize */
	if (opt_daemon) {
		int i;

		/*
		 * fork
		 * child: setsid, close FD 0, 1, 2, chdir /
		 * parent: exit (if fork is successful)
		 */
		ret = daemon(0, 0);
		if (ret < 0) {
			PERROR("daemon");
			goto error;
		}
		/*
		 * We are in the child. Make sure all other file
		 * descriptors are closed, in case we are called with
		 * more opened file descriptors than the standard ones.
		 */
		for (i = 3; i < sysconf(_SC_OPEN_MAX); i++) {
			(void) close(i);
		}
	}

	/* Set up max poll set size */
	lttng_poll_set_max_size();

	if (*command_sock_path == '\0') {
		switch (opt_type) {
		case LTTNG_CONSUMER_KERNEL:
			snprintf(command_sock_path, PATH_MAX, DEFAULT_KCONSUMERD_CMD_SOCK_PATH,
					DEFAULT_LTTNG_RUNDIR);
			break;
		case LTTNG_CONSUMER64_UST:
			snprintf(command_sock_path, PATH_MAX,
					DEFAULT_USTCONSUMERD64_CMD_SOCK_PATH, DEFAULT_LTTNG_RUNDIR);
			break;
		case LTTNG_CONSUMER32_UST:
			snprintf(command_sock_path, PATH_MAX,
					DEFAULT_USTCONSUMERD32_CMD_SOCK_PATH, DEFAULT_LTTNG_RUNDIR);
			break;
		default:
			WARN("Unknown consumerd type");
			goto error;
		}
	}

	/* Init */
	lttng_consumer_init();

	if (!getuid()) {
		/* Set limit for open files */
		set_ulimit();
	}

	/* create the consumer instance with and assign the callbacks */
	ctx = lttng_consumer_create(opt_type, lttng_consumer_read_subbuffer,
		NULL, lttng_consumer_on_recv_stream, NULL);
	if (ctx == NULL) {
		goto error;
	}

	lttng_consumer_set_command_sock_path(ctx, command_sock_path);
	if (*error_sock_path == '\0') {
		switch (opt_type) {
		case LTTNG_CONSUMER_KERNEL:
			snprintf(error_sock_path, PATH_MAX, DEFAULT_KCONSUMERD_ERR_SOCK_PATH,
					DEFAULT_LTTNG_RUNDIR);
			break;
		case LTTNG_CONSUMER64_UST:
			snprintf(error_sock_path, PATH_MAX,
					DEFAULT_USTCONSUMERD64_ERR_SOCK_PATH, DEFAULT_LTTNG_RUNDIR);
			break;
		case LTTNG_CONSUMER32_UST:
			snprintf(error_sock_path, PATH_MAX,
					DEFAULT_USTCONSUMERD32_ERR_SOCK_PATH, DEFAULT_LTTNG_RUNDIR);
			break;
		default:
			WARN("Unknown consumerd type");
			goto error;
		}
	}

	if (set_signal_handler() < 0) {
		goto error;
	}

	/* Connect to the socket created by lttng-sessiond to report errors */
	DBG("Connecting to error socket %s", error_sock_path);
	ret = lttcomm_connect_unix_sock(error_sock_path);
	/* not a fatal error, but all communication with lttng-sessiond will fail */
	if (ret < 0) {
		WARN("Cannot connect to error socket (is lttng-sessiond started?)");
	}
	lttng_consumer_set_error_sock(ctx, ret);

	/*
	 * For UST consumer, we block RT signals used for periodical metadata flush
	 * in main and create a dedicated thread to handle these signals.
	 */
	switch (opt_type) {
	case LTTNG_CONSUMER32_UST:
	case LTTNG_CONSUMER64_UST:
		consumer_signal_init();
		break;
	default:
		break;
	}
	ctx->type = opt_type;

	/* Create thread to manage channels */
	ret = pthread_create(&channel_thread, NULL, consumer_thread_channel_poll,
			(void *) ctx);
	if (ret != 0) {
		perror("pthread_create");
		goto error;
	}

	/* Create thread to manage the polling/writing of trace metadata */
	ret = pthread_create(&metadata_thread, NULL, consumer_thread_metadata_poll,
			(void *) ctx);
	if (ret != 0) {
		perror("pthread_create");
		goto metadata_error;
	}

	/* Create thread to manage the polling/writing of trace data */
	ret = pthread_create(&data_thread, NULL, consumer_thread_data_poll,
			(void *) ctx);
	if (ret != 0) {
		perror("pthread_create");
		goto data_error;
	}

	/* Create the thread to manage the receive of fd */
	ret = pthread_create(&sessiond_thread, NULL, consumer_thread_sessiond_poll,
			(void *) ctx);
	if (ret != 0) {
		perror("pthread_create");
		goto sessiond_error;
	}

	switch (opt_type) {
	case LTTNG_CONSUMER32_UST:
	case LTTNG_CONSUMER64_UST:
		/* Create the thread to manage the metadata periodic timers */
		ret = pthread_create(&metadata_timer_thread, NULL,
				consumer_timer_metadata_thread, (void *) ctx);
		if (ret != 0) {
			perror("pthread_create");
			goto metadata_timer_error;
		}

		ret = pthread_detach(metadata_timer_thread);
		if (ret) {
			errno = ret;
			perror("pthread_detach");
		}
		break;
	default:
		break;
	}

metadata_timer_error:
	ret = pthread_join(sessiond_thread, &status);
	if (ret != 0) {
		perror("pthread_join");
		goto error;
	}

sessiond_error:
	ret = pthread_join(data_thread, &status);
	if (ret != 0) {
		perror("pthread_join");
		goto error;
	}

data_error:
	ret = pthread_join(metadata_thread, &status);
	if (ret != 0) {
		perror("pthread_join");
		goto error;
	}

metadata_error:
	ret = pthread_join(channel_thread, &status);
	if (ret != 0) {
		perror("pthread_join");
		goto error;
	}

	if (!ret) {
		ret = EXIT_SUCCESS;
		lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_EXIT_SUCCESS);
		goto end;
	}

error:
	ret = EXIT_FAILURE;
	if (ctx) {
		lttng_consumer_send_error(ctx, LTTCOMM_CONSUMERD_EXIT_FAILURE);
	}

end:
	lttng_consumer_destroy(ctx);
	lttng_consumer_cleanup();

	return ret;
}
Esempio n. 4
0
void* client_main_thread(void* arg) {
	struct client_struct* client = (struct client_struct*)arg;
	int skip_sleep;

	do {
		skip_sleep = 0;

		/* GLOBAL READ LOCK */
		pthread_rwlock_rdlock(&netopeer_state.global_lock);

		switch (client->transport) {
#ifdef NP_SSH
		case NC_TRANSPORT_SSH:
			skip_sleep += np_ssh_client_transport((struct client_struct_ssh*)client);
			skip_sleep += np_ssh_client_netconf_rpc((struct client_struct_ssh*)client);
			break;
#endif
#ifdef NP_TLS
		case NC_TRANSPORT_TLS:
			skip_sleep += np_tls_client_transport((struct client_struct_tls*)client);
			skip_sleep += np_tls_client_netconf_rpc((struct client_struct_tls*)client);
			break;
#endif
		default:
			nc_verb_error("%s: internal error (%s:%d)", __func__, __FILE__, __LINE__);
		}

		/* GLOBAL READ UNLOCK */
		pthread_rwlock_unlock(&netopeer_state.global_lock);

		if (!skip_sleep) {
			/* we did not do anything productive, so let the thread sleep */
			usleep(netopeer_options.response_time*1000);
		}
	} while (!client->to_free);

	/* GLOBAL WRITE LOCK */
	pthread_rwlock_wrlock(&netopeer_state.global_lock);

	np_client_detach(&netopeer_state.clients, client);

	/* GLOBAL WRITE UNLOCK */
	pthread_rwlock_unlock(&netopeer_state.global_lock);

	switch (client->transport) {
#ifdef NP_SSH
	case NC_TRANSPORT_SSH:
		client_free_ssh((struct client_struct_ssh*)client);
		break;
#endif
#ifdef NP_TLS
	case NC_TRANSPORT_TLS:
		client_free_tls((struct client_struct_tls*)client);
		break;
#endif
	default:
		free(client);
		break;
	}

#ifdef NP_TLS
	np_tls_thread_cleanup();
#endif

	pthread_detach(pthread_self());

	return NULL;
}
Esempio n. 5
0
void
SDL_SYS_DetachThread(SDL_Thread * thread)
{
    pthread_detach(thread->handle);
}
Esempio n. 6
0
/*************************************************
  Function:			phone_monitor_proc
  Description: 		模拟门前机监视线程
  Input: 			
  	1.param			参数
  Output:			无
  Return:			BOOLEAN
  Others:
*************************************************/
static void* phone_monitor_proc(void *param)
{
	// 设置分离线程
	pthread_detach(pthread_self());
	time_t t0;
	//int32 RequestTimes = 3;  
	int32 ret = FALSE;
	static int32 times = 10;
	
	
LabChange:

	t0 = time(0);
	g_Video_Start = 0;
	//RequestTimes = 3;
	if (MONITOR_REQUEST == g_MonitorInfo.state)			
	{
		g_PreMonitorState = MONITOR_REQUEST;
		GuiNotify(g_MonitorInfo.state, g_MonitorInfo.index);
		g_MonitorInfo.state = MONITOR_MONITORING;  // 模拟门前机直接监视 
		usleep(1000);
		#if 0
		//  3次不成功就退出
		while (RequestTimes)
		{
			// 【开启监视接口】索引号传入
			//ret = [开启监视接口函数];
			if (ret == FALSE)
			{
				RequestTimes--;
			}
			else
			{
				g_MonitorInfo.state = MONITOR_MONITORING;
				break;
			}
		}
		if (RequestTimes <= 0)
		{
			g_MonitorInfo.state = MONITOR_END;
		}
		#endif
	}

	t0 = time(0);
	if(MONITOR_MONITORING == g_MonitorInfo.state)	
	{	
		dprintf(" *************** MONITOR_MONITORING ******************* \n");
		g_PreMonitorState = MONITOR_MONITORING;
		hw_mk_start();
		// [开启视频接口]
		ret = media_start_analog_video();
		if (ret == -1)
		{
			g_MonitorInfo.state = MONITOR_END;
			g_PreMonitorState = MONITOR_END;
		}
		else
		{
			GuiNotify(g_MonitorInfo.state, 0);	
			g_Video_Start = 1;
			
			g_MonitorInfo.TimeMax = MONITOR_TIME_MAX;	
			g_MonitorInfo.TimeOut = 0;
			g_RemainTime = 0;
		}
		
		while (MONITOR_MONITORING == g_MonitorInfo.state)
		{
			g_MonitorInfo.TimeOut = time(0) - t0;
			if (g_MonitorInfo.TimeMax > 0)
			{
				//剩余时间
				g_RemainTime = g_MonitorInfo.TimeMax - g_MonitorInfo.TimeOut;
				dprintf("g_RemainTime : %d\n ", g_RemainTime);
				if (g_RemainTime <= 0)
				{
					g_ErrType = MONITOR_MONITORING_TIMEOUT;
					g_MonitorInfo.state = MONITOR_END;
					break;
				}
				else
				{
					//GuiNotify(MONITOR_TIMER, g_RemainTime);
				}

				times = 10;
				while ((times--) > 0 && MONITOR_MONITORING == g_MonitorInfo.state)
				{
					usleep(100*1000);
				}
			}
		}
	}

	t0 = time(0);
	if(MONITOR_TALKING == g_MonitorInfo.state)
	{
		dprintf("MONITOR_TALKING == g_MonitorInfo.state \n");

		// [监视进入通话接口]
		//hw_switch_analog();
		hw_mk_talk();
		
		g_PreMonitorState = MONITOR_TALKING;
		GuiNotify(g_MonitorInfo.state, 0);
		
		g_MonitorInfo.TimeMax = MONITOR_TALK_TIME_MAX;		
		g_MonitorInfo.TimeOut = 0;
		g_MonitorInfo.HeartTime = 0;
		
		while (MONITOR_TALKING == g_MonitorInfo.state)
		{
			if (g_MonitorInfo.TimeMax > 0)
			{
				g_RemainTime = 0;
				g_MonitorInfo.TimeOut = time(0) - t0;
				g_RemainTime = g_MonitorInfo.TimeMax - g_MonitorInfo.TimeOut;					
				if (g_RemainTime <= 0)
				{
					dprintf("monitor timer proc : talking time out\n");
					g_ErrType = MONITOR_TALKING_TIMEOUT;
					g_MonitorInfo.state = MONITOR_END;
					break;
				}
				else
				{
					//GuiNotify(MONITOR_TIMER, g_RemainTime);
				}
					
				times = 10;
				while ((times--) > 0 && MONITOR_TALKING == g_MonitorInfo.state)
				{
					usleep(100*1000);
				}
			}
		}
	}

	// 监视下一个情况 
	if (MONITOR_REQUEST == g_MonitorInfo.state)
	{
		// [关闭视频接口]
		media_stop_analog_video();
		goto LabChange;
	}
	
	dprintf("monitor proc : AS_MONITOR_END : g_ErrType : %d\n", g_ErrType);
	media_stop_analog_video();	
	g_Video_Start = 0;
	hw_switch_digit();  // [关闭监视接口]
	sys_set_monitor_state(FALSE);
	dprintf("monitor proc end!\n");
	
	g_MonitorInfo.state = MONITOR_END;
	g_PreMonitorState = MONITOR_END;
	GuiNotify(g_MonitorInfo.state, g_ErrType);
	inter_SetThread(&g_MonitorInfo.mThread);

	pthread_exit(NULL);
	return NULL;             // 返回后资源由系统释放
}
Esempio n. 7
0
static DWORD WINAPI
#else
static void *
#endif
handle_connection(void *arg)
{
	ssize_t n;
	unsigned long long sum = 0, first_length = 0;
	char *buf;
#ifdef _WIN32
	HANDLE tid;
#else
	pthread_t tid;
#endif
	struct socket *conn_sock;
	struct timeval start_time, now, diff_time;
	double seconds;
	unsigned long messages = 0;
	unsigned long recv_calls = 0;
	unsigned long notifications = 0;
	int flags;
	struct sockaddr_in addr;
	socklen_t len;
	union sctp_notification *snp;
	struct sctp_paddr_change *spc;
	struct timeval note_time;
	unsigned int infotype;
	struct sctp_recvv_rn rn;
	socklen_t infolen = sizeof(struct sctp_recvv_rn);

	conn_sock = *(struct socket **)arg;
#ifdef _WIN32
	tid = GetCurrentThread();
#else
	tid = pthread_self();
	pthread_detach(tid);
#endif

	buf = malloc(BUFFERSIZE);
	flags = 0;
	len = (socklen_t)sizeof(struct sockaddr_in);
	infotype = 0;
	memset(&rn, 0, sizeof(struct sctp_recvv_rn));
	n = usrsctp_recvv(conn_sock, buf, BUFFERSIZE, (struct sockaddr *) &addr, &len, (void *)&rn,
	                 &infolen, &infotype, &flags);

	gettimeofday(&start_time, NULL);
	while (n > 0) {
		recv_calls++;
		if (flags & MSG_NOTIFICATION) {
			notifications++;
			gettimeofday(&note_time, NULL);
			printf("notification arrived at %f\n", note_time.tv_sec+(double)note_time.tv_usec/1000000.0);
			snp = (union sctp_notification *)buf;
			if (snp->sn_header.sn_type==SCTP_PEER_ADDR_CHANGE)
			{
				spc = &snp->sn_paddr_change;
				printf("SCTP_PEER_ADDR_CHANGE: state=%d, error=%d\n",spc->spc_state, spc->spc_error);
			}
		} else {
			if (very_verbose) {
				printf("Message received\n");
			}
			sum += n;
			if (flags & MSG_EOR) {
				messages++;
				if (first_length == 0)
					first_length = sum;
			}
		}
		flags = 0;
		len = (socklen_t)sizeof(struct sockaddr_in);
		infolen = sizeof(struct sctp_recvv_rn);
		infotype = 0;
		memset(&rn, 0, sizeof(struct sctp_recvv_rn));
		n = usrsctp_recvv(conn_sock, (void *) buf, BUFFERSIZE, (struct sockaddr *) &addr, &len, (void *)&rn,
		                  &infolen, &infotype, &flags);
	}
	if (n < 0)
		perror("sctp_recvv");
	gettimeofday(&now, NULL);
	timersub(&now, &start_time, &diff_time);
	seconds = diff_time.tv_sec + (double)diff_time.tv_usec/1000000.0;
	printf("%llu, %lu, %lu, %lu, %llu, %f, %f\n",
	        first_length, messages, recv_calls, notifications, sum, seconds, (double)first_length * (double)messages / seconds);
	fflush(stdout);
	usrsctp_close(conn_sock);
	free(buf);
#ifdef _WIN32
	return 0;
#else
	return (NULL);
#endif
}
Esempio n. 8
0
void Thread::OnStop()
{
	tid_ = 0;
	flag_ = 0;
	pthread_detach(pthread_self());
}
Esempio n. 9
0
/** 
 * @internal
 *
 * Stops the valvula thread pool, that was initialized by
 * valvula_thread_pool_init.
 * 
 */
void valvula_thread_pool_exit (ValvulaCtx * ctx) 
{
	/* get current context */
	int             iterator;
	ValvulaThread  * thread;

	if (ctx->skip_thread_pool_wait)
		return;

	valvula_log (VALVULA_LEVEL_DEBUG, "stopping thread pool..");

	/* flag the queue to be stoping */
	valvula_mutex_lock (&ctx->thread_pool->mutex);
	ctx->thread_pool_being_stopped = axl_true;
	valvula_mutex_unlock (&ctx->thread_pool->mutex);

	/* push beacons to notify eacy thread created to stop */
	iterator = 0;
	while (iterator < axl_list_length (ctx->thread_pool->threads)) {
		valvula_log (VALVULA_LEVEL_DEBUG, "pushing beacon to stop thread from the pool..");
		/* push a notifier */
		valvula_async_queue_push (ctx->thread_pool->queue, INT_TO_PTR (1));

		/* update the iterator */
		iterator++;
	} /* end if */

	/* stop all threads */
	if (ctx->skip_thread_pool_wait) {
		valvula_log (VALVULA_LEVEL_DEBUG, "found skip thread finish wait");
		/* remove all threads */
		while (axl_list_length (ctx->thread_pool->threads) > 0) {
			/* get reference to the thread to be not waited */
			thread = axl_list_get_first (ctx->thread_pool->threads);

			/* remove from the list */
			axl_list_unlink_first (ctx->thread_pool->threads);

#if defined(AXL_OS_UNIX)
			/* flag is as detached */
			pthread_detach (*thread);
#endif
			/* release object */
			axl_free (thread);

		}
	} /* end if */

	axl_list_free (ctx->thread_pool->threads);
	axl_list_free (ctx->thread_pool->events);
	axl_list_cursor_free (ctx->thread_pool->events_cursor);
	axl_list_free (ctx->thread_pool->stopped);

	/* unref the queue */
	valvula_async_queue_unref (ctx->thread_pool->queue);

	/* terminate mutex */
	valvula_mutex_destroy (&ctx->thread_pool->mutex);
	valvula_mutex_destroy (&(ctx->thread_pool->stopped_mutex));

	/* free the node itself */
	axl_free (ctx->thread_pool);
	ctx->thread_pool = NULL;

	valvula_log (VALVULA_LEVEL_DEBUG, "thread pool is stopped..");
	return;
}
Esempio n. 10
0
static void
handle_request( VoodooManager        *manager,
                VoodooRequestMessage *request )
{
     DirectResult    ret;
     VoodooInstance *instance;

     D_MAGIC_ASSERT( manager, VoodooManager );
     D_ASSERT( request != NULL );
     D_ASSERT( request->header.size >= sizeof(VoodooRequestMessage) );
     D_ASSERT( request->header.type == VMSG_REQUEST );

     D_DEBUG( "Voodoo/Dispatch: Handling REQUEST message %llu to %u::%u %s%s(%d bytes).\n",
              (unsigned long long)request->header.serial, request->instance, request->method,
              (request->flags & VREQ_RESPOND) ? "[RESPONDING] " : "",
              (request->flags & VREQ_ASYNC) ? "[ASYNC] " : "",
              request->header.size );

     pthread_mutex_lock( &manager->instances.lock );

     instance = direct_hash_lookup( manager->instances.local, request->instance );
     if (!instance) {
          pthread_mutex_unlock( &manager->instances.lock );

          D_ERROR( "Voodoo/Dispatch: "
                   "Requested instance %u doesn't exist (anymore)!\n", request->instance );

          if (request->flags & VREQ_RESPOND)
               voodoo_manager_respond( manager, request->header.serial,
                                       DR_NOSUCHINSTANCE, VOODOO_INSTANCE_NONE,
                                       VMBT_NONE );

          return;
     }

     if (request->flags & VREQ_ASYNC) {
          pthread_t             thread;
          DispatchAsyncContext *context;

          context = D_MALLOC( sizeof(DispatchAsyncContext) + request->header.size );
          if (!context) {
               D_WARN( "out of memory" );
               pthread_mutex_unlock( &manager->instances.lock );
               return;
          }

          context->manager  = manager;
          context->instance = instance;
          context->request  = (VoodooRequestMessage*) (context + 1);

          direct_memcpy( context->request, request, request->header.size );

          pthread_create( &thread, NULL, dispatch_async_thread, context );
          pthread_detach( thread );
     }
     else {
          ret = instance->dispatch( instance->proxy, instance->real, manager, request );

          if (ret && (request->flags & VREQ_RESPOND))
               voodoo_manager_respond( manager, request->header.serial,
                                       ret, VOODOO_INSTANCE_NONE,
                                       VMBT_NONE );
     }

     pthread_mutex_unlock( &manager->instances.lock );
}
Esempio n. 11
0
static void *fuse_do_work(void *data)
{
	struct fuse_worker *w = (struct fuse_worker *) data;
	struct fuse_mt *mt = w->mt;

	while (!fuse_session_exited(mt->se)) {
		int isforget = 0;
		struct fuse_chan *ch = mt->prevch;
		struct fuse_buf fbuf = {
			.mem = w->buf,
			.size = w->bufsize,
		};
		int res;

		pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
		res = fuse_session_receive_buf(mt->se, &fbuf, &ch);
		pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
		if (res == -EINTR)
			continue;
		if (res <= 0) {
			if (res < 0) {
				fuse_session_exit(mt->se);
				mt->error = -1;
			}
			break;
		}

		pthread_mutex_lock(&mt->lock);
		if (mt->exit) {
			pthread_mutex_unlock(&mt->lock);
			return NULL;
		}

		/*
		 * This disgusting hack is needed so that zillions of threads
		 * are not created on a burst of FORGET messages
		 */
		if (!(fbuf.flags & FUSE_BUF_IS_FD)) {
			struct fuse_in_header *in = fbuf.mem;

			if (in->opcode == FUSE_FORGET ||
			    in->opcode == FUSE_BATCH_FORGET)
				isforget = 1;
		}

		if (!isforget)
			mt->numavail--;
		if (mt->numavail == 0)
			fuse_loop_start_thread(mt);
		pthread_mutex_unlock(&mt->lock);

		fuse_session_process_buf(mt->se, &fbuf, ch);

		pthread_mutex_lock(&mt->lock);
		if (!isforget)
			mt->numavail++;
		if (mt->numavail > 10) {
			if (mt->exit) {
				pthread_mutex_unlock(&mt->lock);
				return NULL;
			}
			list_del_worker(w);
			mt->numavail--;
			mt->numworker--;
			pthread_mutex_unlock(&mt->lock);

			pthread_detach(w->thread_id);
			free(w->buf);
			free(w);
			return NULL;
		}
		pthread_mutex_unlock(&mt->lock);
	}

	sem_post(&mt->finish);

	return NULL;
}

int fuse_start_thread(pthread_t *thread_id, void *(*func)(void *), void *arg)
{
	sigset_t oldset;
	sigset_t newset;
	int res;
	pthread_attr_t attr;
	char *stack_size;

	/* Override default stack size */
	pthread_attr_init(&attr);
	stack_size = getenv(ENVNAME_THREAD_STACK);
	if (stack_size && pthread_attr_setstacksize(&attr, atoi(stack_size)))
		fprintf(stderr, "fuse: invalid stack size: %s\n", stack_size);

	/* Disallow signal reception in worker threads */
	sigemptyset(&newset);
	sigaddset(&newset, SIGTERM);
	sigaddset(&newset, SIGINT);
	sigaddset(&newset, SIGHUP);
	sigaddset(&newset, SIGQUIT);
	pthread_sigmask(SIG_BLOCK, &newset, &oldset);
	res = pthread_create(thread_id, &attr, func, arg);
	pthread_sigmask(SIG_SETMASK, &oldset, NULL);
	pthread_attr_destroy(&attr);
	if (res != 0) {
		fprintf(stderr, "fuse: error creating thread: %s\n",
			strerror(res));
		return -1;
	}

	return 0;
}
Esempio n. 12
0
static void *tcp_server_thread(void *p_param)
{
	/* local variables definitions */
	int j = 0;
	int n = 0;
	int ret_val = 0;
	char data = 0;
	fd_list_node *p_fd_list_node = NULL;
	pthread_t thread_id = 0;
	recv_data_thread_context *p_recv_data_thread_context = NULL;
	tcp_server_context *p_tcp_server_context = (tcp_server_context*)p_param;
	
	/* code body */
	while (1)
	{
		ret_val = poll(
					p_tcp_server_context->p_poll_fds,
					(p_tcp_server_context->listen_addr_num + 1),
					(-1));
		if (ret_val > 0)
		{
			for (j = 0; j < p_tcp_server_context->listen_addr_num; j++)
			{
				if (p_tcp_server_context->p_poll_fds[j].revents & POLLIN)
				{
					p_fd_list_node = calloc(1, sizeof(*p_fd_list_node));
					p_fd_list_node->fd = accept(p_tcp_server_context->p_listen_socket_fd[j], NULL, NULL);

					if (0 != pthread_mutex_lock(&(p_tcp_server_context->mutex)))
					{
					}
					else
					{
						p_fd_list_node->p_next_node = p_tcp_server_context->p_conn_socket_list;
						p_tcp_server_context->p_conn_socket_list = p_fd_list_node;

						p_recv_data_thread_context = calloc(1, sizeof(*p_recv_data_thread_context));
						if (NULL == p_recv_data_thread_context)
						{
						}
						else
						{
							p_recv_data_thread_context->fd = p_fd_list_node->fd;
							p_recv_data_thread_context->index = j;
							p_recv_data_thread_context->p_tcp_server_context = p_tcp_server_context;
							if (0 == pthread_create(&thread_id, NULL, recv_data_thread, p_recv_data_thread_context))
							{
								pthread_detach(thread_id);
							}
							else
							{
							}
						}
						pthread_mutex_unlock(&(p_tcp_server_context->mutex));
					}
				}
			}
			if (p_tcp_server_context->p_poll_fds[p_tcp_server_context->listen_addr_num].revents & POLLIN)
			{
				n = recv(p_tcp_server_context->manage_socket_fd[1], &data, sizeof(data), 0);
				break;
			}
		}
		else
		{
			break;
		}
	}

	for (j = 0; j < p_tcp_server_context->listen_addr_num; j++)
	{
		close(p_tcp_server_context->p_listen_socket_fd[j]);
	}
	
	if (0 != pthread_mutex_lock(&(p_tcp_server_context->mutex)))
	{
	}
	else
	{
		p_tcp_server_context->tcp_server_exit = TRUE;

		p_fd_list_node = p_tcp_server_context->p_conn_socket_list;
		
		/* There is no receive data thread */
		if (NULL == p_fd_list_node)
		{
			data = DONE_COMMAND;
			send(p_tcp_server_context->manage_socket_fd[1], &data, sizeof(data), 0);
		}
		else
		{
			while (NULL != p_fd_list_node)
			{
				shutdown(p_fd_list_node->fd, SHUT_RD);
				p_fd_list_node = p_fd_list_node->p_next_node;
			}
		}
		
		pthread_mutex_unlock(&(p_tcp_server_context->mutex));
	}
	
	return NULL;
}
Esempio n. 13
0
File: conn.c Progetto: nuxlli/npfs
static void *
np_conn_read_proc(void *a)
{
	int i, n, size, msize;
	Npsrv *srv;
	Npconn *conn;
	Nptrans *trans;
	Npreq *req;
	Npfcall *fc, *fc1;

	pthread_detach(pthread_self());
	conn = a;
	np_conn_incref(conn);
	srv = conn->srv;
	msize = conn->msize;
	fc = np_conn_new_incall(conn);
	n = 0;
	while (conn->trans && (i = np_trans_read(conn->trans, fc->pkt + n, msize - n)) > 0) {
		pthread_mutex_lock(&conn->lock);
		if (conn->resetting) {
			pthread_cond_wait(&conn->resetdonecond, &conn->lock);
			n = 0;	/* discard all input */
			i = 0;
		}
		pthread_mutex_unlock(&conn->lock);
		n += i;

again:
		if (n < 4)
			continue;

		size = fc->pkt[0] | (fc->pkt[1]<<8) | (fc->pkt[2]<<16) | (fc->pkt[3]<<24);
		if (n < size)
			continue;

		if (!np_deserialize(fc, fc->pkt, conn->dotu))
			break;

		if (conn->srv->debuglevel) {
			fprintf(stderr, "<<< (%p) ", conn);
			np_printfcall(stderr, fc, conn->dotu);
			fprintf(stderr, "\n");
		}

		fc1 = np_conn_new_incall(conn);
		if (n > size)
			memmove(fc1->pkt, fc->pkt + size, n - size);
		n -= size;

		req = np_req_alloc(conn, fc);
		pthread_mutex_lock(&srv->lock);
		if (!conn->resetting)
			np_srv_add_req(srv, req);
		else 
			np_req_unref(req);
		pthread_mutex_unlock(&srv->lock);
		fc = fc1;
		if (n > 0)
			goto again;

	}

	pthread_mutex_lock(&conn->lock);
	trans = conn->trans;
	conn->trans = NULL;
	np_conn_free_incall(conn, fc, 0);
	pthread_mutex_unlock(&conn->lock);

	np_srv_remove_conn(conn->srv, conn);
	np_conn_reset(conn, 0, 0);

	if (trans)
		np_trans_destroy(trans);

	np_conn_decref(conn);
	return NULL;
}
Esempio n. 14
0
void Thread::detach()
{
	pthread_detach(_tid);
}
Esempio n. 15
0
void cancel_test(void)
{
  pthread_t waiter;
  void *result;
  int status;

  /* Test 1: Normal Cancel *********************************************/
  /* Start the waiter thread  */

  printf("cancel_test: Test 1: Normal Cancelation\n");
  printf("cancel_test: Starting thread\n");
  start_thread(&waiter, 1);

  /* Then cancel it.  It should be in the pthread_cond_wait now */

  printf("cancel_test: Canceling thread\n");
  status = pthread_cancel(waiter);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_cancel failed, status=%d\n", status);
    }

  /* Then join to the thread to pick up the result (if we don't do
   * we will have a memory leak!)
   */

  printf("cancel_test: Joining\n");
  status = pthread_join(waiter, &result);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_join failed, status=%d\n", status);
    }
  else
    {
      printf("cancel_test: waiter exited with result=%p\n", result);
      if (result != PTHREAD_CANCELED)
        {
          printf("cancel_test: ERROR expected result=%p\n", PTHREAD_CANCELED);
        }
      else
        {
          printf("cancel_test: PASS thread terminated with PTHREAD_CANCELED\n");
        }
    }

  /* Test 2: Cancel Detached Thread ************************************/

  printf("cancel_test: Test 2: Cancelation of detached thread\n");
  printf("cancel_test: Re-starting thread\n");
  restart_thread(&waiter, 1);

  /* Detach the thread */

  status = pthread_detach(waiter);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_detach, status=%d\n", status);
    }

  /* Then cancel it.  It should be in the pthread_cond_wait now */

  printf("cancel_test: Canceling thread\n");
  status = pthread_cancel(waiter);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_cancel failed, status=%d\n", status);
    }

  /* Join should now fail */

  printf("cancel_test: Joining\n");
  status = pthread_join(waiter, &result);
  if (status == 0)
    {
      printf("cancel_test: ERROR pthread_join succeeded\n");
    }
  else if (status != ESRCH)
    {
      printf("cancel_test: ERROR pthread_join failed but with wrong status=%d\n", status);
    }
  else
    {
      printf("cancel_test: PASS pthread_join failed with status=ESRCH\n");
    }

  /* Test 3: Non-cancelable threads ************************************/
  /* This test currently depends on signals.  It doesn't have to and
   * could be re-designed so that it does not depend on signals.
   */

#ifndef CONFIG_DISABLE_SIGNALS
  printf("cancel_test: Test 3: Non-cancelable threads\n");
  printf("cancel_test: Re-starting thread (non-cancelable)\n");
  restart_thread(&waiter, 0);

  /* Give the thread a chance to run an to set the non-cancelable state.
   * This is the dependency on signals:
   */

  usleep(200*1000);

  /* Then cancel it.  It should be in the pthread_cond_wait now.  The
   * behavior here is non-standard:  when the thread is at a cancelation
   * point, it should be cancelable, even when cancelation is disable.
   *
   * The cancelation should succeed, because the cancelation is pending.
   */

  printf("cancel_test: Canceling thread\n");
  status = pthread_cancel(waiter);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_cancel failed, status=%d\n", status);
    }

  /* Signal the thread.  It should wake up and restore the cancelable state.
   * When the cancelable state is re-enabled, the thread should be canceled.
   */

  status = pthread_mutex_lock(&mutex);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_mutex_lock failed, status=%d\n", status);
    }

  status = pthread_cond_signal(&cond);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_cond_signal failed, status=%d\n", status);
    }

  status = pthread_mutex_unlock(&mutex);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_mutex_unlock failed, status=%d\n", status);
    }

  /* Then join to the thread to pick up the result (if we don't do
   * we will have a memory leak!)
   */

  printf("cancel_test: Joining\n");
  status = pthread_join(waiter, &result);
  if (status != 0)
    {
      printf("cancel_test: ERROR pthread_join failed, status=%d\n", status);
    }
  else
    {
      printf("cancel_test: waiter exited with result=%p\n", result);
      if (result != PTHREAD_CANCELED)
        {
          printf("cancel_test: ERROR expected result=%p\n", PTHREAD_CANCELED);
        }
      else
        {
          printf("cancel_test: PASS thread terminated with PTHREAD_CANCELED\n");
        }
    }
#endif
}
/* $begin detach */
void Pthread_detach(pthread_t tid) {
    int rc;

    if ((rc = pthread_detach(tid)) != 0)
        posix_error(rc, "Pthread_detach error");
}
Esempio n. 17
0
Thread::~Thread()
{
    if(isStarted_)
        pthread_detach(tid_);
}
Esempio n. 18
0
static void NPClientDetachConnectThread(void)
{
	pthread_create(&connectthread, NULL, NPClientConnectThread, NULL);
	pthread_detach(connectthread);
}
Esempio n. 19
0
/*************************************************
  Function:			monitor_proc
  Description: 		监视线程
  Input: 			
  	1.param			参数
  Output:			无
  Return:			BOOLEAN
  Others:
*************************************************/
static void* monitor_proc(void *param)
{
	// 设置分离线程
	pthread_detach(pthread_self());
	time_t t0;
	int32 size = 0;
	int32 ret = FALSE;
	static int32 times = 10;	
	
LabChange:
	g_Video_Start = 0;
	g_Audio_Start = 0;
	monitor_set_media_ifover(FALSE);
	ret = media_start_net_video(g_MonitorInfo.address, _RECVONLY);
	if (ret == TRUE)
	{
		dprintf("monitor_proc : monitoring : start net video OK\n");
		g_Video_Start = 1;
	}
	
	t0 = time(0);
	if (MONITOR_REQUEST == g_MonitorInfo.state)			
	{
		g_PreMonitorState = MONITOR_REQUEST;
		monitor_fill_destdevno();
		GuiNotify(g_MonitorInfo.state, g_MonitorInfo.index);
		g_MonitorInfo.TimeOut = 0;
		g_MonitorInfo.HeartTime = 0;
		while (MONITOR_REQUEST == g_MonitorInfo.state)
		{
			memset(g_data, 0, sizeof(g_data));
			memcpy(g_data, &g_MonitorInfo.LocalVideoPort, 2);
			g_MonitorInfo.TimeOut = time(0) - t0;
			// 监视请求5s后没有回应退出
			if (g_MonitorInfo.TimeOut >= 5)
			{
				dprintf("monitor_timer_proc : request time out \n");
				g_ErrType = MONITOR_REQUEST_TIMEOUT;
				g_MonitorInfo.state = MONITOR_END;
				break;
			}

			// 以下每秒发送一次连接请求
			if (g_MonitorInfo.DevType == DEVICE_TYPE_DOOR_NET)							
			{
				// 监视网络门前机
				uint8 *tmp = NULL;
				MAC_TYPE MacType = DOOR1_MAC;
				if (g_MonitorInfo.index == 1)
				{
					MacType = DOOR1_MAC;
				}
				else
				{
					MacType = DOOR2_MAC;
				}
				
				tmp = storage_get_mac(MacType);
				memcpy(g_mac, tmp, 6);
				
				g_data[2] = DEVICE_TYPE_DOOR_NET;
				g_data[3] = (uint8)g_MonitorInfo.index;
				
				#ifdef _SEND_SDP_PARAM_
				memcpy(&g_data[4], (char *)(&g_venc_parm), 16);
				memcpy(&g_data[20], (char *)(&g_audio_parm), 8);
				memcpy(&g_data[28], g_mac, 6);
				size = 66;
				#else
				memcpy(&g_data[4], g_mac, 6);
				size = 10;
				#endif
				
				set_nethead(g_MoniDestDeviceNo, PRIRY_DEFAULT);
				net_direct_send(CMD_MONITOR, g_data, size, g_MonitorInfo.address, g_MonitorInfo.port);
			}
			else
			{
				#ifdef _TY_STAIR_
				if (storage_get_extmode(EXT_MODE_GENERAL_STAIR))
				{
					g_data[2] = (uint8)g_MonitorInfo.DevType;
					g_data[3] = (uint8)g_MonitorInfo.index;
					
					#ifdef _SEND_SDP_PARAM_
					memcpy(&g_data[4], (char *)(&g_venc_parm), 16);
					memcpy(&g_data[20], (char *)(&g_audio_parm), 8);
					size = 66;
					#else
					size = 4;
					#endif
					
					set_nethead(g_MoniDestDeviceNo, PRIRY_DEFAULT);
					net_direct_send(CMD_MONITOR, g_data, size, g_MonitorInfo.address, g_MonitorInfo.port);
				}
				else
				#endif
				{
					g_data[2] = (uint8)g_MonitorInfo.DevType;
					g_data[3] = (uint8)g_MonitorInfo.index;
					
					#ifdef _SEND_SDP_PARAM_
					memcpy(&g_data[4], (char *)(&g_venc_parm), 16);
					memcpy(&g_data[20], (char *)(&g_audio_parm), 8);
					size = 66;
					#else
					size = 4;
					#endif
					set_nethead(g_MoniDestDeviceNo, PRIRY_DEFAULT);
					net_direct_send(CMD_MONITOR, g_data, size, g_MonitorInfo.address, g_MonitorInfo.port);
				}		
			}	

			// 睡眠时间会影响视频出来快慢
			times = 10;
			while ((times--) > 0 && MONITOR_REQUEST == g_MonitorInfo.state)
			{
				usleep(100*1000);
			}
		}

		// 解决链接转监视太快 UI切换失败问题
		if (time(0) - t0 < 2)
		{
			usleep(500*1000);
		}
	}

	t0 = time(0);
	if(MONITOR_MONITORING == g_MonitorInfo.state)	
	{
		g_MonitorInfo.TimeMax = MONITOR_TIME_MAX;	
		g_MonitorInfo.TimeOut = 0;
		g_MonitorInfo.HeartTime = 0;
		g_RemainTime = 0;
		while (MONITOR_MONITORING == g_MonitorInfo.state)
		{
			g_MonitorInfo.TimeOut = time(0) - t0;
			if (g_MonitorInfo.TimeMax > 0)
			{
				// 剩余时间
				g_RemainTime = g_MonitorInfo.TimeMax - g_MonitorInfo.TimeOut;
				if (g_RemainTime <= 0)
				{
					set_nethead(g_MoniDestDeviceNo, PRIRY_DEFAULT);
					net_direct_send(CMD_STOP_MONITOR, g_buf, 2, g_MonitorInfo.address, g_MonitorInfo.port);
					g_ErrType = MONITOR_MONITORING_TIMEOUT;
					g_MonitorInfo.state = MONITOR_END;
					break;
				}
				else
				{
					GuiNotify(MONITOR_TIMER, g_RemainTime);
					set_nethead(g_MoniDestDeviceNo, PRIRY_DEFAULT);
					net_direct_send(CMD_MONITOR_HEART, g_buf, 2, g_MonitorInfo.address, g_MonitorInfo.port);
				}

				if (g_MonitorInfo.HeartTime > HEART_TIMEOUT)
				{
					g_ErrType = MONITOR_HEART_TIMEOUT;
					g_MonitorInfo.state = MONITOR_END;
					break;
				}
				g_MonitorInfo.HeartTime++;

				times = 10;
				while ((times--) > 0 && (MONITOR_MONITORING == g_MonitorInfo.state))
				{
					usleep(100*1000);
				}
			}
		}
	}

	if (MONITOR_TALKING == g_MonitorInfo.state)
	{
		hw_switch_digit(); 				// 切换到数字对讲 				
		media_set_talk_volume(g_MonitorInfo.DevType, storage_get_talkvolume());
		media_set_mic_volume(storage_get_micvolume());
		if (media_start_net_audio(g_MonitorInfo.address))
		{						
			dprintf("media_start_net_audio return ok\n ");
			g_Audio_Start = 1;			
			media_add_audio_sendaddr(g_MonitorInfo.address, g_MonitorInfo.RemoteAudioPort);
			// add by chenbh 2016-08-22
			media_enable_audio_send();
			media_enable_audio_recv();
		}	
		else
		{						
			dprintf(" media_start_net_audio return error\n ");
			g_MonitorInfo.state = MONITOR_END;
		}
	}
	
	t0 = time(0);
	if (MONITOR_TALKING == g_MonitorInfo.state)
	{				
		dprintf("MONITOR_TALKING == g_MonitorInfo.state \n");
		GuiNotify(g_MonitorInfo.state, 0);

		g_PreMonitorState = MONITOR_TALKING;
		g_MonitorInfo.TimeMax = MONITOR_TALK_TIME_MAX;		
		g_MonitorInfo.TimeOut = 0;
		g_MonitorInfo.HeartTime = 0;
		
		while (MONITOR_TALKING == g_MonitorInfo.state)
		{
			if (g_MonitorInfo.TimeMax > 0)
			{
				g_RemainTime = 0;
				g_MonitorInfo.TimeOut = time(0) - t0;
				// 剩余时间
				//g_RemainTime = g_MonitorInfo.TimeMax - g_MonitorInfo.TimeOut;					
				if (g_MonitorInfo.TimeOut >= g_MonitorInfo.TimeMax)
				{
					dprintf("monitor timer proc : talking time out\n");
					set_nethead(g_MoniDestDeviceNo, PRIRY_DEFAULT);
					net_direct_send(CMD_STOP_MONITOR, g_buf, 2, g_MonitorInfo.address, g_MonitorInfo.port);
					g_ErrType = MONITOR_TALKING_TIMEOUT;
					g_MonitorInfo.state = MONITOR_END;
					break;
				}
				else
				{
					g_RemainTime = g_MonitorInfo.TimeMax - g_MonitorInfo.TimeOut;
					GuiNotify(MONITOR_TIMER, g_RemainTime);
					set_nethead(g_MoniDestDeviceNo, PRIRY_DEFAULT);
					net_direct_send(CMD_MONITOR_HEART, g_buf, 2, g_MonitorInfo.address, g_MonitorInfo.port);
				}
				
				if (g_MonitorInfo.HeartTime > HEART_TIMEOUT)
				{
					g_ErrType = MONITOR_HEART_TIMEOUT;
					g_MonitorInfo.state = MONITOR_END;
					break;
				}
				g_MonitorInfo.HeartTime++;
				
				times = 10;
				while ((times--) > 0 && (MONITOR_TALKING == g_MonitorInfo.state))
				{
					usleep(100*1000);
				}
			}
		}
	}

	// 监视下一个情况 得回到监视请求
	if (MONITOR_REQUEST == g_MonitorInfo.state)
	{
		media_stop_net_video(_RECVONLY);
		goto LabChange;
	}

	dprintf("monitor proc : g_PreMonitorState : %d\n", g_PreMonitorState);
	if (g_Audio_Start == 1)
	{
		g_Audio_Start = 0;
		media_del_audio_send_addr(g_MonitorInfo.address, MEDIA_AUDIO_PORT);
		usleep(10*1000);
		media_stop_net_audio();		
	}

	// 关闭视频接口
	if (g_Video_Start == 1)
	{
		g_Video_Start = 0;
		media_stop_net_video(_RECVONLY);	
	}

	monitor_set_media_ifover(TRUE);
	dprintf("monitor proc : AS_MONITOR_END : g_ErrType : %d\n", g_ErrType);
	//sys_set_monitor_state(FALSE);
	dprintf("monitor proc end!\n");
	g_MonitorInfo.state = MONITOR_END;
	g_PreMonitorState = MONITOR_END;
	GuiNotify(g_MonitorInfo.state, g_ErrType);
	g_ErrType = MONITOR_OK;
	sys_set_monitor_state(FALSE);	
	inter_SetThread(&g_MonitorInfo.mThread);

	pthread_exit(NULL);
	return NULL;             	// 返回后资源由系统释放
}
Esempio n. 20
0
static void NPClientDetachPrepareThread(void)
{
	pthread_create(&preparethread, NULL, NPClientPrepareThread, NULL);
	pthread_detach(preparethread);
}
Esempio n. 21
0
void
xpthread_detach (pthread_t thr)
{
  xpthread_check_return ("pthread_detach", pthread_detach (thr));
}
Esempio n. 22
0
int TRI_DetachThread (TRI_thread_t* thread) {
  return pthread_detach(*thread);
}
Esempio n. 23
0
/*
 * First of all, creates a transaction;
 * then reads the newly created bus path,
 * adds a match to the bus to wait until installation is really finished before notifying the user.
 * finally, calls InstallFiles method, and processes the bus while finished == 0.
 */
void *install_package(void *str) {
    sd_bus_error error = SD_BUS_ERROR_NULL;
    sd_bus_message *mess = NULL;
    sd_bus *install_bus = NULL;
    const char *path;
    int r, inhibit_fd = -1, finished = 0;
    
    r = sd_bus_open_system(&install_bus);
    if (r < 0) {
        print_and_warn(strerror(-r), ERR_LINE);
        goto finish;
    }
    INFO("calling CreateTransaction on bus.");
    r = sd_bus_call_method(install_bus,
                           "org.freedesktop.PackageKit",
                           "/org/freedesktop/PackageKit",
                           "org.freedesktop.PackageKit",
                           "CreateTransaction",
                           &error,
                           &mess,
                           NULL);
    if (r < 0) {
        print_and_warn(error.message, ERR_LINE);
        goto finish;
    }
    if (config.inhibit) {
        inhibit_fd = inhibit_suspend("Package installation...");
    }
    sd_bus_message_read(mess, "o", &path);
    r = sd_bus_add_match(install_bus, NULL, "type='signal',interface='org.freedesktop.PackageKit.Transaction',member='Finished'", match_callback, &finished);
    if (r < 0) {
        print_and_warn(strerror(-r), ERR_LINE);
        goto finish;
    }
    sd_bus_flush(install_bus);
    INFO("calling InstallFiles on bus.");
    r = sd_bus_call_method(install_bus,
                        "org.freedesktop.PackageKit",
                        path,
                        "org.freedesktop.PackageKit.Transaction",
                        "InstallFiles",
                        &error,
                        NULL,
                        "tas",
                        0,
                        1,
                        (char *)str);
    if (r < 0) {
        print_and_warn(error.message, ERR_LINE);
        goto finish;
    }
    while (!finished) {
        r = sd_bus_process(install_bus, NULL);
        if (r > 0) {
            continue;
        }
        r = sd_bus_wait(install_bus, (uint64_t) -1);
        if (r < 0) {
            break;
        }
    }

finish:
    stop_inhibition(inhibit_fd);
    close_bus(&error, mess, install_bus);
    pthread_detach(pthread_self());
    pthread_exit(NULL);
}
Esempio n. 24
0
Thread::~Thread()
{
	pthread_detach(pthId_);
	isRunning_ = false;
}
Esempio n. 25
0
void *jalls_handler(void *thread_ctx_p) {
	if (!thread_ctx_p) {
		return NULL; //should never happen.
	}

	struct jalls_thread_context *thread_ctx = NULL;
	thread_ctx = thread_ctx_p;
	pid_t *pid = NULL;
	uid_t *uid = NULL;
	int debug = thread_ctx->ctx->debug;
	int err = pthread_detach(pthread_self());
	if (err < 0) {
		if (debug) {
			fprintf(stderr, "Failed to detach the thread\n");
		}
		goto out;
	}

	while (!should_exit) {

		// read protocol version, message type, data length,
		// metadata length and possible fd.
		uint16_t protocol_version;
		uint16_t message_type;
		uint64_t data_len;
		uint64_t meta_len;
		int msg_fd = -1;

		struct msghdr msgh;
		memset(&msgh, 0, sizeof(msgh));

		struct iovec iov[4];
		iov[0].iov_base = &protocol_version;
		iov[0].iov_len = sizeof(protocol_version);
		iov[1].iov_base = &message_type;
		iov[1].iov_len = sizeof(message_type);
		iov[2].iov_base = &data_len;
		iov[2].iov_len = sizeof(data_len);
		iov[3].iov_base = &meta_len;
		iov[3].iov_len = sizeof(meta_len);

		msgh.msg_iov = iov;
		msgh.msg_iovlen = 4;

		char msg_control_buffer[CMSG_SPACE(sizeof(msg_fd))];

		msgh.msg_control = msg_control_buffer;
		msgh.msg_controllen = sizeof(msg_control_buffer);

#ifdef SO_PEERCRED
		struct ucred cred;
		memset(&cred, 0, sizeof(cred));
		pid = &cred.pid;
		uid = &cred.uid;
		*pid = -1;
		*uid = 0;
		socklen_t cred_len = sizeof(cred);
		if (-1 == getsockopt(thread_ctx->fd, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len)) {
			if (debug) {
				fprintf(stderr, "failed receiving peer crendentials\n");
			}
		}
#endif
#ifdef SCM_UCRED
		ucred_t *cred = NULL;
		pid_t tmp_pid = -1;
		uid_t tmp_uid = 0;
		pid = &tmp_pid;
		uid = &tmp_uid;
		if (-1 == getpeerucred(thread_ctx->fd, &cred)) {
			if (debug) {
				fprintf(stderr, "failed receiving peer credentials\n");
			}
		} else {
			tmp_pid = ucred_getpid(cred);
			tmp_uid = ucred_geteuid(cred);
			ucred_free(cred);
		}
#endif
		
		ssize_t bytes_recv = jalls_recvmsg_helper(thread_ctx->fd, &msgh, debug);
		if (bytes_recv < 0) {
			if (debug) {
				fprintf(stderr, "Failed to receive the message header\n");
			}
			goto out;
		}
		if (bytes_recv == 0) {
			if (debug) {
				fprintf(stderr, "The peer has shutdown\n");
			}
			goto out;
		}

		//receive fd
		struct cmsghdr *cmsg;
		cmsg = CMSG_FIRSTHDR(&msgh);
		while (cmsg != NULL) {
			if (cmsg->cmsg_level == SOL_SOCKET) {
				if (cmsg->cmsg_type == SCM_RIGHTS && cmsg->cmsg_len == CMSG_LEN(sizeof(msg_fd))) {
					if (message_type != JALLS_JOURNAL_FD_MSG) {
						if (debug) {
							fprintf(stderr, "received an fd for a message type that was not journal_fd\n");
						}
						goto out;
					}
					void *tmp_fd = CMSG_DATA(cmsg);
					if (debug && msg_fd != -1) {
						fprintf(stderr, "received duplicate ancillary data: overwrote the fd\n");
					}
					msg_fd = *((int *)tmp_fd);
					if (msg_fd < 0) {
						if (debug) {
							fprintf(stderr, "received an fd < 0\n");
						}
						goto out;
					}
				} else {
					if (debug) {
						fprintf(stderr, "received unrecognized ancillary data\n");
					}
					goto out;
				}
			}
			cmsg = CMSG_NXTHDR(&msgh, cmsg);
		}

		thread_ctx->peer_pid = *pid;
		thread_ctx->peer_uid = *uid;
		if (debug && *pid == -1) {
			thread_ctx->peer_pid = 0;
			thread_ctx->peer_uid = 0;

			fprintf(stderr, "Did not receive credentials\n");
		}

		if (protocol_version != 1) {
			if (debug) {
				fprintf(stderr, "received protocol version != 1\n");
			}
			return NULL;
		}

		//call appropriate handler
		switch (message_type) {
			case JALLS_LOG_MSG:
				err = jalls_handle_log(thread_ctx, data_len, meta_len);
				break;
			case JALLS_AUDIT_MSG:
				err = jalls_handle_audit(thread_ctx, data_len, meta_len);
				break;
			case JALLS_JOURNAL_MSG:
				err = jalls_handle_journal(thread_ctx, data_len, meta_len);
				break;
			case JALLS_JOURNAL_FD_MSG:
				if (msg_fd < 0) {
					if (debug) {
						fprintf(stderr, "Message type is journal_fd, but no fd was received\n");
					}
					goto out;
				}
				err = jalls_handle_journal_fd(thread_ctx, data_len, meta_len, msg_fd);
				break;
			default:
				if (debug) {
					fprintf(stderr, "Message type is not legal.\n");
				}
				goto out;
		}
		if (err < 0) {
			goto out;
		}
	}

out:
	close(thread_ctx->fd);
	free(thread_ctx);
	return NULL;
}
Esempio n. 26
0
int main(int argc, char *argv[])
{
	int fd = -1, newfd = -1;

	struct sockaddr_in sin;

      int serv_port = SERV_PORT;

        /* 参数处理*/
        if( argc >2 ) {
                usage(argv[0]);
                exit(EXIT_FAILURE);
        }
        if(argc == 2) {
                serv_port = atoi(argv[1]);
        } 

        /* 1.创建套接字*/	
	if( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("socket");
		exit(1);
	}

	/* 2. 绑定 */
	/*2.1 填充sockaddr_in结构体,填充绑定的IP地址和端口号 */
	sin.sin_family = AF_INET;
	sin.sin_port = htons(SERV_PORT);
#if 0	
	if(inet_pton(AF_INET,SERV_IP, &sin.sin_addr) != 1) {
		perror("inet_pton");
		exit(EXIT_FAILURE);
	}
#else
	sin.sin_addr.s_addr = htonl(INADDR_ANY);
#endif
	bzero(sin.sin_zero, 8); 

	/* 允许地址快速重用 **/       
	int b_reuse =1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof(int));

	/* 2.2 调用bind()函数去绑定在本地的某个IP地址+端口上*/
	if(bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
		perror("bind");
		exit(EXIT_FAILURE);
	}

	/* 3.把套接字变成被动套接字 */
	listen(fd, BACKLOG);
	printf("server staring....OK!\n");

	/*4. 阻塞等待客户端连接 */
while(1) {

	struct sockaddr_in cin;
        int clen = sizeof(cin);
	pthread_t tid;
	struct cli_info *pInfo = NULL;

        newfd = accept(fd, (struct sockaddr *)&cin, &clen); /*阻塞等待客户端的连接请求*/
	pInfo = (struct cli_info *)malloc(sizeof(struct cli_info));
	
	/* 填充客户端信息的的结构体*/
	pInfo->cli_fd = newfd;
	memcpy(&pInfo->cin, &cin, sizeof(cin));

	//FIXME!!
	//...把pInfo加到主线程的客户端信息链表中	

	pthread_create(&tid, NULL, cli_data_handler, (void *)pInfo);
	pthread_detach(tid);
}
	close(fd);
	return 0;
}
Esempio n. 27
0
//-----------------------------------------------------------------------------
void* thread_func(void* param)
{
	thread_param* th_param = (thread_param*)param;
	process_events_and_channel_data_from_plugin(th_param);
	pthread_detach(pthread_self());
}
int main(int argc, char *argv[])
{
  int fd, sock_server, sock_client;
  pthread_t thread;
  void *(*handler[4])(void *) =
  {
    rx_ctrl_handler,
    rx_data_handler,
    tx_ctrl_handler,
    tx_data_handler
  };
  void *cfg, *sts;
  char *end, *name = "/dev/mem";
  struct sockaddr_in addr;
  uint16_t port;
  uint32_t command;
  ssize_t result;
  int yes = 1;
  long number;

  errno = 0;
  number = (argc == 2) ? strtol(argv[1], &end, 10) : -1;
  if(errno != 0 || end == argv[1] || number < 1 || number > 2)
  {
    printf("Usage: sdr-transceiver 1|2\n");
    return EXIT_FAILURE;
  }

  if((fd = open(name, O_RDWR)) < 0)
  {
    perror("open");
    return EXIT_FAILURE;
  }

  switch(number)
  {
    case 1:
      port = 1001;
      cfg = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40000000);
      sts = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40001000);
      rx_data = mmap(NULL, 2*sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40002000);
      tx_data = mmap(NULL, 2*sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40004000);
      break;
    case 2:
      port = 1002;
      cfg = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40006000);
      sts = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40007000);
      rx_data = mmap(NULL, 2*sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40008000);
      tx_data = mmap(NULL, 2*sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x4000A000);
      break;
  }

  gpio = ((uint16_t *)(cfg + 0));

  rx_freq = ((uint32_t *)(cfg + 4));
  rx_rate = ((uint32_t *)(cfg + 8));
  rx_cntr = ((uint16_t *)(sts + 0));

  tx_freq = ((uint32_t *)(cfg + 12));
  tx_rate = ((uint32_t *)(cfg + 16));
  tx_cntr = ((uint16_t *)(sts + 2));

  /* set PTT pin to low */
  *gpio = 0;

  /* set default rx phase increment */
  *rx_freq = (uint32_t)floor(600000/125.0e6*(1<<30)+0.5);
  /* set default rx sample rate */
  *rx_rate = 625;

  /* set default tx phase increment */
  *tx_freq = (uint32_t)floor(600000/125.0e6*(1<<30)+0.5);
  /* set default tx sample rate */
  *tx_rate = 625;

  if((sock_server = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    perror("socket");
    return EXIT_FAILURE;
  }

  setsockopt(sock_server, SOL_SOCKET, SO_REUSEADDR, (void *)&yes , sizeof(yes));

  /* setup listening address */
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  addr.sin_port = htons(port);

  if(bind(sock_server, (struct sockaddr *)&addr, sizeof(addr)) < 0)
  {
    perror("bind");
    return EXIT_FAILURE;
  }

  listen(sock_server, 1024);

  while(1)
  {
    if((sock_client = accept(sock_server, NULL, NULL)) < 0)
    {
      perror("accept");
      return EXIT_FAILURE;
    }

    result = recv(sock_client, (char *)&command, 4, MSG_WAITALL);
    if(result <= 0 || command > 3 || sock_thread[command] > -1)
    {
      close(sock_client);
      continue;
    }

    sock_thread[command] = sock_client;

    if(pthread_create(&thread, NULL, handler[command], NULL) < 0)
    {
      perror("pthread_create");
      return EXIT_FAILURE;
    }
    pthread_detach(thread);
  }

  close(sock_server);

  return EXIT_SUCCESS;
}
Esempio n. 29
0
File: x.c Progetto: childhood/parcle
int
main(int argc, char *argv[])
{
	fd_set              rfds, wfds;
	struct cn_strct    *tp, *to;
	int                 rnum, wnum, readsocks;
	int                 i;
	struct    tm       *tm_struct;

	/* initialize the masterdate we update only every second */
	_Last_loop = time(NULL);
	tm_struct  = gmtime(&_Last_loop);
	strftime( _Master_date, 32, "%a, %d %b %Y %H:%M:%S %Z", tm_struct);
#if DEBUG_VERBOSE == 2
	_Conn_count=0;
#endif
#if DEBUG_VERBOSE == 1
	printf("STARTED AT: %s\n", _Master_date);
#endif

	signal(SIGQUIT, die);
	signal(SIGTERM, die);
	signal(SIGPIPE, check_sockets);
	signal(SIGINT,  clean_on_quit);

	/* Fill up the initial connection lists; _Free_conns is just a LIFO stack,
	 * there shall never be a performance issues -> single linked only */
	_Free_count=0;
	for (i = 0; i < INITIAL_CONNS; i++) {
		tp = _Free_conns;
		_Free_conns = (struct cn_strct *) calloc(1, sizeof(struct cn_strct));
		_Free_conns->data_buf_head =
			(char *) calloc (RECV_BUFF_LENGTH, sizeof (char));
		_Free_conns->c_next = tp;
		_Free_conns->c_prev = NULL;
		_Free_conns->q_prev = NULL;
		_Free_conns->identifier = _Conn_count++;
		_Free_count++;
	}

	/* create the master listener */
	if ((_Master_sock = create_listener(HTTP_PORT)) == -1) {
		fprintf(stderr, "ERR: Couldn't bind to port %d\n",
				HTTP_PORT);
		exit(1);
	}

	/* set up LIFO queue */
	_Queue_tail = _Queue_head = NULL;
	_Queue_count = 0;

	/* create workers for application */
	for(i = 0; i < WORKER_THREADS; i++) {
		pthread_create(&_Workers[i], NULL, &run_app_thread, (void *) &i);
	}
	sleep(1);
	for(i = 0; i < WORKER_THREADS; i++) {
		pthread_detach( _Workers[i] );
	}

#if DEBUG_VERBOSE == 1
	printf("%s: listening on port %d (http)\n",
			_Server_version, HTTP_PORT);
#endif

	/* main loop */
	while (1) {
		// clean socket lists
		FD_ZERO(&rfds);
		FD_ZERO(&wfds);
		wnum = -1;

		// Add master listener to reading sockets
		FD_SET(_Master_sock, &rfds);
		rnum = _Master_sock;

		// Add the established sockets
		tp = _Busy_conns;

		/* Adding connection to the SocketSets based on state */
		while (tp != NULL) {
			if (REQSTATE_READ_HEAD == tp->req_state) {
				FD_SET(tp->net_socket, &rfds);
				rnum = (tp->net_socket > rnum) ? tp->net_socket : rnum;
			}
			if (REQSTATE_SEND_FILE == tp->req_state) {
				FD_SET(tp->net_socket, &wfds);
				wnum = (tp->net_socket > wnum) ? tp->net_socket : wnum;
			}
			tp = tp->c_next;
		}

		readsocks = select(
			(wnum > rnum) ? wnum+1 : rnum+1,
			(-1 != rnum)  ? &rfds : NULL,
			(-1 != wnum)  ? &wfds : NULL,
			(fd_set *) 0,
			NULL
		);

		// is the main listener in the read set? -> New connection
		if (FD_ISSET(_Master_sock, &rfds)) {
			handle_new_conn(_Master_sock);
			readsocks--;
		}

		// Handle the established sockets
		tp = _Busy_conns;

		while (readsocks > 0 && tp != NULL) {
			to = tp;
			tp = tp->c_next;

			if (REQSTATE_READ_HEAD == to->req_state &&
			  FD_ISSET(to->net_socket, &rfds)) {
				readsocks--;
#if DEBUG_VERBOSE == 1
				printf("WANNA RECV HEAD\n");
#endif
				read_request(to);
			}
			if (REQSTATE_SEND_FILE == to->req_state &&
			  FD_ISSET(to->net_socket, &wfds)) {
				readsocks--;
#if DEBUG_VERBOSE == 1
				printf("WANNA SEND FILE\n");
#endif
				send_file(to);
			}
		}
	}
	return 0;
}
Esempio n. 30
0
/*
 * The thread start routine for crew threads. Waits in the rngBlkGet()
 * call  where address of workQEntries are received, then processes work items until requested to shut down.
 *
 * For none active Receivers/DDRs their cmd will set to -1 , thus they will
 *  pend immediately.
 *
 *     Author:  Greg Brissey
 */
void *worker_routine (void *arg)
{
   int status;
   WORKQ_ENTRY_ID  pWrkQentry;
   RCVR_DESC_ID pRcvrDesc;
   WORKQINVARIENT_ID pWrkqInvar;
   int inQueue;
   int processThreadFlag;
   char *CntlrId;

   RCVR_DESC_ID pAccessWrkDesc = (RCVR_DESC_ID) arg; 
   if (pAccessWrkDesc == &ProcessThread)
      processThreadFlag = 1;
   else
      processThreadFlag = 0;

   CntlrId = pAccessWrkDesc->cntlrId;
   DPRINT3(+2,"'%s':  threadId: 0x%lx, RCVR_DESC_ID: 0x%lx,  starting\n", 
         CntlrId,pAccessWrkDesc->threadID,pAccessWrkDesc);

    pThreadBlockAllSigs();   /* block most signals here */

    pthread_detach(pAccessWrkDesc->threadID);   /* if thread terminates no need to join it to recover resources */

    while (1) {

	/* obtain work from the pipe line Q, if non the thread blocks */
        rngBlkGet(pAccessWrkDesc->pInputQ, &pWrkQentry,1);

        if (!processThreadFlag)
           incrActiveCntlrStatus(CntlrId);
             
        pRcvrDesc = (RCVR_DESC_ID) pWrkQentry->pInvar->pRcvrDesc;


        DPRINT2(+2,"'%s': Got workQ: 0x%lx\n", pRcvrDesc->cntlrId, pWrkQentry);
        inQueue = rngBlkNElem(pRcvrDesc->pInputQ);
        DPRINT2(+2,"'%s': work still in Q: %d\n", pRcvrDesc->cntlrId, inQueue);

#define INSTRUMENT
#ifdef INSTRUMENT
        if (inQueue >  pRcvrDesc->p4Diagnostics->pipeHighWaterMark)
             pRcvrDesc->p4Diagnostics->pipeHighWaterMark = inQueue;
#endif

        DPRINT2(+2,"'%s': Got workQ: 0x%lx\n", pAccessWrkDesc->cntlrId, pAccessWrkDesc);
        DPRINT2(+2,"'%s': work still in Q: %d\n", pAccessWrkDesc->cntlrId, rngBlkNElem(pAccessWrkDesc->pInputQ));

        status = (pAccessWrkDesc->pCallbackFunc)(pWrkQentry);

        /* if status is not < 0 then send workQ on to next stage
         * if status < 0 then there is an error or the function call already
         * handled the passing to the next stage and this routine does not need to
         */
        DPRINT2(+2,"'%s': CallBack Returned: %d\n", pRcvrDesc->cntlrId, status);
        if (status  >= 0)
        {
           DPRINT2(+2,"'%s': Done,  Send WorkQ onto Processing Thread: 0x%lx\n", 
		pRcvrDesc->cntlrId, pRcvrDesc);
           rngBlkPut(pAccessWrkDesc->pOutputQ, &pWrkQentry,1);
        }
        if (!processThreadFlag)
           decActiveCntlrStatus(CntlrId);
    }
}