コード例 #1
0
ファイル: Sim03.c プロジェクト: kexu935/CS446_SIM03
//
// Main Function Implementation ///////////////////////////////////
//
   int main( int argc, char* argv[] )
      {
       struct pcb_table myPCB = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };   // pcb table
       struct pcb_table *pcbPtr = NULL;   //pcb pointer
       bool isThread = false;   // check if the meta a thread
       bool toFile = false;   // check if the log needs to output to file
       int currentProcess = 0;   // current running process
       pthread_t myThread;   // thread

       currentLog = logList;

       // read config file
       readConfig( argv[1], &myPCB );

       // check if need to print to monitor or file
       if(myPCB.logMode == 1 || myPCB.logMode == 2 )
          toMonitor = true;
       if(myPCB.logMode == 1 || myPCB.logMode == 3 )
          toFile = true;

       // read meta data file, update pointer
       readMeta( myPCB.dataFile, &pcbList, myPCB, &processCounter);
       pcbPtr = pcbList;

       // start timer
       clock_gettime( CLOCK_REALTIME, &startTime ); 

       // print start log
       clock_gettime( CLOCK_REALTIME, &endTime );
       totalTime = timeLap( startTime, endTime );
       recordLog( &logList, &currentLog, totalTime, "Simulator program starting" );
       if( toMonitor )
          printLog( currentLog );

       // print log
       clock_gettime( CLOCK_REALTIME, &endTime );
       totalTime = timeLap( startTime, endTime );
       recordLog( &logList, &currentLog, totalTime, "OS: preparing all processes" );
       if( toMonitor )
          printLog( currentLog );

       // loop around processes
       while( processCounter > 0 )
          {
          // if the process hasn't finished
          if( pcbPtr -> current != NULL )
             {
              // print log
              clock_gettime( CLOCK_REALTIME, &endTime );
              totalTime = timeLap( startTime, endTime );
              recordLog( &logList, &currentLog, totalTime, "OS: seleting next process" );
              if( toMonitor )
                 printLog( currentLog );

              // print log
              clock_gettime( CLOCK_REALTIME, &endTime );
              totalTime = timeLap( startTime, endTime );
              metaStartLog( pcbPtr -> current, pcbPtr, logComment );
              recordLog( &logList, &currentLog, totalTime, logComment );
              if( toMonitor )
                 printLog( currentLog );

              // if the current meta is process
              if( pcbPtr -> current -> component == 'P' )
                 {
                  runProcess( pcbPtr -> current, &pcbPtr );
                  if( pcbPtr -> currentLeft == 0 )
                     {
                      clock_gettime( CLOCK_REALTIME, &endTime );
                      totalTime = timeLap( startTime, endTime );
                      interruptLog(pcbPtr -> current, logComment);
                      recordLog( &logList, &currentLog, totalTime, logComment );
                      if( toMonitor )
                         printLog( currentLog );

                      pcbPtr -> current = pcbPtr -> current -> next;
                      if( pcbPtr -> current != NULL && pcbPtr -> current -> component == 'P' )
                         pcbPtr -> currentLeft = pcbPtr -> current -> cyc_time;
                      if(pcbPtr -> current == NULL)
                         processCounter --;
                     }
                 }

              // if the current meta needs spawn thread
              else
                 {
                  // spawn thread
                  pthread_create( &myThread, NULL, thread_perform, (void*) pcbPtr );

                  // print log
                  clock_gettime( CLOCK_REALTIME, &endTime );
                  totalTime = timeLap( startTime, endTime );
                  blockLog(pcbPtr->current, logComment);
                  recordLog( &logList, &currentLog, totalTime, logComment );
                  if( toMonitor )
                     printLog( currentLog );

                  // block process
                  blockProcess(&pcbList, pcbPtr, &blockQueue);
                 }
             }

          // select next process in queue
          if(pcbPtr -> next == NULL)
             pcbPtr = pcbList;
          else
             pcbPtr = pcbPtr -> next;
          }

       // print ending log
       clock_gettime( CLOCK_REALTIME, &endTime );
       totalTime = timeLap( startTime, endTime );
       recordLog( &logList, &currentLog, totalTime, "Simulator program ending" );
       if( toMonitor )
          printLog( currentLog );

       // output to file
       if( toFile )
          outputToFile( logList, myPCB );

       return 0;
      }   // end of main
コード例 #2
0
    d->diffusionTractographyToolBox->setTitle("Tractography");

    connect(d->diffusionTractographyToolBox, SIGNAL(addToolBox(medToolBox *)),
            this, SLOT(addToolBox(medToolBox *)));
    connect(d->diffusionTractographyToolBox, SIGNAL(removeToolBox(medToolBox *)),
            this, SLOT(removeToolBox(medToolBox *)));

    // -- View toolboxes --

    QList<QString> toolboxNames = medToolBoxFactory::instance()->toolBoxesFromCategory("view");
    foreach(QString toolbox, toolboxNames)
    {
       addToolBox( medToolBoxFactory::instance()->createToolBox(toolbox, parent) );
    }

    connect(d->diffusionEstimationToolBox, SIGNAL(processRequested(QString, QString)), this, SLOT(runProcess(QString, QString)));
    connect(d->diffusionScalarMapsToolBox, SIGNAL(processRequested(QString, QString)), this, SLOT(runProcess(QString, QString)));
    connect(d->diffusionTractographyToolBox, SIGNAL(processRequested(QString, QString)), this, SLOT(runProcess(QString, QString)));

    connect(d->diffusionEstimationToolBox, SIGNAL(processCancelled()), this, SLOT(cancelProcess()));
    connect(d->diffusionTractographyToolBox, SIGNAL(processCancelled()), this, SLOT(cancelProcess()));

    this->addToolBox( d->diffusionEstimationToolBox );
    this->addToolBox( d->diffusionScalarMapsToolBox );
    this->addToolBox( d->diffusionTractographyToolBox );

    d->processRunning = false;
}

medDiffusionWorkspace::~medDiffusionWorkspace()
{
コード例 #3
0
ファイル: sshd.c プロジェクト: DX-MON/init.d
int main(int argc, char **argv)
{
	if (argc < 2)
		return usage(argv[0]);

	if (CHECK_ARG(1, "start"))
	{
		if (normalFileExists("/etc/ssh/ssh_host_key") == FALSE)
		{
			int ret;
			printf(INFO "Generating /etc/ssh/ssh_host_key" NEWLINE);
			ret = evaluateRetVal(runProcess(7, 0, NULL, NULL, "ssh-keygen", "-t", "rsa1", "-f", "/etc/ssh/ssh_host_key", "-N", "", NULL));
			if (ret != 0)
				return ret;
		}
		if (normalFileExists("/etc/ssh/ssh_host_dsa_key") == FALSE)
		{
			int ret;
			printf(INFO "Generating /etc/ssh/ssh_host_dsa_key" NEWLINE);
			ret = evaluateRetVal(runProcess(7, 0, NULL, NULL, "ssh-keygen", "-t", "dsa", "-f", "/etc/ssh/ssh_host_dsa_key", "-N", "", NULL));
			if (ret != 0)
				return ret;
		}
		if (normalFileExists("/etc/ssh/ssh_host_rsa_key") == FALSE)
		{
			int ret;
			printf(INFO "Generating /etc/ssh/ssh_host_rsa_key" NEWLINE);
			ret = evaluateRetVal(runProcess(7, 0, NULL, NULL, "ssh-keygen", "-t", "rsa", "-f", "/etc/ssh/ssh_host_rsa_key", "-N", "", NULL));
			if (ret != 0)
				return ret;
		}
		printf(SUCCESS "Starting SSH Server..." NEWLINE);
		loadProc("/usr/sbin/sshd", PIDFILE, 0, 0, 0);
		usleep(50);
		{
			FILE *file;
			char *fileName, *PID;
			PID = readLine(PIDFILE, 1);
			if (PID == NULL)
			{
				printf(FAILURE "loadProc() failed to work! Please ignore the apparent success of the previous line." NEWLINE);
				return echoFailure();
			}
			fileName = toString("/proc/%s/oom_adj", PID);
			file = fopen(fileName, "w");
			fwrite("-16\n", 4, 1, file);
			fclose(file);
			free(fileName);
		}
	}
	else if (CHECK_ARG(1, "stop"))
	{
		printf(FAILURE "Stopping SSH Server..." NEWLINE);
		killProc("/usr/sbin/sshd", PIDFILE, -1, 0);
	}
	else if (CHECK_ARG(1, "reload"))
	{
		printf(WARNING "Reloading SSH Server..." NEWLINE);
		reloadProc("/usr/sbin/sshd", PIDFILE);
	}
	else if (CHECK_ARG(1, "restart"))
	{
		runProcess(2, RUN_PROC_PASS_STDOUT, NULL, NULL, argv[0], "stop", NULL);
		usleep(100);
		runProcess(2, RUN_PROC_PASS_STDOUT, NULL, NULL, argv[0], "start", NULL);
	}
	else if (CHECK_ARG(1, "status"))
		return statusProc("/usr/sbin/sshd", PIDFILE);
	else
		return usage(argv[0]);
	return 0;
}
コード例 #4
0
TEST(RepoClientTest, UploadTest)
{
	//this ensures we can run processes
	ASSERT_TRUE(system(nullptr));

	//Test failing to connect to database
	std::string db = "stUpload";
	std::string failToConnect = produceUploadArgs("invalidAdd", 12345, db, "failConn", getSuccessFilePath());
	EXPECT_EQ((int)REPOERR_AUTH_FAILED, runProcess(failToConnect));
	EXPECT_FALSE(projectExists(db, "failConn"));

	//Test Bad authentication
	std::string failToAuth = produceUploadArgs("blah", "blah", db, "failAuth", getSuccessFilePath());
	EXPECT_EQ((int)REPOERR_AUTH_FAILED, runProcess(failToAuth));
	EXPECT_FALSE(projectExists(db, "failAuth"));

	//Test Bad FilePath
	std::string badFilePath = produceUploadArgs(db, "failPath", "nonExistentFile.obj");
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(badFilePath));
	EXPECT_FALSE(projectExists(db, "failPath"));

	//Test Bad extension
	std::string badExt = produceUploadArgs(db, "failExt", getDataPath(badExtensionFile));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(badExt));
	EXPECT_FALSE(projectExists(db, "failExt"));

	//Insufficient arguments
	std::string lackArg = getClientExePath() + " " + REPO_GTEST_DBADDRESS + " " + std::to_string(REPO_GTEST_DBPORT) + " "
		+ REPO_GTEST_DBUSER + " " + REPO_GTEST_DBPW + " import " + getSuccessFilePath();
	EXPECT_EQ((int)REPOERR_INVALID_ARG, runProcess(lackArg));

	//Test Good Upload
	std::string goodUpload = produceUploadArgs(db, "cube", getSuccessFilePath());
	EXPECT_EQ((int)REPOERR_OK, runProcess(goodUpload));
	EXPECT_TRUE(projectExists(db, "cube"));

	//Test Textured Upload
	std::string texUpload = produceUploadArgs(db, "textured", getDataPath(texturedModel));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_MISSING_TEXTURE, runProcess(texUpload));
	EXPECT_TRUE(projectExists(db, "textured"));

	//Test missing nodes Upload
	std::string misUpload = produceUploadArgs(db, "missing", getDataPath(missingNodesModel));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_MISSING_NODES, runProcess(misUpload));
	EXPECT_TRUE(projectExists(db, "missing"));

	//Upload IFCFile
	std::string ifcUpload = produceUploadArgs(db, "ifcTest", getDataPath(ifcModel));
	EXPECT_EQ((int)REPOERR_OK, runProcess(ifcUpload));
	EXPECT_TRUE(projectExists(db, "ifcTest"));

	//JSON AS argument
	//Empty JSON
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(emptyFile))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(importNoFile))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(emptyJSONFile))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(importbadDir))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(importbadDir2))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(importNoDatabase))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(importNoDatabase2))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(getDataPath(importNoProject))));
	EXPECT_EQ((int)REPOERR_LOAD_SCENE_FAIL, runProcess(produceUploadFileArgs(importNoProject2)));
	
	EXPECT_EQ((int)REPOERR_OK, runProcess(produceUploadFileArgs(getDataPath(importNoOwner))));
	EXPECT_TRUE(projectExists("testDB", importNoOwnerPro));
	EXPECT_TRUE(projectSettingsCheck("testDB", importNoOwnerPro, REPO_GTEST_DBUSER, "thisTag", "MyUpload"));
	
	EXPECT_EQ((int)REPOERR_OK, runProcess(produceUploadFileArgs(getDataPath(importNoOwner2))));
	EXPECT_TRUE(projectExists("testDB", importNoOwnerPro2));
	EXPECT_TRUE(projectSettingsCheck("testDB", importNoOwnerPro2, REPO_GTEST_DBUSER, "thisTag", "MyUpload"));

	EXPECT_EQ((int)REPOERR_OK, runProcess(produceUploadFileArgs(getDataPath(importSuccess))));
	EXPECT_TRUE(projectExists("testDB", importSuccessPro));
	EXPECT_TRUE(projectSettingsCheck("testDB", importSuccessPro, "owner", "", ""));

	EXPECT_EQ((int)REPOERR_OK, runProcess(produceUploadFileArgs(getDataPath(importSuccess2))));
	EXPECT_TRUE(projectExists("testDB", importSuccessPro2));
	EXPECT_TRUE(projectSettingsCheck("testDB", importSuccessPro2, "owner", "taggg", "desccc"));

}
コード例 #5
0
ファイル: process.c プロジェクト: sakirtemel/cse333-project1
pid_t runBackgroundProcess(const char *cmd){
	pid_t pid;
	pid = runProcess(cmd);
	return pid;
}
コード例 #6
0
ファイル: Library.cpp プロジェクト: yinchuandong/Library
void *thread_fun(void* arg){
	JNIEnv *env;
	jclass cls;
	jmethodID mid;


	if(g_jvm->AttachCurrentThread(&env,NULL) != JNI_OK){
		LOGE("%s: AttachCurrentThread() failed", __FUNCTION__);
		return NULL;
	}

	cls = env->GetObjectClass(g_obj);
	if (cls == NULL) {
		LOGE("FindClass() Error.....");
		goto error;
	}

//	mid = env->GetStaticMethodID(cls,"fromJNI","(I)V");
//	if (mid == NULL) {
//		LOGE("GetMethodID() Error.....");
//		goto error;
//	}
//	env->CallStaticVoidMethod(cls, mid,(int)arg);

	//============创建一个后台僵尸进程======================
	pid_t pid;
	struct rlimit r;
	int i;

	if((pid = fork()) < 0)
	{
		LOGI("i am daemon==1");
			perror("fork");
			exit(0);
	}
	else if(pid != 0)
	{
		LOGI("i am daemon==2");
	}

	setsid();
	LOGI("i am daemon==3");
	if((pid = fork()) < 0)
	{
		LOGI("i am daemon==4");
			perror("fork");
			exit(0);
	}
	else if(pid != 0)
	{
		LOGI("i am daemon==5");
	}

	chdir("/");
	LOGI("i am daemon==6");
	if(r.rlim_max == RLIM_INFINITY)
	{
			r.rlim_max = 1024;
	}
	//===================================

	int isExit;
	while(1)
	{
		LOGI("i am daemon sucess myservice====");
//		isExit = isProcessExist("com.example.myservice");
//		LOGD("%d isProcessExist============================", isExit);
//		isExit = isdaemonExist();
//		LOGD("%d isdaemonExist============================", isExit);
		runProcess("com.gw.library.service.action.alarm");
		sleep(60);
	}

error:
	if (g_jvm->DetachCurrentThread() != JNI_OK) {
		LOGE("%s: DetachCurrentThread() failed", __FUNCTION__);
	}
	pthread_exit(0);
}
コード例 #7
0
bool AvisynthCheckThread::checkAvisynth(QString &basePath, const SysinfoModel *const sysinfo, QFile *&path, const bool &x64)
{
	qDebug("Avisynth %s-Bit support is being tested.", x64 ? "64" : "32");

	//Look for "portable" Avisynth version
	static const char *const ARCH_DIR[] = { "x64", "x86" };
	const QLatin1String archSuffix = QLatin1String(ARCH_DIR[x64 ? 1 : 0]);
	if (ENABLE_PORTABLE_AVS)
	{
		const QString avsPortableDir = QString("%1/extra/Avisynth").arg(QCoreApplication::applicationDirPath());
		if (VALID_DIR(avsPortableDir))
		{
			QFileInfo avsDllFile(QString("%1/%2/avisynth.dll").arg(avsPortableDir, archSuffix)), devilDllFile(QString("%1/%2/devil.dll").arg(avsPortableDir, archSuffix));
			if (avsDllFile.exists() && devilDllFile.exists() && avsDllFile.isFile() && devilDllFile.isFile())
			{
				qWarning("Adding portable Avisynth to PATH environment variable: %s", MUTILS_UTF8(avsPortableDir));
				basePath = avsPortableDir;
			}
		}
	}

	//Get extra paths
	QStringList avisynthExtraPaths;
	if (!basePath.isEmpty())
	{
		avisynthExtraPaths << QString("%1/%2").arg(basePath, archSuffix);
	}

	//Setup process object
	const QStringList output = runProcess(AVS_CHECK_BINARY(sysinfo, x64), QStringList(), &avisynthExtraPaths);

	//Init regular expressions
	QRegExp avsLogo("Avisynth\\s+Checker\\s+(x86|x64)");
	QRegExp avsPath("Avisynth_DLLPath=(.+)");
	QRegExp avsVers("Avisynth_Version=(\\d+)\\.(\\d+)");
	
	//Check for version info
	bool avisynthLogo = false;
	quint32 avisynthVersion[2] = { 0, 0 };
	QString avisynthPath;
	for(QStringList::ConstIterator iter = output.constBegin(); iter != output.constEnd(); iter++)
	{
		if(avisynthLogo)
		{
			if(avsPath.indexIn(*iter) >= 0)
			{
				avisynthPath =  avsPath.cap(1).trimmed();
			}
			else if(avsVers.indexIn(*iter) >= 0)
			{
				quint32 temp[2];
				if(MUtils::regexp_parse_uint32(avsVers, temp, 2))
				{
					avisynthVersion[0] = temp[0];
					avisynthVersion[1] = temp[1];
				}
			}
		}
		else
		{
			if(avsLogo.lastIndexIn(*iter) >= 0)
			{
				avisynthLogo = true;
			}
		}
	}
	
	//Minimum required version found?
	if((avisynthVersion[0] >= 2) && (avisynthVersion[1] >= 50) && (!avisynthPath.isEmpty()))
	{
		Wow64RedirectionDisabler disableWow64Redir;
		path = new QFile(avisynthPath);
		if(!path->open(QIODevice::ReadOnly))
		{
			MUTILS_DELETE(path);
		}
		qDebug("Avisynth was detected successfully (current version: %u.%02u).", avisynthVersion[0], avisynthVersion[1]);
		qDebug("Avisynth DLL path: %s", MUTILS_UTF8(avisynthPath));
		return true;
	}
	
	//Failed to determine version
	qWarning("Failed to determine Avisynth version!");
	return false;
}
コード例 #8
0
// EXCEPTIONS: CProcessFailure
// TO DO:	clean up error reporting
//			use dialog to say we're busy and give a cancel button
void CPhonruleProcess::processDictionaries(CProcessStatus& status)
{
	CPathDescriptor sLOGPath;
	try
	{
		CModelFilesSet* pMFS = NULL;

		// do we operate on the src dicts or target dicts?
		CTypedPtrArray<CPtrArray, CPathDescriptor*>* pRootUnifiedDicts;
		switch(status.m_iCurrentSeqFunction)
		{
			case CProcess::kAnalysis:
				pRootUnifiedDicts = & status.m_pSrcDicts;
				pMFS =status.getInputMFS();
				if((*pRootUnifiedDicts).GetSize()==0)
					throw CProcessFailure(this, _T("There were no source dictionaries specified"));
				break;
			case CProcess::kSynthesis:
				pMFS =status.getOutputMFS();
				pRootUnifiedDicts = & status.m_pTarDicts;
				if((*pRootUnifiedDicts).GetSize()==0)
					throw CProcessFailure(this, _T("There were target dictionaries specified"));
				break;
			default: // the user should never be able to make this happen
				throw CProcessFailure(this, _T("Phonrule should only be called as part of analysis or synthesis"));
		}

		// combine all runs into one log
		sLOGPath = status.makeTempPath(pMFS->getAbrev() + _T("-phrl"), _T(".log"));
		sLOGPath.deleteFile();

		for(int iRootFileIndex = 0; iRootFileIndex< (*pRootUnifiedDicts).GetSize(); iRootFileIndex++)
		{

			CString sBaseName = (*pRootUnifiedDicts)[iRootFileIndex]->getFileName() + _T("-phrl");
			CPathDescriptor sOutputDictPath = status.makeTempPath(sBaseName,_T(".dic"));
			sOutputDictPath.deleteFile();

			USES_CONVERSION;
			char lpszErrorStr[1000];
			BOOL OK = setupProcess(lpszErrorStr,
						m_bTrace ||
						(status.m_pProcPrefs->m_dwFlags & CProcessingPrefs::kTrace), // jdh 11/11/99
						m_bMonitorRules,
						m_cCommentChar,
						T2CA(pMFS->getPhonrulePath()),			// lpszRulesPath
						T2CA((*pRootUnifiedDicts)[iRootFileIndex]->getFullPath()),	// lpszDictInPath
						T2CA(sOutputDictPath.getFullPath()),			// lpszDictOutPath
						T2CA(sLOGPath.getFullPath()),				// lpszLogFilePath
						TRUE); // append log

			if(!OK)
				throw(CProcessFailure(this, A2CT(lpszErrorStr)));


			BOOL bError = runProcess();

			WIN32_FIND_DATA fileInfo;
			if(INVALID_HANDLE_VALUE == FindFirstFile(sOutputDictPath.getFullPath(), &fileInfo))
				throw(CProcessFailure(this, _T("Phonrule DLL did not produce the expected dictionary.  Check the phonrule log for more information.")));

			// change the path so that latter processes will use what we produced
			(*(*pRootUnifiedDicts)[iRootFileIndex]) = sOutputDictPath;//.getFullPath();

			// make sure these are closed
			if(logfile)
				fclose(logfile);	// this is the same as errlogfile
			if(outfile)
				fclose(outfile);
		}

#ifndef rde279
#pragma message("I don't know if chopping this out is correct, but the logStream being created here is unused so it memory leaks")
#else
		CResultStreamFile* logStream =
			new CResultStreamFile(
					new CResultStreamDescriptor(this,
												_T("Phonrule Log"), //short description
												_T("Log of this process; read it for status and diagnostics."), // long description
												pMFS->getAbrev() + _T(" Phnrl Log")
											),
					sLOGPath.getFullPath(),
					status.getInputLang());
#endif
#ifndef hab241
		registerLog(status, sLOGPath, status.getInputLang());
#else // hab241
		status.registerResultStream(logStream);
#endif // hab241
	}
	catch(CProcessFailure failure)
	{
		if(logfile)
			fclose(logfile);	// this is the same as errlogfile
		if(outfile)
			fclose(outfile);

		registerLog(status, sLOGPath, status.getInputLang());
		throw(failure);
	}
	catch(CString sError)
	{
		if(logfile)
			fclose(logfile);	// this is the same as errlogfile
		if(outfile)
			fclose(outfile);
		registerLog(status, sLOGPath, status.getInputLang());
		throw(CProcessFailure(this, sError));
	}
}
コード例 #9
0
ファイル: tester.cpp プロジェクト: CSchool/AIBattle
int main(int argc, char **argv)
{
    if (argc != 3 && argc != 4)
    {
        std::cout << "Usage: Maxit_tester <program1> <program2> [<seed>]\n";
        return 1;
    }
    const char *program1 = argv[1];
    const char *program2 = argv[2];

    // init field
    if (argc >= 4)
        srand(atoi(argv[3]));
    else
        srand((unsigned int)time(NULL));
    for (int i = 0 ; i < size ; ++i)
    {
        for (int j = 0 ; j < size ; ++j)
        {
            field[i][j] = rand() % size + 1;
        }
    }
    col = 1;
    row = 1;

    // save field and score before the first move
    saveField(1);

    bool first = true;
    ExecutionResult result = ER_OK;
    for (int move = 0 ; move < size * size ; ++move)
    {
        std::ostringstream outs;
        for (int i = 0 ; i < size ; ++i)
        {
            for (int j = 0 ; j < size ; ++j)
            {
                outs << field[i][j] << " ";
            }
            outs << "\n";
        }
		outs << !first + 1 << "\n" << (first ? row : col) << "\n"; 
        std::string output;
        printInput(first, outs.str());
        result = runProcess(first ? program1 : program2, 
            outs.str(), output, 1000, 64000);
        if (result == ER_OK)
        {
            InStream ins(output);

            int rowcol;
            try
            {
                ins >> ValueInBounds<int>(rowcol, 1, size);
            }
            catch (ReadCheckerException &exception)
            {
                result = ER_IM;

                std::ostringstream outs;
                outs << output << std::endl << exception.getReadResultText() << ": " << exception.what() << std::endl;

                printLog(first, result, outs.str());
                break;
            }

            if  (
                    (first && field[row-1][rowcol-1]) ||
                    (!first && field[rowcol-1][col-1])
                )
            {

                if (first)
                    col = rowcol;
                else
                    row = rowcol;

                printLog(first, result, output);

                scores[!first] += field[row-1][col-1];
                
                field[row-1][col-1] = -field[row-1][col-1];
                // save field and score after the correct move
                saveField(!first + 1);
                field[row-1][col-1] = 0;

                // get next player
                bool canFirst = checkFirst(row);
                bool canSecond = checkSecond(col);
                if ((first && canSecond)
                    || (!first && canFirst))
                    first = !first;
                else if (canFirst)
                    first = true;
                else if (canSecond)
                    first = false;
                else 
                    break;
            }
            else
            {
                result = ER_IM;
                printLog(first, result, output);
                break;
            }
        }
        else
        {