예제 #1
0
int main()
{
    initSignal();

    // initLog();

    AlarmManager * pM   = new AlarmManager();

    while(true)
    {
        if(pM->Init() == true)
            break;

        gAlmLog->ERROR("%-24s| alarm manager init fail",
            "main");

        poll(NULL, 0, 5 * 1000);
    }

    while(true)
        pM->Do();

    pM->Final();

    gAlmLog->WARNING("%-24s| ALM TERMINATED",
        "main");

    finalLog();

    return 0;
}
예제 #2
0
void Contest::init() {
	logMsg("Initialize Database...");
	initDB();
	logMsg("done\n");

/*  logMsg("Load codes into RAM...");
  loadCodes();
  logMsg("done\n");*/

	logMsg("Initialize Prizes...");
  if (SetupPrizes == true) {
  	setupPrizes();
    logMsg("done\n");
  } else
    logMsg("Already initialized.\n");

  logMsg("Started signal handler...");
	initSignal();
	logMsg("done\n");

 	logMsg("Started thread engine...");
	initThreads(iaddr);
	logMsg("done\n");
  
  current_day		= 0;
	current_week	= 0;
	current_month	= 0;
	
  return;
}
예제 #3
0
파일: station2.c 프로젝트: FEx79/3eme
int main(void)
{
    initSignal();
    
    // Initialise les mutex
    pthread_mutex_init(&mutex_received, NULL);
    pthread_mutex_init(&mutex_give, NULL);
    
    // Cree un thread qui ecoutera ce que la station 1 et 3 lui dira
    if(pthread_create(&receive_1, NULL, receiveFrom1, NULL) != 0 ||
       pthread_create(&receive_3, NULL, receiveFrom3, NULL) != 0) {
        printf("Erreur thread\n");
        return 1;
    }
    
    // Attend que le serveur d'~coute soit lanc~
    printf("Appuyez sur une touche lorsque station 1 et station 3 seront lance ...\n");
    while(kbhit() == 0);
    
    initSend(&station_1, ADDR_STATION_1, PORT_LISTEN_1_2);
    initSend(&station_3, ADDR_STATION_3, PORT_LISTEN_3_2);
    
    initLink();
        
    // Boucle principale
    while(1) {
        reinitialise();
        processPiece();
    }
    
    return 0;
}
예제 #4
0
void Call::playInit()
{
#ifdef REN_DEBUG
	qWarning("Call::playInit()");
#endif
	if (!mutePlay)
		emit initSignal(id);
}
StatisticEmailSender::StatisticEmailSender()
{
	QThread* th = new QThread;
	th->start();
	moveToThread(th);

	connect(this, SIGNAL(initSignal()), SLOT(initSlot()));
	connect(this, SIGNAL(destroyed()), th, SLOT(deleteLater()));
}
int initSemaphore(semaphore_t *p_semaphore, unsigned int p_maxValue)
{
	int ret = initSignal(&(p_semaphore->signal));
	if(ret != 0)
		return ret;
	
	p_semaphore->value = 0;
	p_semaphore->maxValue = p_maxValue;
	
	return ret;
}
예제 #7
0
파일: skpSignal.cpp 프로젝트: yefy/skp
SkpSignal::SkpSignal() :
    SkpObjectData(*new SkpSignalPrivate())
{
    /*
    m_eventRead = new SkpEventRead();
    m_eventRead->connect(m_pipe.notifyRead(), std::bind(&SkpSignal::onSigno, this, std::placeholders::_1));
    m_eventRead->start(0);
    */

    initSignal();
}
예제 #8
0
DetailEditWidget::DetailEditWidget(QToolBox* toolbox,QWidget* parent):
	QWidget(parent),Ui::detailEditForm()
{
	setupUi(this);
	this->mode = MODE_CREATE;
	this->labelTitle->setText(QString::fromUtf8("Ajout d'un nouveau film"));
	this->btnEditer->setText(QString::fromUtf8("Ajouter"));
	this->film = NULL;
	this->toolBox = toolbox;
	loadHoraire();
	initSignal();
}
예제 #9
0
DetailEditWidget::DetailEditWidget(Film* f, QToolBox* toolbox, QWidget* parent):
	QWidget(parent),Ui::detailEditForm()
{
	setupUi(this);
	this->mode = MODE_EDIT;
	this->labelTitle->setText(QString::fromUtf8("Édition"));
	this->film=f;
	this->toolBox = toolbox;
	this->textEdit->setText(QString::fromUtf8(f->getName().c_str()));
	this->te_synopsis->setText(QString::fromUtf8(f->getSynopsis().c_str()));
	loadHoraire();
	initSignal();
}
bool SenderObject::qt_emit( int _id, QUObject* _o )
{
    switch ( _id - staticMetaObject()->signalOffset() ) {
    case 0:
        initSignal((QUnknownInterface*)static_QUType_iface.get(_o+1));
        break;
    case 1:
        acceptSignal((QUnknownInterface*)static_QUType_iface.get(_o+1));
        break;
    default:
        return QObject::qt_emit(_id,_o);
    }
    return TRUE;
}
예제 #11
0
void wyliodrinSetup()
{
	wiringSetup ();
	//wyliodrin_port, wyliodrin_project, wyliodrin_session, wyliodrin_userid - environment variables
	char * val = getenv("wyliodrin_port");
	int port = 0;
	if(val != NULL)
		port = atoi(val);
	if(port == 0)
		port = 6379;

	char *projectId = getenv("wyliodrin_project");
	//printf("projid = %s\n", projectId);
	char *sessionId = getenv("wyliodrin_session");
	char *userid = getenv("wyliodrin_userid");
	//printf("port = %d\nprojectid = %s\nsessionid = %s\nuserid=%s\n",port,projectId,sessionId,userid);
	initSignal(port, projectId, sessionId, userid);
	// signalSetup ();
}
예제 #12
0
// renyang - 只是用來判斷完成某件事情的訊號
void Receiver::emitSignal(signal_type type)
{
#ifdef REN_DEBUG
	qWarning(QString("Receiver::emitSignal(signal_type %1)").arg(type));
#endif
	switch(type)
	{
		case SIGNAL_FINISH:
			emit finishSignal();
			break;
		if (working)
		{
			case SIGNAL_INIT:
				emit initSignal();
				break;
			case SIGNAL_RING:
				emit ringSignal();
				break;
			// renyang - 回覆答鈴
			case SIGNAL_RINGREPLY:
				emit ringReplySignal();
				break;
			case SIGNAL_SENDNEWKEY:
				emit sendNewKey();
				break;
			case SIGNAL_KEYREQUEST:
				emit keyRequest();
				break;
			case SIGNAL_NEWKEY:
				QString text = blowfish->isAsciiKey() ? blowfish->getPass() : "random key";
				emit newKey(text);
				break;
		}
		default:
			break;
	}
}
예제 #13
0
//---------------------------------------------------------------------------
int ACE_MAIN(int argc, ACE_TCHAR  *argv[])
{
	// 환경설정 (제일 먼저 초기화 해야함)
	procArguments(argc, argv);

	// 로그
	if(initLog() < 0)
	{
		printf("로그 초기화를 실패했으므로 프로그램을 종료합니다.\n");
		return -1;
	}

	//-----------------------------------------------------------------------
	// 데몬 만들기 
	//-----------------------------------------------------------------------
	// acceptor 가 초기화 된 후 데몬을 만들게 되면, 부모프로세스가 제거되면서
	// listen 소켓도 같이 제거된다. 그러므로 acceptor 를 초기화 하기 전에
	// 데몬을 먼저 만들어야 한다.
	if(Config::instance()->process.daemon == true)
	{
		if(makeDaemon() < 0)
		{
			printf("데몬으로 만들기를 실패했으므로 프로그램을 종료합니다.\n");
			return -1;
		}
	}
	
	PAS_NOTICE1("%s", compile_date);

	// 시그널 핸들러
	PasSignalHandler* pSignalHandler = new PasSignalHandler;
	initSignal(pSignalHandler);

	//------------------
	// 각 모듈의 초기화
	//------------------
	HTTP::Request::HeaderBuffBytes = HTTP::Response::HeaderBuffBytes = Config::instance()->process.HttpHeaderBufferBytes;
	
	increseFdLimit();

	
	// PAS 공식 로그
	char hostName[32];

	gethostname(hostName, sizeof(hostName)-1);
	PasDataLog::setPasAddr(hostName);
	
	// 메모리 매니저 초기화
	//initMessageBlockManager();
	if (readMBconfig() < 0)
	{
		printf("메모리 풀 컨피그 설정값을 확인하세요.\n");
		PAS_ERROR("메모리 풀 컨피그 설정값을 확인하세요.\n");
		return -1;
	}

	const int numWorkerThread = Config::instance()->thread.numWorker;

	// 리액터
	ACE_Reactor* pReactor = ReactorPool::instance()->createMaster();
	
	ReactorPool::instance()->createWorkers(numWorkerThread);

	ACE_Reactor* pGlobalReactor = ACE_Reactor::instance();

	PAS_NOTICE3("REACTOR: Master=%X, Global=%X, Master=%x", 
		pReactor,  pGlobalReactor, ReactorPool::instance()->masterReactor());

	// Listen 포트 설정
	PAS_NOTICE("Listen Socket Activate");
	PasAcceptor* pAcceptor = new PasAcceptor(pReactor);
	
	const int listenPort = Config::instance()->network.listenPort;

	// mIDC 내의 서버를 감시하는 쪽에 mwatch 전달하기 위해 메시지 작성한다.
	Util2::setMwatchMsg(listenPort);

	// acceptor 기동 
	if(pAcceptor->open(listenPort) < 0)
	{
		PAS_ERROR1("Listen 소켓 생성 실패, Port[%d]\n", listenPort);
		PAS_ERROR("프로그램 종료\n");

		printf("Listen 소켓 생성 실패, Port[%d]\n", listenPort);
		printf("프로그램 종료\n");
		return -1;
	}

	// 쓰레드 매니저
	ACE_Thread_Manager* pTManager = ACE_Thread_Manager::instance();	

	// monitor 보고리를 위한 thread 를 생성한다.
	MonitorReporter *monitor = MonitorReporter::instance(pTManager);
	monitor->activate(THR_NEW_LWP | THR_JOINABLE);

	WatchReporter *watch = WatchReporter::instance(pTManager);
	watch->activate(THR_NEW_LWP | THR_JOINABLE);

	// UserInfo 관리를 위한 thread 를 생성한다.
	UserInfoMng *userInfoMng = UserInfoMng::instance(pTManager);
	userInfoMng->activate(THR_NEW_LWP | THR_JOINABLE);
	
	// phone trace 를 위한 thread 를 생성한다.
	PhoneTraceMng *phoneTraceMng = PhoneTraceMng::instance(pTManager);
	phoneTraceMng->setDataFile((char*)"trace.acl");
	phoneTraceMng->activate(THR_NEW_LWP | THR_JOINABLE);

	// 공지 처리 (Stat Filter)  를 위한 thread 를 생성한다.
	StatFilterMng *statFilterMng = StatFilterMng::instance(pTManager);
	statFilterMng->setDataFile((char*)"k_stat.cfg");
	statFilterMng->activate(THR_NEW_LWP | THR_JOINABLE);

	// ACL 초기화
	if(Config::instance()->acl.enable)
		initACL();

	CGI::cgiSetupConstants();
	
	// Create AuthAgent Thread
	AuthAgent *authAgent = AuthAgent::instance(pTManager);
	authAgent->activate(THR_NEW_LWP | THR_JOINABLE);

	//usleep(1000);
	
	// 내부 정보 (sysinfo) 출력를 위한 Thread
	SysInfo  *sysInfo = SysInfo::instance(pTManager);
	sysInfo->activate(THR_NEW_LWP | THR_JOINABLE);

	// hash key 로그 작성을 위한 초기화.
	HashKey::prepare();
	
	// 로그 화일을 먼저 만들어 놓는다.  테스트시에 편하다. (tail -f )
	PasDataLog::instance();
	
	// accept event 핸들러 등록
	pReactor->register_handler(pAcceptor, ACE_Event_Handler::ACCEPT_MASK);

	// 이벤트 디멀티플렉싱
	PAS_NOTICE("Master Reactor Start");
	pReactor->run_event_loop();
	PAS_NOTICE("Master Reactor Stop");

	ReactorPool::instance()->stopWorkers();


	/*--- Reactor 가 종료된 경우 아래 라인으로 진행된다. ---*/

	stopACL(); // ACL 종료
	userInfoMng->stop();
	monitor->stop();
	watch->stop();
	phoneTraceMng->putq(new ACE_Message_Block());
	statFilterMng->putq(new ACE_Message_Block());
	sysInfo->putq(new ACE_Message_Block());
	authAgent->putq(new ACE_Message_Block());

	DNS::Manager::instance()->removeAllQuerier();
	
	// 모든 쓰레드 종료 대기
	PAS_NOTICE("Waiting for all threads to stop");
	pTManager->wait();

	delete phoneTraceMng;
	delete statFilterMng;
	delete sysInfo;
	// 생성한 동적 객체 삭제
	delete pSignalHandler;
	
	PAS_NOTICE("======= PAS GW Stop =======");

	return 0;
}
예제 #14
0
void StatisticEmailSender::init()
{
	Q_EMIT initSignal();
}
예제 #15
0
void LinuxSEH::init() {
	initSignal(SIGSEGV);
	initSignal(SIGBUS);
	initSignal(SIGILL);
	initSignal(SIGABRT);
}
예제 #16
0
파일: psid.c 프로젝트: ParaStation/psmgmt
int main(int argc, const char *argv[])
{
    poptContext optCon;   /* context for parsing command-line options */

    int rc, version = 0, debugMask = 0, pipeFD[2] = {-1, -1}, magic = FORKMAGIC;
    char *logdest = NULL, *configfile = "/etc/parastation.conf";
    FILE *logfile = NULL;

    struct poptOption optionsTable[] = {
	{ "debug", 'd', POPT_ARG_INT, &debugMask, 0,
	  "enable debugging with mask <mask>", "mask"},
	{ "configfile", 'f', POPT_ARG_STRING, &configfile, 0,
	  "use <file> as config-file (default is /etc/parastation.conf)",
	  "file"},
	{ "logfile", 'l', POPT_ARG_STRING, &logdest, 0,
	  "use <file> for logging (default is syslog(3))."
	  " <file> may be 'stderr' or 'stdout'", "file"},
	{ "version", 'v', POPT_ARG_NONE, &version, 0,
	  "output version information and exit", NULL},
	POPT_AUTOHELP
	{ NULL, '\0', 0, NULL, 0, NULL, NULL}
    };

    optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
    rc = poptGetNextOpt(optCon);

    /* Store arguments for later modification in forwarders, etc. */
    PSID_argc = argc;
    PSID_argv = argv;

    if (version) {
	printVersion();
	return 0;
    }

    if (logdest) {
	if (strcasecmp(logdest, "stderr")==0) {
	    logfile = stderr;
	} else if (strcasecmp(logdest, "stdout")==0) {
	    logfile = stdout;
	} else {
	    logfile = fopen(logdest, "a+");
	    if (!logfile) {
		char *errstr = strerror(errno);
		fprintf(stderr, "Cannot open logfile '%s': %s\n", logdest,
			errstr ? errstr : "UNKNOWN");
		exit(1);
	    }
	}
    }

    if (!logfile) {
	openlog("psid", LOG_PID|LOG_CONS, LOG_DAEMON);
    }
    PSID_initLogs(logfile);

    printWelcome();

    if (rc < -1) {
	/* an error occurred during option processing */
	poptPrintUsage(optCon, stderr, 0);
	PSID_log(-1, "%s: %s\n",
		 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		 poptStrerror(rc));
	if (!logfile)
	    fprintf(stderr, "%s: %s\n",
		    poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		    poptStrerror(rc));

	return 1;
    }

    /* Save some space in order to modify the cmdline later on */
    PSC_saveTitleSpace(PSID_argc, PSID_argv, 1);

    if (logfile!=stderr && logfile!=stdout) {
	/* Daemonize only if neither stdout nor stderr is used for logging */
	if (pipe(pipeFD) < 0) {
	    PSID_exit(errno, "unable to create pipe");
	}

	/* Start as daemon */
	switch (fork()) {
	case -1:
	    PSID_exit(errno, "unable to fork server process");
	    break;
	case 0: /* I'm the child (and running further) */
	    close (pipeFD[0]);
	    break;
	default: /* I'm the parent and exiting */
	    close (pipeFD[1]);

	    /* Wait for child's magic data */
	    rc = read(pipeFD[0], &magic, sizeof(magic));
	    if (rc != sizeof(magic) || magic != (FORKMAGIC)) return -1;

	    return 0;
       }
    }

#define _PATH_TTY "/dev/tty"
    /* First disconnect from the old controlling tty. */
    {
	int fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
	if (fd >= 0) {
	    if (ioctl(fd, TIOCNOTTY, NULL)) {
		PSID_warn(-1, errno, "%s: ioctl(TIOCNOTTY)", __func__);
	    }
	    close(fd);
	}
    }


    /*
     * Disable stdin,stdout,stderr and install dummy replacement
     * Take care if stdout/stderr is used for logging
     */
    {
	int dummy_fd;

	dummy_fd=open("/dev/null", O_WRONLY , 0);
	dup2(dummy_fd, STDIN_FILENO);
	if (logfile!=stdout) dup2(dummy_fd, STDOUT_FILENO);
	if (logfile!=stderr) dup2(dummy_fd, STDERR_FILENO);
	close(dummy_fd);
    }

    /* Forget about inherited window sizes */
    unsetenv("LINES");
    unsetenv("COLUMNS");

    if (debugMask) {
	PSID_setDebugMask(debugMask);
	PSC_setDebugMask(debugMask);
	PSID_log(-1, "Debugging mode (mask 0x%x) enabled\n", debugMask);
    }

    /* Init the Selector facility as soon as possible */
    if (!Selector_isInitialized()) Selector_init(logfile);
    PSID_registerLoopAct(Selector_gc);

    /* Initialize timer facility explicitely to ensure correct logging */
    if (!Timer_isInitialized()) Timer_init(logfile);

    /*
     * Create the Local Service Port as early as possible. Actual
     * handling is enabled later. This gives psiadmin the chance to
     * connect. Additionally, this will guarantee exclusiveness
     */
    PSID_createMasterSock(PSmasterSocketName);

    PSID_checkMaxPID();

    /* read the config file */
    PSID_readConfigFile(logfile, configfile);
    /* Now we can rely on the config structure */

    {
	in_addr_t addr;

	PSID_log(-1, "My ID is %d\n", PSC_getMyID());

	addr = PSIDnodes_getAddr(PSC_getMyID());
	PSID_log(-1, "My IP is %s\n", inet_ntoa(*(struct in_addr *) &addr));
    }

    if (!logfile && PSID_config->logDest!=LOG_DAEMON) {
	PSID_log(-1, "Changing logging dest from LOG_DAEMON to %s\n",
		 PSID_config->logDest==LOG_KERN ? "LOG_KERN":
		 PSID_config->logDest==LOG_LOCAL0 ? "LOG_LOCAL0" :
		 PSID_config->logDest==LOG_LOCAL1 ? "LOG_LOCAL1" :
		 PSID_config->logDest==LOG_LOCAL2 ? "LOG_LOCAL2" :
		 PSID_config->logDest==LOG_LOCAL3 ? "LOG_LOCAL3" :
		 PSID_config->logDest==LOG_LOCAL4 ? "LOG_LOCAL4" :
		 PSID_config->logDest==LOG_LOCAL5 ? "LOG_LOCAL5" :
		 PSID_config->logDest==LOG_LOCAL6 ? "LOG_LOCAL6" :
		 PSID_config->logDest==LOG_LOCAL7 ? "LOG_LOCAL7" :
		 "UNKNOWN");
	closelog();

	openlog("psid", LOG_PID|LOG_CONS, PSID_config->logDest);
	printWelcome();
    }

    /* call startupScript, if any */
    if (PSID_config->startupScript && *PSID_config->startupScript) {
	int ret = PSID_execScript(PSID_config->startupScript, NULL, NULL, NULL);

	if (ret > 1) {
	    PSID_log(-1, "startup script '%s' failed. Exiting...\n",
		     PSID_config->startupScript);
	    PSID_finalizeLogs();
	    exit(1);
	}
    }

    /* Setup handling of signals */
    initSigHandlers();

    if (PSID_config->coreDir) {
	if (chdir(PSID_config->coreDir) < 0) {
	    PSID_warn(-1, errno, "Unable to chdir() to coreDirectory '%s'",
		      PSID_config->coreDir);
	}
    }

    PSIDnodes_setProtoV(PSC_getMyID(), PSProtocolVersion);
    PSIDnodes_setDmnProtoV(PSC_getMyID(), PSDaemonProtocolVersion);
    PSIDnodes_setHWStatus(PSC_getMyID(), 0);
    PSIDnodes_setKillDelay(PSC_getMyID(), PSID_config->killDelay);
    PSIDnodes_setAcctPollI(PSC_getMyID(), PSID_config->acctPollInterval);

    /* Bring node up with correct numbers of CPUs */
    declareNodeAlive(PSC_getMyID(), PSID_getPhysCPUs(), PSID_getVirtCPUs());

    /* Initialize timeouts, etc. */
    PSID_initStarttime();

    /* initialize various modules */
    PSIDcomm_init();  /* This has to be first since it gives msgHandler hash */

    PSIDclient_init();
    initState();
    initOptions();
    initStatus();
    initSignal();
    PSIDspawn_init();
    initPartition();
    initHW();
    initAccount();
    initInfo();
    initEnvironment();
    /* Plugins shall be last since they use most of the ones before */
    initPlugins();

    /* Now we start all the hardware -- this might include the accounter */
    PSID_log(PSID_LOG_HW, "%s: starting up the hardware\n", __func__);
    PSID_startAllHW();

    /*
     * Prepare hostlist to initialize RDP and MCast
     */
    {
	in_addr_t *hostlist;
	int i;

	hostlist = malloc(PSC_getNrOfNodes() * sizeof(unsigned int));
	if (!hostlist) {
	    PSID_exit(errno, "Failed to get memory for hostlist");
	}

	for (i=0; i<PSC_getNrOfNodes(); i++) {
	    hostlist[i] = PSIDnodes_getAddr(i);
	}

	if (PSID_config->useMCast) {
	    /* Initialize MCast */
	    int MCastSock = initMCast(PSC_getNrOfNodes(),
				      PSID_config->MCastGroup,
				      PSID_config->MCastPort,
				      logfile, hostlist,
				      PSC_getMyID(), MCastCallBack);
	    if (MCastSock<0) {
		PSID_exit(errno, "Error while trying initMCast");
	    }
	    setDeadLimitMCast(PSID_config->deadInterval);

	    PSID_log(-1, "MCast and ");
	} else {
	    setStatusTimeout(PSID_config->statusTimeout);
	    setMaxStatBCast(PSID_config->statusBroadcasts);
	    setDeadLimit(PSID_config->deadLimit);
	    setTmOutRDP(PSID_config->RDPTimeout);
	}

	/* Initialize RDP */
	RDPSocket = RDP_init(PSC_getNrOfNodes(),
			     PSIDnodes_getAddr(PSC_getMyID()),
			     PSID_config->RDPPort, logfile, hostlist,
			     PSIDRDP_handleMsg, RDPCallBack);
	if (RDPSocket<0) {
	    PSID_exit(errno, "Error while trying initRDP");
	}

	PSID_log(-1, "RDP (%d) initialized.\n", RDPSocket);

	free(hostlist);
    }

    /* Now start to listen for clients */
    PSID_enableMasterSock();

    /* Once RDP and the master socket are ready parents might be released */
    if (pipeFD[1] > -1) {
	if (write(pipeFD[1], &magic, sizeof(magic)) <= 0) {
	    /* We don't care */
	}
	close(pipeFD[1]);
    }

    PSID_log(-1, "SelectTime=%d sec    DeadInterval=%d\n",
	     PSID_config->selectTime, PSID_config->deadInterval);

    /* Trigger status stuff, if necessary */
    if (PSID_config->useMCast) {
	declareMaster(PSC_getMyID());
    } else {
	int id = 0;
	while (id < PSC_getMyID()
	       && (send_DAEMONCONNECT(id) < 0 && errno == EHOSTUNREACH)) {
	    id++;
	}
	if (id == PSC_getMyID()) declareMaster(id);
    }

    /*
     * Main loop
     */
    while (1) {
	int res = Swait(PSID_config->selectTime * 1000);

	if (res < 0) PSID_warn(-1, errno, "Error while Swait()");

	/* Handle actions registered to main-loop */
	PSID_handleLoopActions();
    }
}
예제 #17
0
파일: servod.cpp 프로젝트: Sumeet002/dashee
/**
 * Our main function is designed to take in arguments from the command line
 * and run a UDP server. The UDP server provides a interface to the outside 
 * world which can communicate and send commands to our Servo controller.
 *
 * @param argc The number of arguments
 * @param argv The arguments array
 *
 * @returns 0 on successfull shutdown and any other number for error.
 * @retval 0 Successfull process
 * @retval -5 Failed on Vehicle init
 * @retval -4 Failed on Configuration
 * @retval -3 Failed because an Exception occrred
 * @retval -2 Failed because runtime::error exception occurred
 * @retval -1 Failed because exception occured when fallback activated
 */
int main(int argc, char ** argv)
{    

    // Program exit code
    int volatile RETVAL = 0;
        
    // Create the pointers which will be initiated later
    // Initialising to NULL is important otherwise you will seg fault
    Container * container;

    try
    {
        // Create handlers to our threads
        dashee::Threads::Thread threadServer 
            = dashee::Threads::Thread(threadReadFromServer);
        dashee::Threads::Thread threadSensor 
            = dashee::Threads::Thread(threadUpdateSensors);
        dashee::Threads::Thread threadController
            = dashee::Threads::Thread(threadStepController);

        // Add to our signalThread vector, so signal can be called on these 
        // threads, incase a signal is sent to the main program
        signalThreads.push_back(&threadServer);
        signalThreads.push_back(&threadSensor);
        signalThreads.push_back(&threadController);


// Open to syslog if it is set as a daemon
#ifdef DAEMON
        dashee::Log::openSyslog(argv[0], LOG_DAEMON);
#endif
        
        container = new Container(argc, argv);
        
        // Initilize the container
        threadInitilizeContainer(container);
 
        // Load sighandler and set the config
        initSignal();

// Start this program as a daemon so it
// can be run in background
#ifdef DAEMON
	dashee::startDaemon(
                container->getConfig(), 
                DASHEE_LOGFILE, 
                DASHEE_WORKINGDIR, 
                DASHEE_PIDFILE
            );
#endif

        // Helpfull message to let the user know the service is configured
        // and will now try starting
        dashee::Log::info(
                1, 
                "Started '%s' on port %d as %d.", 
                argv[0], 
                container->getConfig()->getUInt(
                    "port", 
                    Container::SERVER_PORT
                ),
                getpid()
            );
        
        // Start our threads
        threadServer.start(static_cast<void *>(container->getServer()));
        threadSensor.start((void *)NULL);
        threadController.start(static_cast<void *>(container));

        // Wait for threads to gracefully stop
        threadServer.join();
        threadSensor.join();
        threadController.join();
    
        // Cleanup our refrences
        dashee::Log::info(2, "Performing cleanups.");
        delete container;

    }
    catch (dashee::ExceptionConfig e)
    {
        dashee::Log::error("caught(ExceptionConfig): %s", e.what());
        RETVAL = -3;
    }
    catch (dashee::Exception e)
    {
        dashee::Log::error("caught(Exception): %s.", e.what());
        RETVAL = -2;
    }
    catch (std::runtime_error e)
    {
        dashee::Log::error("caught(runtime_error): %s.", e.what());
        RETVAL = -1;
    }
    
    dashee::Log::info(1, "Exiting with '%d'.", RETVAL);

// Close the daemon_stream if the program
// was compiled as a daemon
#ifdef DAEMON
    dashee::Log::close();
#endif

    return RETVAL;
}
int initCondition(condition_t *p_cond)
{
	return initSignal(&(p_cond->signal));
}
예제 #19
0
Call::Call(int callId, QString myName)
{
#ifdef REN_DEBUG
	qWarning(QString("Call::Call(int %1, QString %2)").arg(callId).arg(myName));
#endif
	id = callId;
	sd = -1;

	dec_state = NULL;
	dec_state = speex_decoder_init(&speex_uwb_mode);
	// renyang - Initializes and allocates resources for a SpeexBits struct
	speex_bits_init(&bits);

	int enh = 1;
	speex_decoder_ctl(dec_state, SPEEX_SET_ENH, &enh);
	speex_decoder_ctl(dec_state, SPEEX_GET_FRAME_SIZE, &frame_size);

	if ((outBuffer = (float *) malloc(frame_size*4*sizeof(float)))==NULL)
		throw Error(Error::IHU_ERR_MEMORY);
	if ((soundBuffer = (float *) malloc(MAXBUFSIZE*sizeof(float)))==NULL)
		throw Error(Error::IHU_ERR_MEMORY);
	readyFrames = 0;

	rsa = new Rsa(RSA_STRENGTH);
	transmitter = new Transmitter(rsa);
	receiver = new Receiver(rsa);
	// renyang-modify 建立一個ip handler
	sctpiphandler = new SctpIPHandler();

	// renyang-modify - 當某一個ip沒有一段時間後, 沒有辦法收到data, 要處理
	connect(sctpiphandler,SIGNAL(SigAddressConfrim(QString)),this,SLOT(SlotAddressConfirm(QString)));
	// renyang-modify - 當多次沒有收到資料, 宣告這一個ip失聯
	connect(sctpiphandler,SIGNAL(SigAddressFail(QString)),this,SLOT(SlotAddressFail(QString)));
	// renyang-modify - 某一個ip有收到資料, 宣告這一個ip復活啦
	connect(sctpiphandler,SIGNAL(SigAddressAvailable(QString)),this,SLOT(SlotAddressAvailable(QString)));

	stopTimer = new QTimer(this);

	active = false;
	muteRec = false;
	mutePlay = false;
	callFree = true;
	aborted = false;
	recording = false;

	// renyang-modify - 初始化IPChanging, 表示最近沒有改變primary address
	IPChanging = false;
	// renyang-modify - 建立一個Timer來計數改完primary address後多久要改回IPChanging=false
	IPChangingTimer = new QTimer(this);
	connect(IPChangingTimer,SIGNAL(timeout()),this,SLOT(resetIPChanging()));

	// renyang-modify - 初始化傳送與接收image的index
	recvImage_index = sendImage_index = 0;

	transmitter->setMyName(myName);

	srand(time(NULL));

	connect( receiver, SIGNAL(newSocket(int,int,struct sockaddr_in)), this, SLOT(newConnection(int,int,struct sockaddr_in)) );
	connect( receiver, SIGNAL(keyRequest()), this, SLOT(sendKeyRequest()) );
	connect( receiver, SIGNAL(sendNewKey()), this, SLOT(sendKey()) );
	connect( receiver, SIGNAL(newKey(QString)), this, SLOT(receivedNewKey(QString)) );
	// renyang - 沒有再接收到client端傳送過來的訊息, 結束此Call
	connect( receiver, SIGNAL(finishSignal()), this, SLOT(stopCall()) );
	connect( receiver, SIGNAL(error(QString)), this, SLOT(abortCall(QString)) );
	connect( receiver, SIGNAL(warning(QString)), this, SLOT(warning(QString)) );
	connect( receiver, SIGNAL(message(QString)), this, SLOT(warning(QString)) );
	// renyang - 對方接受通話, 或是本地端接受通話
	connect( receiver, SIGNAL(connectedSignal()), this, SLOT(connected()) );
	connect( receiver, SIGNAL(ringSignal()), this, SLOT(playRing()) );
	connect( receiver, SIGNAL(initSignal()), this, SLOT(playInit()) );
	connect( receiver, SIGNAL(newAudioData(char*, int)), this, SLOT(decodeAudioData(char*, int)) );
	connect( receiver, SIGNAL(ringReplySignal()), transmitter, SLOT(sendRingReplyPacket()) );

	// renyang-modify - 接收由receiver傳送上來的peer address
	connect (receiver,SIGNAL(SignalgetIps(QStringList)),this,SLOT(SlotgetIps(QStringList)));
	// renyang-modify - 當Receiver接收到與之前的primary不同時, 要求改變primary address
	connect (receiver,SIGNAL(setPrimaddrSignal(QString)),this,SLOT(setPrimaddr(QString)));
	// renyang-modify - 當Receiver接收到事件時, 會通知上層的Call, 以便修改CallTab的ip list情況
	connect (receiver,SIGNAL(SigAddressEvent(QString,QString)),this,SLOT(SlotAddressEvent(QString,QString)));
	// renyang-modify - 對方要求影像
	connect (receiver,SIGNAL(requestImage()),this,SLOT(SlotGetImage()));
	// renyang-modify - 由receiver接收到image資料, 並處理這一些資料
	connect (receiver,SIGNAL(newVideoData(char *,int)),this,SLOT(decodeVideoData(char *,int)));
	// renyang-modify - 當收到想要接收目前封包的下一部分時...
	connect (receiver,SIGNAL(requestNextImage()),this,SLOT(sendVideo()));
	// renyang-modify - 接收到完整的image,準備把它放到video_label
	connect (receiver,SIGNAL(completeImage()),this,SLOT(processImage()));
	// renyang-modify - 跟對方要求影像失敗
	connect (receiver,SIGNAL(requestImageFail()),this,SLOT(SlotrequestImageFail()));
	// renyang-modify - end

	connect( transmitter, SIGNAL(ringMessage()), this, SLOT(ringMessage()) );
	connect( transmitter, SIGNAL(finishSignal()), this, SLOT(stopCall()) );
	connect( transmitter, SIGNAL(error(QString)), this, SLOT(abortCall(QString)) );
	connect( transmitter, SIGNAL(message(QString)), this, SLOT(message(QString)) );
	connect( transmitter, SIGNAL(startSignal()), this, SLOT(startRecorder()) );

	connect( stopTimer, SIGNAL(timeout()), this, SLOT(close()) );

	// renyang-modify - 初始化streamno
	streamno = 1;

}