Beispiel #1
0
static void
acceptManageAssociation(DUL_NETWORKKEY ** network,
			DUL_ASSOCIATIONKEY * association,
			DUL_ASSOCIATESERVICEPARAMETERS * service,
			CTNBOOLEAN forkFlag,
			CTNBOOLEAN threadFlag,
			CTNBOOLEAN abortFlag,
			CTNBOOLEAN verboseDUL,
			int releaseDelay,
			const char* logDir,
			const char* storageDir,
                        const char* dbName)
{
    int pid = 0;
    CONDITION cond = 0;
    THREAD_STRUCT *s;

    s = (THREAD_STRUCT*)malloc(sizeof(*s));
    memset(s, 0, sizeof(*s));
    s->network = network;
    s->association = association;
    s->service = service;
    s->abortFlag = abortFlag;
    s->releaseDelay = releaseDelay;
    strcpy(s->logDir, logDir);
    strcpy(s->storageDir, storageDir);
    strcpy(s->dbName, dbName);

    if (threadFlag) {
#ifdef CTN_USE_THREADS
#ifdef _MSC_VER
	fprintf(stderr, "Not designed for threads and Windows (yet)\n");
	exit(1);
#else
	pthread_t threadID;
	s->runMode = MODE_THREAD;
	pthread_create(&threadID, NULL, runThread, s);
	harvestThreads();
#endif
#else
	fprintf(stderr, "Code not compiled for thread use\n");
	exit(1);
#endif
	return;
    } else if (forkFlag) {
	harvestChildren();
	s->runMode = MODE_FORK;
	pid = fork();
	if (pid == 0) {
	    runThread(s);
	} else {
	    (void) DUL_DropAssociation(&association);
	    return;
	}
    } else {
	s->runMode = MODE_SINGLE;
	runThread(s);
    }

}
void MainWindow::on_openButton_clicked()
{
    changeTestinfo();
    test->testFunc = T_OPEN;
    test->openMode = O_WRITE;
    createThread();
    runThread();

    test->openMode = O_READ;
    createThread();
    runThread();
}
Beispiel #3
0
void VTcpServer::run()
{
  while (runThread().active())
  {
    VTcpSession* newTCPSession = accept();
    if (newTCPSession == NULL)
    {
      SET_DEBUG_ERROR(VNetError, "error in accept", WSAGetLastError());
      break;
    }
    if (!newTCPSession->open())
    {
      error = newTCPSession->error;
      continue;
    }
    VTcpSessionThread* thread = new VTcpSessionThread(this, newTCPSession);
    //thread->moveToThread(runThread().m_qthread); // gilgil temp 2012.08.16
    thread->name = className();
    threadList.lock();
    threadList.append(thread);
    threadList.unlock();
    if (!thread->open())
    {
      error = thread->error;
      break;
    }
  }
}
Beispiel #4
0
// HotKeyIt ahktextdll
EXPORT UINT_PTR ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args)
{
	if (setscriptstrings(fileName && !IsBadReadPtr(fileName,1) && *fileName ? fileName : aDefaultDllScript, argv && !IsBadReadPtr(argv,1) && *argv ? argv : _T(""), args && !IsBadReadPtr(args,1) && *args ? args : _T("")))
		return 0;
	nameHinstanceP.istext = 1;
	return runThread();
}
void wsThreadPool::startUp() {
    _mInitialized = true;
    numThreads = maxThreads = WS_NUM_CORES - 1; //  Save one processor for the main thread
    if (numThreads <= 0) {
        wsEcho(WS_LOG_THREADS, "No extra threads have been created.");
    }
    threads = wsNewArray(pthread_t, numThreads);
    threadIndices = wsNewArray(u32, numThreads);
    for (u32 i = 0; i < numThreads; ++i) {
        threadIndices[i] = i;
    }
    #ifdef WS_OS_FAMILY_UNIX
        threadAttributes = wsNew(pthread_attr_t, pthread_attr_t());
        pthread_attr_init(threadAttributes);
        pthread_attr_setdetachstate(threadAttributes, PTHREAD_CREATE_JOINABLE);
    #elif defined(WS_OS_FAMILY_WINDOWS)
    #endif  /*  Whipstitch OS families  */
    listMutex = wsNew(wsMutex, wsMutex());
    logMutex = wsNew(wsMutex, wsMutex());
    wsInitMutex(listMutex);
    wsInitMutex(logMutex);
    taskList = wsNew(wsQueue<wsTask*>, wsQueue<wsTask*>(WS_MAX_TASK_QUEUE_SIZE));
    tasksRunning = 0;
    wsEcho(WS_LOG_THREADS, "Initializing %u Worker Threads", numThreads);
    for (u32 i = 0; i < numThreads; ++i) {
        runThread(i);
    }
}
/**
   This will run the code of the ArASyncTask without creating a new
   thread to run it in. It performs the needed setup then calls runThread().
   This is good if you have a task which you wish to run multiple
   instances of and you want to use the main() thread  instead of having
   it block, waiting for exit of the program.
   @param arg the argument to pass to the runThread()
*/
AREXPORT void * ArASyncTask::runInThisThread(void *arg)
{
  myJoinable=true;
  myRunning=true;
#ifdef WIN32
  myThread=GetCurrentThreadId();
#else
  myThread=pthread_self();
#endif
  
  if (myName.size() == 0)
    ArLog::log(ourLogLevel, "Running anonymous thread with ID %d", 
	       myThread);
  else
    ArLog::log(ourLogLevel, "Running %s thread with ID %d", myName.c_str(),
	       myThread);
  
  ourThreadsMutex.lock();
  // MPL BUGFIX, this wasn't workign for some reason (was printing
  // 0)...  so I got rid of it and did it the easier way anyhow
  //printf("!!!! %d\n", ourThreads.insert(MapType::value_type(myThread, this)).second);
  ourThreads[myThread] = this;
  ourThreadsMutex.unlock();

  return(runThread(arg));
}
void MainWindow::on_writeButton_clicked()
{
    changeTestinfo();
    test->testFunc = T_WRITE;
    createThread();
    runThread();
}
Beispiel #8
0
// HotKeyIt ahktextdll
EXPORT unsigned int ahktextdll(LPTSTR fileName, LPTSTR argv, LPTSTR args)
{
	if (setscriptstrings(*fileName ? fileName : _T("#Persistent"), argv, args))
		return 0;
	nameHinstanceP.istext = 1;
	return runThread();
}
Beispiel #9
0
int Kmeans::run(int maxIterations) {
    int iterations = 0;
    #ifdef USE_THREADS
    {
        ThreadInfo *info = new ThreadInfo[numThreads];
        for (int t = 0; t < numThreads; ++t) {
            info[t].km = this;
            info[t].threadId = t;
            info[t].maxIterations = maxIterations;
            pthread_create(&info[t].pthread_id, NULL, Kmeans::runner, &info[t]);
        }
        // wait for everything to finish...
        for (int t = 0; t < numThreads; ++t) {
            pthread_join(info[t].pthread_id, NULL);
        }
        iterations = info[0].numIterations;
        delete [] info;
    }
    #else
    {
        iterations = runThread(0, maxIterations);
    }
    #endif

    return iterations;
}
Beispiel #10
0
void App::terminate()
{
  if (netClient != NULL) netClient->close();
  runThread().close();
  SAFE_DELETE(param);
  SAFE_DELETE(netClient);
}
void MainWindow::on_CreatButton_clicked()
{
    changeTestinfo();
    test->testFunc = T_CRTEATE;
    createThread();
    runThread();
}
void CurlDownloadManager::startThreadIfNeeded()
{
    if (!runThread()) {
        if (m_threadId)
            waitForThreadCompletion(m_threadId);
        setRunThread(true);
        m_threadId = createThread(downloadThread, this, "downloadThread");
    }
}
void MainWindow::startPatching()
{
    Q_D(MainWindow);

    d->bytes = 0;
    d->maxBytes = 0;
    d->files = 0;
    d->maxFiles = 0;

    d->progressBar->setMaximum(0);
    d->progressBar->setValue(0);
    d->detailsLbl->clear();

    if (!d->supported) {
        if (d->presetSel->currentIndex() == 0) {
            d->patchInfo = new mbp::PatchInfo(); // TODO: Memory leak here!

            d->patchInfo->addAutoPatcher("StandardPatcher",
                                         mbp::PatchInfo::AutoPatcherArgs());
            d->patchInfo->setHasBootImage(d->hasBootImageCb->isChecked());
            if (d->patchInfo->hasBootImage()) {
                d->patchInfo->setRamdisk(d->device->id() + "/default");
                QString text = d->bootImageLe->text().trimmed();
                if (!text.isEmpty()) {
                    QStringList split = text.split(QStringLiteral(","));
                    std::vector<std::string> bootImages;
                    for (const QString &bootImage : split) {
                        bootImages.push_back(bootImage.toUtf8().constData());
                    }
                    d->patchInfo->setBootImages(std::move(bootImages));
                }
            }

            d->patchInfo->setDeviceCheck(!d->deviceCheckCb->isChecked());
        } else {
            d->patchInfo = d->patchInfos[d->presetSel->currentIndex() - 1];
        }
    }

    d->state = MainWindowPrivate::Patching;
    updateWidgetsVisibility();

    FileInfoPtr fileInfo = new mbp::FileInfo();
    fileInfo->setFilename(d->fileName.toUtf8().constData());
    fileInfo->setDevice(d->device);
    fileInfo->setPatchInfo(d->patchInfo);
    QString romId;
    if (d->instLocSel->currentIndex() >= d->instLocs.size()) {
        romId = QStringLiteral("data-slot-%1").arg(d->instLocLe->text());
    } else {
        romId = d->instLocs[d->instLocSel->currentIndex()].id;
    }
    fileInfo->setRomId(romId.toUtf8().constData());

    emit runThread(d->patcher, fileInfo);
}
Beispiel #14
0
TimeSync::TimeSync() : QObject()
{
    started=0;
    startTime=QDateTime::currentDateTime().toTime_t();
    timeShift=0;
    additionalTimer=0;
    getNTPTimeRetryCount=0;

    dateUpdateThread=new QThread;
    connect(dateUpdateThread,SIGNAL(started()),this,SLOT(runThread()));
    connect(this,SIGNAL(finishThread()),dateUpdateThread,SLOT(quit()));
    connect(this,SIGNAL(startSync()),this,SLOT(getNTPTime()));
    this->moveToThread(dateUpdateThread);
    dateUpdateThread->start();
}
Beispiel #15
0
// ============================================================================================
bool	TestLauncher::goToTrial(int trialIndex)
{
	if ((trialIndex >= 0)&&(trialIndex < tests.size()))
	{
		currentIndex = trialIndex;
		/* update audio data */
		releaseAudioData();
		runThread();
		return true;
	}
	else
	{
		return false;
	}
}
void MainWindow::on_upLocalFile_clicked()
{
    QList<QString> fileList = QFileDialog::getOpenFileNames(
                this,
                QDir::currentPath());

    if (!fileList.isEmpty()) {
        changeTestinfo();
        ui->selectFileCount->setText(QString::number(fileList.length()));
        test->filePath = fileList;
        test->count = ui->uploadCount->text().toInt();
        test->testFunc = T_UPLOAD;
        createThread();
        runThread();
    }
}
Beispiel #17
0
// ============================================================================================
bool	TestLauncher::goForward()
{
	if (currentIndex < tests.size() - 1)
	{
		currentIndex++;
		/* update audio data */

		dbgOut( L"\t Starting test " + String(currentIndex) + L"\t" + tests[currentIndex]->testName );

		releaseAudioData();
		runThread();
		return true;
	}
	else
	{
		return false;
	}
}
Beispiel #18
0
void App::inputAndSend()
{
  LOG_DEBUG("beg");

  char* buf = new char[param->bufSize];
  while (runThread().active())
  {
    char* p = gets_s(buf, param->bufSize);
    if (p == NULL) break;
    int readLen = (int)strlen(p);
    if (readLen == 0) continue;
    buf[readLen] = '\0';
    int writeLen = netClient->write(buf, readLen);
    if (writeLen == VERR_FAIL) break;
  }
  delete[] buf;

  LOG_DEBUG("end");
}
Beispiel #19
0
bool voicesport::SpeechKit::startASR()
{
	is_stop = false;
	if (sock){
		int result = send(sock, "start", 5, 0);
		return true;
	}
	else
		connectServer();
	
	int result = send(sock, "start", 5, 0);
	if (result == SOCKET_ERROR) {
		return false;
	}
	else {
		std::thread runThread(&voicesport::SpeechKit::recevingData, this);
		runThread.detach();
		return true;
	}

}
Beispiel #20
0
void MCF::dlFilesFromHttp(const char* url, const char* installDir)
{
	gcTrace("Url: {0}, Dir: {1}", url, installDir);

	gcAssert(!m_pTHandle);

	if (m_bStopped)
		return;

	if (!url)
		throw gcException(ERR_BADURL);

	//save the header first incase we fail
	saveMCF_Header();

	MCFCore::Thread::HGTController *temp = new MCFCore::Thread::HGTController(url, this, installDir);
	temp->onProgressEvent +=delegate(&onProgressEvent);
	temp->onErrorEvent += delegate(&onErrorEvent);

	runThread(temp);
	saveMCF_Header();
}
Beispiel #21
0
// ============================================================================================
bool TestLauncher::init(String stimuliDir)
{	
	stimuliDirectory = stimuliDir;
	
	bool res = readTrialSettings();
	
	if (!res)
	{
		return false;
	}

	debugTrialSettings();

	/* read audio stimuli */
	runThread();

	if (lastError.isEmpty())
	{	
		mushraAudioPlayer = new MushraAudioPlayer(this);
	}
	
	return res;
}
/*! Executes the thread.
 *  \deprecated Obsolete coding style.
 */
void Thread::RunThread()
{
  runThread();
}
Beispiel #23
0
void Script::executeThreads(uint msec) {
	ScriptThreadList::iterator threadIterator;

	if (_vm->_interface->_statusTextInput)
		return;

	threadIterator = _threadList.begin();

	while (threadIterator != _threadList.end()) {
		ScriptThread &thread = *threadIterator;

		if (thread._flags & (kTFlagFinished | kTFlagAborted)) {
			if (thread._flags & kTFlagFinished)
				setPointerVerb();

			if (_vm->getGameId() == GID_IHNM) {
				thread._flags &= ~kTFlagFinished;
				thread._flags |= kTFlagAborted;
				++threadIterator;
			} else {
				threadIterator = _threadList.erase(threadIterator);
			}
			continue;
		}

		if (thread._flags & kTFlagWaiting) {

			switch (thread._waitType) {
			case kWaitTypeDelay:
				if (thread._sleepTime < msec)
					thread._sleepTime = 0;
				else
					thread._sleepTime -= msec;

				if (thread._sleepTime == 0)
					thread._flags &= ~kTFlagWaiting;
				break;

			case kWaitTypeWalk:
				{
					ActorData *actor = (ActorData *)thread._threadObj;
					if (actor->_currentAction == kActionWait)
						thread._flags &= ~kTFlagWaiting;
				}
				break;

			case kWaitTypeWaitFrames: // IHNM
				if (thread._frameWait < _vm->_frameCount)
					thread._flags &= ~kTFlagWaiting;
				break;
			}
		}

		if (!(thread._flags & kTFlagWaiting)) {
			if (runThread(thread))
				break;
		}

		++threadIterator;
	}

}
void CtrlrPanelMIDISnapshot::handleAsyncUpdate()
{
    gatherSnapshotData();
    runThread();
}
  return TypedThreadHandle<FuncPtrThreadZero> (new FuncPtrThreadZero(func));
}

FuncPtrThreadZero::Handle runNamedThread(const std::string &name, void (* func)())
{
	return TypedThreadHandle<FuncPtrThreadZero> (new FuncPtrThreadZero(name, func));
}

#if 0
// Testing stuff

class testclass
{
public:
	void zeroArg() {}
	void oneArg(testclass *) {}
	void twoArg(testclass *, int) {}
};

testclass m;

typedef MemberFunctionThreadZero<testclass>::Handle AsyncTestMemberFunctionZero;
AsyncTestMemberFunctionZero temp = runThread(m, testclass::zeroArg);

typedef MemberFunctionThreadOne<testclass, testclass *>::Handle AsyncTestMemberFunctionOne;
AsyncTestMemberFunctionOne temp2 = runThread(m, testclass::oneArg, &m);

typedef MemberFunctionThreadTwo<testclass, testclass *, int>::Handle AsyncTestMemberFunctionTwo;
AsyncTestMemberFunctionTwo temp3 = runThread(m, testclass::twoArg, &m, 4);
#endif
Beispiel #26
0
void serverOperationsForm::onInit(wxInitDialogEvent& event)
{
    wxLogDebug( _T("[serverOpForm] on init fired") );
    runThread();
    event.Skip();
}
Beispiel #27
0
void server(char* port, int kflag){
	int sockfd, new_fd, numbytes;  // listen on sock_fd, new connection on new_fd
	struct addrinfo hints, *servinfo, *p;
	struct sockaddr_storage their_addr; // connector's address information
	socklen_t sin_size;
	struct sigaction sa;
	int yes=1;
	char s[INET6_ADDRSTRLEN];
	int rv;
	char buf[MAXDATASIZE];

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE; // use my IP

	//This checks if something went wrong. addrinfo returns 0 when it suceeds
	if ((rv = getaddrinfo(NULL, port, &hints, &servinfo)) != 0) {
	fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
	exit(1);
	}

	// loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("server: socket");
			continue;
		}

		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
				sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("server: bind");
			continue;
		}

		break;
	}

	freeaddrinfo(servinfo); // all done with this structure

	if (p == NULL)  {
		fprintf(stderr, "server: failed to bind\n");
		exit(1);
	}

	if (listen(sockfd, BACKLOG) == -1) {
		perror("listen");
		exit(1);
	}

	if(vflag){fprintf(stderr, "Waiting for a connection...\n");}


	/* For multiple connections */
	if(rflag)
	{		
		char *message;
		struct Clients *conns = malloc(sizeof(struct Clients));
		conns->clients = malloc(10 * sizeof(int));
		conns->length = 0;

		//Create the sending thread that reads from STDIN
		struct Thread *sender_thread = createThread(send_to_all, conns);

		//Run it 
		int sender_t = runThread(sender_thread, NULL);

		//Initialize a mutex lock
		pthread_mutex_init(&mutexDelete, NULL);


		do
		{
			
			new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
			if(new_fd == -1)
			{
				perror("accept");
				continue;
			}

			inet_ntop(their_addr.ss_family,
	 			get_in_addr((struct sockaddr *)&their_addr),
	 			s, sizeof s);

			/* Get por of incoming connection*/
			struct sockaddr_in *sin = (struct sockaddr_in*)&their_addr;
			short w = ntohs(sin->sin_port);

			/*For debugging print when we get a connection*/
			if(vflag){fprintf(stderr, "Server: got connection from %s\nAnd the port is %u\n", s, w);}

			/* Add connection to our struct of clients and prepare thread*/
			/* Mutex lock is used as conns is a shared resource*/
			pthread_mutex_lock(&mutexDelete);
				addFD(conns,new_fd);
			pthread_mutex_unlock(&mutexDelete);

			struct Thread *sniffer_thread = createThread(read_and_send_to_all, conns);

			int threazy = runThread(sniffer_thread, NULL);

			detachThread(sniffer_thread);

		} while (1);

		/*Clean up the listener socket and mutex*/
		pthread_mutex_destroy(&mutexDelete);
		close(sockfd);
		exit(0);
	}



	/* Now wait for connections , this is for regular -l*/
	do 
	{
	 	sin_size = sizeof their_addr;
	 	new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
	 	if (new_fd == -1) {
	 		perror("accept");
	 		continue;
	 	}

	 	inet_ntop(their_addr.ss_family,
	 		get_in_addr((struct sockaddr *)&their_addr),
	 		s, sizeof s);
 		
 		/* Get por of incoming connection*/
		struct sockaddr_in *sin = (struct sockaddr_in*)&their_addr;
		short w = ntohs(sin->sin_port);


	 	/*For debugging print when we get a connection*/
		if(vflag){fprintf(stderr, "Server: got connection from %s\nAnd the port is %u\n", s, w);}

		/*Let's start a thread that we will
		use for receiving messages*/
	 	struct Thread *receive_thread = createThread(receiving_thread, &new_fd);

		/* And now we send it off !*/
	 	int rthreazy = runThread(receive_thread, NULL);

		/* Now we start a thread for reading fron STDIN and run it*/
		struct Thread *send_thread = createThread(sending_thread, &new_fd);
	 	int sthreazy = runThread(send_thread, NULL);

		/* Join threads */
	 	joinThread(receive_thread, NULL);

		close(new_fd);


	} while(kflag); //if kflag is on we keep on listening after a connection closes

	/*Clean the listener socket if you are leaving*/
	close(sockfd);
}
int main() {
	float I0, I0_goal,
		I1,
		f;
	// prepare for running multiple trials simultaneously
	/*
	MorrisLecar:
		Subthreshold:
			state[0] = -21.35
			state[1] = 0.2
		Suprathreshold:
			state[0] = 4.65
			state[1] = 0.43
	HodgkinHuxley:
		Subthreshold:
			state[0] = -67.2
			state[1] = 0.31
			state[2] = 0.26
			state[3] = 0.01
		Suprathreshold:
			state[0] = 1.0
			state[1] = 0.31
			state[2] = 0.052
			state[3] = 0.596
	*/
	TrialParameters trialData[THREAD_COUNT];
	for (int th=0; th < THREAD_COUNT; th++ ) {
		#ifdef HH
		trialData[th].neuron.state[0] = -67.3;
		trialData[th].neuron.state[1] = 0.42;
		trialData[th].neuron.state[2] = 0.24;
		trialData[th].neuron.state[3] = 0.06;
		#else
		trialData[th].neuron.state[0] = -21.35;
		trialData[th].neuron.state[1] = 0.2;
		#endif
		trialData[th].seed = -585 + th;
	}
	
	// open our output file
	// reliability_hh_bak_I03.6_supra_trials500_sigma0.3_t50-100-50.log	
	logfile = fopen("data/reliability-hh-sub.log", "w");
	if (logfile == NULL) {
		printf("Cannot open the file.\n");
		exit(1);
	}
	
	// to plot voltage vs time
  	// /*
	vlogfile = fopen("data/voltage.log", "w");
	if (vlogfile == NULL) {
		printf("Cannot open the file.\n");
		exit(1);
	}
	// */

	// print column headings
	fprintf(logfile, "I1\tfreq\treliability\n");
 	fprintf(vlogfile, "t\tI\tV\tn\tm\th\n");

#ifdef WIN32	
	HANDLE threads[THREAD_COUNT];
#endif
	
	#ifdef HH
	I0 = 2.6; // below bistable region
	// I0 = 4.3; // above bistable region
	I0_goal = 2.6; // in bistable region
	#else
	I0 = 24.5; // below bistable region
	//I0 = 26.5; // above bistable region
	I0_goal = 25.4; // in bistable region
	#endif
	// iterate over I1 from zero to one
	for(I1 = 0.0; I1 <= 0.0; I1 += I1_step) {
		// iterate over frequency
		for(f = 0.0; f <= 0.0; ) {
			for (int th=0; th < THREAD_COUNT; th++, f += f_step) {
				trialData[th].I0 = I0;
				trialData[th].I0_goal = I0_goal;
				trialData[th].I1 = I1;
				trialData[th].f = f;
				#ifdef WIN32
				threads[th] = CreateThread(NULL, 0, runThread, &(trialData[th]), 0, NULL);
				#else
				runThread(&(trialData[th]));
				#endif
			}
			#ifdef WIN32
			WaitForMultipleObjects(THREAD_COUNT, threads, TRUE, INFINITE);
			for (int th=0; th < THREAD_COUNT; th++) {
				CloseHandle(threads[th]);
			}
			#endif
		}
	}
	
	// close the files
	fclose(logfile);
 	fclose(vlogfile);
	
	return 0;
}
///----------------------------------------------------------------------------------
void WingsailControlNode::start()
{
    runThread(WingsailControlNodeThreadFunc);
}
Beispiel #30
0
void client(char *host, char* port){
	int sockfd, numbytes;
	char buff[MAXDATASIZE];
	struct addrinfo hints, *servinfo, *p;
	int rv;
	char s[INET6_ADDRSTRLEN];
	//This struct will be used to bind socket to port
	struct sockaddr_in popt;

	popt.sin_family = INADDR_ANY;
	popt.sin_port = htons(sourcePort);

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;

	if ((rv = getaddrinfo(host, port, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		exit(1);
	}

	// loop through all the results and connect to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("client: socket");
			continue;
		}
		if(pflag)
		{
			//Binds client to specific port
			 if (bind(sockfd, (struct sockaddr*)&popt, sizeof popt) == -1) {
			 	close(sockfd);
			 	perror("server: bind");
			 	continue;
		 	}
		}


		if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("client: connect");
			continue;
		}

		break;
	}

	if (p == NULL) {
		if(vflag){fprintf(stderr, "client: failed to connect\n");}
		exit(2);
	}

	inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
			s, sizeof s);
	/*If in debug mode print where we are connecting*/
	if(vflag){printf("client: connecting to %s\n", s);}

	freeaddrinfo(servinfo); // all done with this structure


	//Thread for sending messages
	struct Thread *send_thread = createThread(sending_thread, &sockfd);
	//Off it goes
	int threazy = runThread(send_thread, NULL);

	//Thread for reading messages
	struct Thread *receive_thread = createThread(receiving_thread, &sockfd);

	//off it goes
	int rthreazy = runThread(receive_thread, NULL);

	if(threazy == -10) {fprintf(stderr, "There was an error with the sending thread\n");}

	joinThread(send_thread, NULL);

}