Пример #1
0
POVMSFloat POVMS_Object::TryGetFloat(POVMSType key, POVMSFloat alt)
{
	if(Exist(key) == true)
		return GetFloat(key);

	return alt;
}
Пример #2
0
POVMSInt POVMS_Object::TryGetInt(POVMSType key, POVMSInt alt)
{
	if(Exist(key) == true)
		return GetInt(key);

	return alt;
}
Пример #3
0
POVMSUCS2String POVMS_Object::TryGetUCS2String(POVMSType key, const char *alt)
{
	if(Exist(key) == true)
		return GetUCS2String(key);

	return POVMS_ASCIItoUCS2String(alt);
}
Пример #4
0
POVMSUCS2String POVMS_Object::TryGetUCS2String(POVMSType key, const POVMSUCS2String& alt)
{
	if(Exist(key) == true)
		return GetUCS2String(key);

	return alt;
}
Пример #5
0
std::string POVMS_Object::TryGetString(POVMSType key, const char *alt)
{
	if(Exist(key) == true)
		return GetString(key);

	return std::string(alt);
}
Пример #6
0
POVMSType POVMS_Object::TryGetType(POVMSType key, POVMSType alt)
{
    if(Exist(key) == true)
        return GetType(key);

    return alt;
}
Пример #7
0
POVMSBool POVMS_Object::TryGetBool(POVMSType key, POVMSBool alt)
{
    if(Exist(key) == true)
        return GetBool(key);

    return alt;
}
Пример #8
0
POVMSLong POVMS_Object::TryGetLong(POVMSType key, POVMSLong alt)
{
	if(Exist(key) == true)
		return GetLong(key);

	return alt;
}
Пример #9
0
void XLFileUtil::DelTree(const std::string &path)
{
	auto pathname = XLStringUtil::pathseparator(path);
	#ifdef _WINDOWS
		if (pathname == "c:\\") return ;
		if (pathname == "C:\\") return ;
	#else
		if (pathname == "/") return ;
	#endif
	if (pathname == "") return ;
	//とりあえずセーフティかけとくかw
	if (pathname.size() <= 7 ) return ;

	if ( Exist(pathname) )
	{//ファイル?
		XLFileUtil::del(pathname);
		if (! Exist(pathname) )
		{
			return ;
		}
	}
	else
	{//ディレクトリかな
		pathname = pathname + PATHSEP;
		if (! Exist(pathname) )
		{//もう存在しないらしい
			return ;
		}
	}

	//pathnameはディレクトリ /終端 が入っている。
	//ディレクトリを巡回しながら消していく
	findfile(pathname , [&](const std::string& filename,const std::string& fullfilename) -> bool{
		auto dirname = fullfilename + PATHSEP;
		if (Exist(dirname) )
		{//ディレクトリなので再帰する
			DelTree(fullfilename);
		}
		else
		{
			del(fullfilename);
		}
		return true;
	});

}
Пример #10
0
bool Users::Add(User user)
{
    if(!Exist(user))
    {
        data.append(user);
        return true;
    }
    return false;
}
Пример #11
0
void PinKnob::RegisterStr(const std::string &name, const std::string &desc,
                          const std::string &val) {
  if (Exist(name))
    return;

  KNOB<std::string> *knob = new KNOB<std::string>(KNOB_MODE_WRITEONCE,
                                                  "pintool", name, val, desc);
  knob_table_[name] = TypedKnob(KNOB_TYPE_STR, knob);
}
Пример #12
0
std::string XLFileUtil::getTempDirectory(const std::string& projectname)
{
#if _MSC_VER
	char buffer[MAX_PATH] = {0};
	::GetTempPath(MAX_PATH , buffer);
	const std::string retTemp = buffer + projectname;
	if (!Exist(retTemp))
	{
		CreateDirectory(retTemp.c_str(),NULL);
	}
#else
	const std::string retTemp = "/tmp/" + projectname;
	if (!Exist(retTemp))
	{
		mkdir(retTemp.c_str(),0755);
	}
#endif
	return retTemp;
}
Пример #13
0
 QString ModArmIoIntf::ResultList::ToString( bool brief /*= true*/ )
 {
     QString res;
     ESS_ASSERT( m_list.size() == m_cmds->Size() );
     for (int i = 0; i < m_list.size(); ++i)
     {
         if (!brief) res += QString("Cmd: %1 ").arg(m_cmds->ToString());
         if (Exist(i)) res += QString("Res: %1 ").arg(m_list.at(i));
     }
     return res;
 }
Пример #14
0
		/***********************
		 * elix::path::Create
		 @ std::string directory
		 - return true if it's a directory exist
		*/
		bool Create( std::string path )
		{
			if ( !Exist(path) )
			{
			#ifdef __GNUWIN32__
				_mkdir( path.c_str() );
			#else
				mkdir( path.c_str(), 0744 );
			#endif
			}
			return true;
		}
Пример #15
0
	char* Get(char* key, unsigned int key_len) {
	    for (int i = 0; i < kMaxRehash; i++) {
		unsigned int index = HasFunc(key, key_len);
		char *ret = Address(index);
		if (Exist(index)) {
		    if (memcpy(ret, key, key_len) == 0) {
			return ret;
		    }
		}
	    }
	    return 0;
	};
Пример #16
0
logical pcBase :: RemoveFromSpecialExtent (char *extnames )
{
  char       *cur_extent = GetExtentName();
  logical     term       = NO;
BEGINSEQ
  if ( !cur_extent || !extnames )                   LEAVESEQ
  if ( !Exist() )                                   ERROR
  
  if ( strcmp(cur_extent,extnames) )
  {
    PropertyHandle   extent(GetDBHandle(),extnames,PI_Write);
                                                    SDBCERR
    if ( extent.Get(ExtractKey()) )
      extent.Delete();
  }
  else 
Пример #17
0
	bool Put(char *key, char *data, unsigned int data_size) {

	    unsigned int index = HasFunc(key, key_size_);

	    for (int i = 0; i < kMaxRehash; i++) {
		if (!Exist(index)) {
		    memcpy(Address(index), key, key_len);
		    memcpy(Address(index), data, data_size);
		    break;
		}
	    }

	    if (i == kMaxRehash) {
		return false;
	    }

	    return true;
	};
Пример #18
0
corona::Image* load_image_from_disk_or_packfile(const char* filename)
{
	corona::Image* img;
	//log("loading image %s", filename);
	if (Exist(filename))
	{
		img = corona::OpenImage(filename, corona::FF_AUTODETECT, corona::PF_DONTCARE);
	}
	else
	{
		img = load_image_from_packfile(filename);
	}

	if (!img)
	{
		err("loadimage: couldn't load image %s; corona just bombed.", filename);
	}
	return img;
}
Пример #19
0
void XLFileUtil::mkdirP(const std::string &dir)
{
	const auto dirname = XLStringUtil::pathseparator(dir);
	const auto dirs = XLStringUtil::split(PATHSEP,dirname);

	std::string path;
	for(auto it = dirs.begin();it != dirs.end(); ++it)
	{
		path += *it + PATHSEP;
		if (!Exist(path))
		{
	#ifdef _MSC_VER
			CreateDirectory(path.c_str(),NULL);
	#else
			mkdir(path.c_str(),0755);
	#endif
		}
	}
}
char *pc1_SDB_Resource :: GetContextType ( )
{
  char         *base_context = NULL;
BEGINSEQ
  if ( !Exist() )                                    ERROR
 
  if ( Inherits("SDB_Type") )
    base_context = "CTX_Structure";
  else if ( Inherits("SDB_Member") )
    base_context = "CTX_Property";
  else if ( Inherits("ADK_Project") )
    base_context = "CTX_Project";
  else if ( Inherits("ADK_Application") )
    base_context = "CTX_Application";
  else if ( Inherits("ADK_StyleElement") )
    base_context = "CTX_Control";
RECOVER
ENDSEQ
  return(base_context);
}
Пример #21
0
bool CompileMaps(const char *ext, MapScriptCompiler *compiler, char *directory = NULL)
{
	if (!directory)
		directory = ".";

	std::string pattern = std::string(directory);
	pattern.append("/*");

	std::vector<std::string> filenames;
	listFilePattern(filenames, pattern.c_str());
	for(std::vector<std::string>::iterator i = filenames.begin();
		i != filenames.end();
		i++)
	{
		if (ExtensionIs(i->c_str(),"map"))
		{
			std::string fullpath(directory);
			fullpath.append("/");
			fullpath.append(*i);

			char *s = stripext(fullpath.c_str());
			if (Exist(va("%s.%s", s,ext))) 
				if(!compiler->CompileMap(s))
					return false;
		}
		else if (i->at(0) != '.')
		{
			// for now, if it's not a .map then try to use it as a directory
			std::string newpath(directory);
			newpath.append("/");
			newpath.append(*i);
			CompileMaps(ext,compiler,(char *)newpath.c_str());
		}
	}


	//log ("");
	return true;
}
Пример #22
0
void GenerateDlg::InitCustomGui()
{
	QListWidgetItem* windows = ui.lstPlatform->takeItem(0);
	QListWidgetItem* mac = ui.lstPlatform->takeItem(0);
	QListWidgetItem* ios = ui.lstPlatform->takeItem(0);
	QListWidgetItem* android = ui.lstPlatform->takeItem(0);

	//if ( Exist(GetExePath() + L"\\components\\WINDOWS") )
	//	ui.lstPlatform->addItem(windows);

	//if ( Exist(GetExePath() + L"\\components\\MACOSX") )
	//	ui.lstPlatform->addItem(mac);

	//if ( Exist(GetExePath() + L"\\components\\IOS") )
	//	ui.lstPlatform->addItem(ios);

	if ( Exist(GetExePath() + L"\\components\\ANDROID") )
		ui.lstPlatform->addItem(android);

	PlatformChanged(ui.lstPlatform->item(0));
	ui.lstPlatform->item(0)->setSelected(true);
	ui.lstPlatform->hide();
	ui.btnCancel->hide();
}
Пример #23
0
logical pcBase :: ProvideInSpecialExtent (char *extnames )
{
  char       *cur_extent = GetExtentName();
  logical     term       = NO;
BEGINSEQ
  if ( !cur_extent || !extnames )                   LEAVESEQ
  if ( !Exist() )                                   ERROR
  
  if ( strcmp(cur_extent,extnames) )
  {
    PropertyHandle   extent(GetDBHandle(),extnames,PI_Write);
                                                    SDBCERR
// waere besser, aber der vertraegt weak-typed nicht
//    extent.Provide(ExtractKey());                   SDBCERR

    if ( !extent.Get(ExtractKey()) )
      extent.AddReference(*this);                   SDBCERR
  }

RECOVER
  term = YES;
ENDSEQ
  return(term);
}
Пример #24
0
 /// Ensure that the given subsystem exists. If it does
 /// not, throws an exception.
 static void EnsureExist(const std::string &k) {
     if (!Exist(k)) throw NoSuchSubsystem();
 }
Пример #25
0
void generation()
{
    individual fuqin1,fuqin2,*pipeiguodu,*pipeichi;
    int *peiduishuzu;//用来存放产生的随机配对
    pipeiguodu=new individual[zhongqunshu1];
    pipeichi=new individual[zhongqunshu1];
    peiduishuzu=new int[zhongqunshu1];
    int member1,member2,j=0,fuzhijishu=0,i=0,temp=0,tt=0;
    float zhizhen;
    //随机遍历的实现
    for(zhizhen=suijibianli();zhizhen<1;(zhizhen=zhizhen+zhizhenjuli))//设定指针1/66
    {
        pipeichi[fuzhijishu]=nowpop[fuzhi(zhizhen)];
        fuzhijishu++;
    }

    //交叉与变异的实现
    //交叉
    for(i=0;i<zhongqunshu1;i++)
    {
        peiduishuzu[i]=-1;
    }
    for (i=0; i<zhongqunshu1; i++)
    { 
        temp =rnd(0,zhongqunshu1-1); //产生值在0-zhongqunshu1-1的随机数 
        while(Exist(temp, i, peiduishuzu))//判断产生的随机数是否已经产生过,如果是,则再产生一个随机数 
        {
            temp =rnd(0,zhongqunshu1-1);
        }
        //如果没有的话,则把产生的随机数放在peiduishuzu中 
        *(peiduishuzu+i) = temp; 
    }
    for(i=0;i<zhongqunshu1-1;i=i+2)
    {
        fuqin1=pipeichi[peiduishuzu[i]];
        fuqin2=pipeichi[peiduishuzu[i+1]];
        crossover(fuqin1,fuqin2,newpop[i],newpop[i+1]);
    }
    for(j=0;j<zhongqunshu1;j++)
    {
        //if(newpop[j].geti<-1000)
        //cout<<"个体数值小于下界了";
        nowpop[j].geti=newpop[j].geti;
    }
    //
    guanjiancanshujisuan();
    //变异的实现
    for(j=0;j<zhongqunshu;j++)
    {
        bianyi(nowpop[j]);
    } 
    //
    guanjiancanshujisuan();
    //精英保留的实现
    jingyingbaoliu();
    //
    guanjiancanshujisuan();
    delete [] peiduishuzu;
    delete [] pipeichi;
    delete [] pipeiguodu;
}
Пример #26
0
void NormalDelete(pBtree p,int key)
{
	int pos;
	pos=Find(p->Key,1,p->Sum,key);
	if(IsLeaf(p))
	{
		if(Equal(p,pos,key))
		{
			Delete(p,pos);
		}
		return;
	}
	else
	{
		if(Equal(p,pos,key))
		{
			if(NodeAvailable(p->Child[pos-1]))
			{
				key=preUpdate(p,pos);
				NormalDelete(p->Child[pos-1],key);
			}
			else if(NodeAvailable(p->Child[pos]))
			{
				key=postUpdate(p,pos);
				NormalDelete(p->Child[pos],key);
			}
			else
			{
				Union(p,pos);
				NormalDelete(p->Child[pos-1],key);
			}
		}
		else
		{
			if(NodeAvailable(p->Child[pos-1]))
			{
				NormalDelete(p->Child[pos-1],key);
			}
			else
			{
				if(Exist(pos-2,p)&&NodeAvailable(p->Child[pos-2]))
				{
					rightFix(pos-2,p,pos-1);
					NormalDelete(p->Child[pos-1],key);
				}
				else if(Exist(pos,p)&&NodeAvailable(p->Child[pos]))
				{
					leftFix(pos-1,p,pos);
					NormalDelete(p->Child[pos-1],key);
				}
				else if(Exist(pos-2,p))
				{
					Union(p,pos-1);
					NormalDelete(p->Child[pos-2],key);
				}
				else
				{
					Union(p,pos);
					NormalDelete(p->Child[pos-1],key);
				}
			}
		}
	}
}
Пример #27
0
 ModArmIo::dword ModArmIoIntf::ResultList::operator[]( int i )
 {        
     ESS_ASSERT(Exist(i));
     return m_list.at(i);
 }
Пример #28
0
// per page tests
void runWTTT(scriptid_t scriptID, unsigned int shardNumber, const char* runNo, long batchID, bool wait, bool debug)
{
	// only do a sleep if the first run - not for manual or retests
	if ((atoi(runNo) == 1) && wait)
	{
		TraceNoise("Sleeping for a bit", runNo, scriptID);

		// sleep for an offset of seconds
		sleep(scriptID % 60);
	}

	ConnectionPtr connection;
	std::string strQuery;
	bool download = true;

	try
	{
#ifdef SHARD_AWARE
		TraceLogic("Connecting to db", CConfig::getShardDatabase(shardNumber).c_str(), shardNumber);
		connection.reset(
			new Connection(
					CConfig::getShardServer(shardNumber),
					CConfig::getShardDatabase(shardNumber),
					CConfig::getShardUser(shardNumber),
					CConfig::getShardPass(shardNumber),
					CConfig::getDBRetryTime()));
#else
		TraceLogic("Connecting to db", CConfig::getDBDatabase(), 0);
		connection.reset(
			new Connection(
					CConfig::getDBServer(),
					CConfig::getDBDatabase(),
					CConfig::getDBUser(),
					CConfig::getDBPass(),
					CConfig::getDBRetryTime()));
#endif
	}
	catch (const std::exception &e)
	{
		LogError("Exception Caught:", e.what(), scriptID);
		return;
	}

	// if the ScriptID == 0 - get it from the batch table
	if (scriptID == 0)
	{
		strQuery = Format(SQL_WTTT_BATCH_SEL, batchID);
		TraceSQL("Issuing", "", 0);
		if (ResultPtr result = connection->Query(strQuery))
		{
			if (result->Next())
			{
				RowPtr row = result->GetCurrentRow();

				scriptID = row->GetFieldLong(1);

				TraceLogic("batchID", "", batchID);
				TraceLogic("scriptID", "", scriptID);
			}
		}
	}

	// script and archive names
	const std::string filename = Format("/home/sc/bin/monitor_scripts/%ld_%u", scriptID, shardNumber);
	const std::string gzfilename = filename + ".gz";

	// Get script details
	long customerNo = 0;
	SC_SCRIPT_LANGUAGE scriptlanguage = SC_SCRIPT_LANGUAGE_UNKNOWN;
	std::string scriptversion;
	strQuery = Format(SQL_WTTT_SCRIPTINFO_SEL, scriptID);
	TraceSQL("Issuing", "", 0);
	if (ResultPtr result = connection->Query(strQuery))
	{
		if (result->Next())
		{
			RowPtr row = result->GetCurrentRow();

			customerNo = row->GetFieldLong(1);
			scriptlanguage = static_cast<SC_SCRIPT_LANGUAGE>(row->GetFieldLong(2));

			// Field can be NULL, so check before dereference
			if (const char* str = row->GetField(3))
			{
				scriptversion = str;
			}

			TraceLogic("customerNo", "", customerNo);
			TraceLogic("scriptlanguage", to_string(scriptlanguage).c_str(), int(scriptlanguage));
			TraceLogic("scriptversion", scriptversion.c_str(), scriptversion.size());
		}
	}

	switch (scriptlanguage)
	{
	case SC_SCRIPT_LANGUAGE_UNKNOWN:
		//
		// No recognised script or script language returned
		//
		LogError(
			"Script not found",
			Format("ScriptID=%d Shard=%d DB.name=%s DB.host=%s",
				scriptID,
				shardNumber,
				CConfig::getShardDatabase(shardNumber).c_str(),
				CConfig::getShardServer(shardNumber).c_str()).c_str(),
			0);
			exit(1);
		break;

	case SC_SCRIPT_LANGUAGE_PHP:
		//
		// Handle PHP script
		//
		strQuery = Format("select Code, length(Code) from Script where ScriptID=%ld", scriptID);
		TraceSQL("Issuing", "", 0);
		if (ResultPtr result = connection->Query(strQuery))
		{
			if (result->Next())
			{
				RowPtr row = result->GetCurrentRow();

				int scriptLength = row->GetFieldInteger(2);
				std::string scriptString(row->GetField(1), scriptLength);

				TraceLogic("length(Code)", "", scriptLength);

				umask(SC_WTTT_UMASK);
				int filePtr = open(filename.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU);
				if (filePtr != -1)
				{
					// output the body to the file
					int nbytes = write(filePtr, scriptString.c_str(), scriptLength);
					if (nbytes != scriptLength)
					{
						LogError("Incomplete write of PHP executeable to disc", to_string(nbytes).c_str(), scriptLength);
					}
					close(filePtr);
				}
				else
				{
					LogError("Unable to write PHP executable to disc", "", scriptID);
				}
			}
		}
		break;

	case SC_SCRIPT_LANGUAGE_CXX:
		//
		// Handle compiled C++ script
		//
		if (Exist(filename))
		{
			// Is the file out of date?
			strQuery = Format(SQL_WTTT_SCRIPTAGE_SEL, scriptID);
			TraceSQL("Issuing", "", 0);
			if (ResultPtr result = connection->Query(strQuery))
			{
				if (result->Next())
				{
					RowPtr row = result->GetCurrentRow();

					long dbage = row->GetFieldLong(1);

					TraceLogic("dbage", "", dbage);

					struct stat statbuf;
					bzero(&statbuf, 0);
					int ret = stat(filename.c_str(), &statbuf);
					TraceLogic("stat", "download", ret);

					download = ret == -1  ||  statbuf.st_mtime < dbage;
					TraceLogic("Overwrite the existing %s?", "download", int(download));

					TraceLogic("statbuf.st_mtime", "", statbuf.st_mtime);
				}
			}
		}

		//
		// Extract script from database
		//
		if (download)
		{
			strQuery = Format(SQL_WTTT_SCRIPT_SEL, scriptID);
			TraceSQL("Issuing", "", 0);
			if (ResultPtr result = connection->Query(strQuery))
			{
				if (result->Next())
				{
					RowPtr row = result->GetCurrentRow();

					int scriptLength = row->GetFieldInteger(2);
					std::string scriptString(row->GetField(1), scriptLength);

					// Field can be NULL, so check before dereference
					int agentVersion = 0;
					if (const char* str = row->GetField(3))
					{
						agentVersion = atoi(str);
					}

					TraceLogic("scriptLength", "", scriptLength);
					TraceLogic("scriptString", scriptString.c_str(), scriptString.size());
					TraceLogic("agentVersion", "", agentVersion);

					umask(SC_WTTT_UMASK);
					int filePtr = open(gzfilename.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU);
					if (filePtr != -1)
					{
						// output the body to the file
						int nbytes = write(filePtr, scriptString.c_str(), scriptLength);
						close(filePtr);

						if (nbytes == scriptLength)
						{
							// unzip, set permissions and prelink
							doUnzip(gzfilename);
							chmod(filename.c_str(), 0775);

							bool prelink = false;
							if (!CConfig::getIMMode())
							{
								TraceLogic("Connecting to passport db", CConfig::getPassportDbDatabase().c_str(), 0);
								ConnectionPtr connectionPassport(
									new Connection(
											CConfig::getPassportDbServer(),
											CConfig::getPassportDbDatabase(),
											CConfig::getPassportDbUser(),
											CConfig::getPassportDbPass(),
											CConfig::getDBRetryTime()));

								strQuery = Format("select Prelink from LibraryVersions where Version=%d", agentVersion);
								TraceSQL("Issuing", "", 0);
								if (ResultPtr result = connectionPassport->Query(strQuery))
								{
									if (result->Next())
									{
										RowPtr row = result->GetCurrentRow();

										prelink = row->GetFieldInteger(1) != 0;

										TraceLogic("prelink", to_string(prelink).c_str(), int(prelink));
									}
								}

								TraceLogic("prelink", "", int(prelink));
							}
							else
							{
								TraceLogic("prelink", "Don't prelink on IM node", 0);
							}

							if (prelink)
							{
								int ret = doPrelink(filename, SC_AGENT_VER_NUM);
								if (ret != 0)
								{
									LogError("Prelink failed", filename.c_str(), ret);
								}
							}
						}
						else
						{
							LogError("Incomplete write of C++ executeable to disc", to_string(nbytes).c_str(), scriptLength);
							return;
						}
					}
					else
					{
						LogError("Unable to write C++ executable to disc", "", scriptID);
						return;
					}
				}
				else
				{
					LogError("C++ Executable not in database", gzfilename.c_str(), result->GetRowCount());
					return;
				}
			}
			else
			{
				LogError("Query for C++ executable failed", strQuery.c_str(), result->GetRowCount());
				return;
			}
		}
		break;

	default:
		LogError("Fatal: Unknown language", "", int(scriptlanguage));
		return;
	}

	// close the db connection
	Clear(connection);

	//
	// Build command line
	//
	std::string systemCmd;

#ifdef USE_SHARED
	// For version 7
	if (scriptlanguage == SC_SCRIPT_LANGUAGE_CXX &&
		Exist("/home/sc/lib/libsiteconfidence.so." + scriptversion) &&
		Exist("/home/sc/lib/libscparser.so." + scriptversion) &&
		Exist("/home/sc/lib/libsiteconfidenceinterface.so." + scriptversion))
	{
		std::ostringstream os;
		os << "export LD_PRELOAD=";
		os << "/home/sc/lib/libsiteconfidence.so." << scriptversion << ":";
		os << "/home/sc/lib/libscparser.so." << scriptversion << ":";
		os << "/home/sc/lib/libsiteconfidenceinterface.so." << scriptversion << "; ";

		systemCmd += os.str();
	}
#endif

#ifdef SHARD_AWARE
	// set environment variables for debug and shardNumber
	{
		std::ostringstream os;
		os	<< "export SHARD_NUMBER=" << shardNumber << "; "
			<< "export SC_DEBUG_MANUAL_MODE=" << (debug != 0) << "; ";

		systemCmd += os.str();
	}
#endif

	// program command line
	{
		std::ostringstream os;
		os << filename << " " << runNo << " " << batchID << " " << scriptID << " " << customerNo;

		systemCmd += os.str();
	}

	//Print(Format("starting script:%s\n", systemCmd.c_str()));

	// execute
	TraceLogic("Starting script", systemCmd.c_str(), scriptID);
	int sysVal = system(systemCmd.c_str());
	int exitVal = WEXITSTATUS(sysVal);
	TraceLogic("System call returned", systemCmd.c_str(), exitVal);

	//Print(Format("script returned:%d\n", exitVal));
}
Пример #29
0
/***
	Open a file. If the file exists it is openned "rb+" else
	it is openned "wb+".
	Parameters:
		- szNameFile: Name of file (just the name or full path)
		- szMode
		- iShFlag
	Return:
		E_NOTOPEN or OK (errno e' setado)
***/
int
C_File::Open( const char *szNameFile, const char *szModePar, int iShFlagPar, BOOL bWait )
{
	C_FileCritSect	cCS0( this, CRITSECT0 );
	int		iMode;
	DWORD	dwShMode;
	DWORD	dwCreateMode;

	if( (_bIs32s && iFile != -1) || (!_bIs32s && hFile != INVALID_HANDLE_VALUE) ){
		return( !OK );
	}
	strcpy( szFileName, szNameFile ? szNameFile : "" );
	strcpy( szMode, szModePar ? szModePar : "" );
	iShFlag = iShFlagPar;
	do{
		iMode = Mode16( szModePar );
		dwAccess = Mode( szModePar );
		dwShMode = ShMode( iShFlagPar );
		dwCreateMode = szModePar ? CreateMode( szModePar ) : Exist( szFileName ) ? OPEN_EXISTING : CREATE_ALWAYS;
		if( _bIs32s ){
			if( szModePar != NULL ){
				if( iMode & O_CREAT ){
					iFile = sopen( szNameFile, iMode, iShFlagPar, S_IREAD | S_IWRITE );
				} else {
					iFile = sopen( szNameFile, iMode, iShFlagPar );
				}
			} else {
				if( Exist( szNameFile ) ){
					iFile = sopen( szNameFile, O_BINARY | O_RDWR, iShFlagPar );
				} else {
					iFile = sopen( szNameFile, O_BINARY | O_RDWR | O_CREAT, iShFlagPar, S_IREAD | S_IWRITE );
				}
			}
		} else {
			saSecurity.nLength = sizeof( SECURITY_ATTRIBUTES );
			saSecurity.lpSecurityDescriptor = NULL;
			saSecurity.bInheritHandle = TRUE;
			hFile = CreateFile( szNameFile, dwAccess, dwShMode, &saSecurity, dwCreateMode, 
						(DWORD) (FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_SEQUENTIAL_SCAN),
						NULL );
		}
		if( (_bIs32s && iFile == -1) || (!_bIs32s && hFile == INVALID_HANDLE_VALUE) ){
			if( _bIs32s ){
				if( errno == EEXIST && (iMode & O_EXCL) ){
					// ************************************************************
					// ATENCAO:
					// ************************************************************
					// nao tentar fechar outro arquivo para re-abrir este se 
					// errno == EEXIST && (iMode & O_EXCL)
					// ************************************************************
					iFile = -1;
					return( !OK );
				}
				if( errno == EACCES && bWait ){
					// o arquivo nao foi aberto porque estah sendo
					// usado por outro processo em modo exclusivo.
					// esperar um pouco e tentar novamente
					Sleep( 1000 );	// 1 segundo
					hFile = INVALID_HANDLE_VALUE;
					iFile = -1;

					// antes de continuar o loop, sair e entrar
					// novamente em regiao critica, para possibilitar
					// outros threads rodarem
					cCS0.LeaveCriticalSection();
					cCS0.EnterCriticalSection();
					continue;
				}
				if( errno != EMFILE ){
					iFile = -1;
					return( !OK );
				}
			} else {
				if( GetLastError() == ERROR_ALREADY_EXISTS && (dwCreateMode == CREATE_NEW) ){
					// ************************************************************
					// ATENCAO:
					// ************************************************************
					// nao tentar fechar outro arquivo para reabrir este se 
					// GetLastError() == ERROR_ALREADY_EXISTS && (dwCreateMode == CREATE_NEW)
					// ************************************************************
					return( !OK );
				}
				if( GetLastError() == ERROR_SHARING_VIOLATION && bWait ){
					// o arquivo nao foi aberto porque estah sendo
					// usado por outro processo em modo exclusivo.
					// esperar um pouco e tentar novamente
					Sleep( 1000 );	// 1 segundo
					hFile = INVALID_HANDLE_VALUE;
					iFile = -1;

					// antes de continuar o loop, sair e entrar
					// novamente em regiao critica, para possibilitar
					// outros threads rodarem
					cCS0.LeaveCriticalSection();
					cCS0.EnterCriticalSection();
					continue;
				}
				if( GetLastError() != ERROR_TOO_MANY_OPEN_FILES ){
#ifdef _USE_PRINTF_
					Printf( "C_File: Deu um erro doidao no Open." );
					Printf( "C_File: Fudeu em <%s>", szNameFile );
#endif
					hFile = INVALID_HANDLE_VALUE;
					iFile = -1;
					return( !OK );
				}
			}
#ifdef _USE_PRINTF_
			Printf( "C_File: Muitos arquivos abertos. Vou terminar." );
#endif
			return( !OK );
		}
	} while ( (_bIs32s && iFile == -1) || (!_bIs32s && hFile == INVALID_HANDLE_VALUE) );
	if( this == _xFile ){
		Seek( 0, SEEK_SET );
		char	szCaca[ 50 ];
		sprintf( szCaca, "%d", ++_iNumXDat );
		Write( szCaca, strlen( szCaca ) );
		Seek( 0, SEEK_SET );
		Lock( strlen( szCaca ) );
#ifdef _USE_PRINTF_
		Printf( "C_File: Abri o _xFile****************************" );
#endif
	}
	if( strstr( szMode, "a" ) != NULL ){
		Seek( 0L, SEEK_END );
	}
	Hash();
	_iNumOpenFiles++;
#ifdef _USE_PRINTF_
	Printf( "C_File: Abri o arquivo <%d> (nome = <%s> - handle = <%d>)", _iNumOpenFiles, szNameFile ? szNameFile : "NULL", _bIs32s ? iFile : (int) hFile );
#endif

	// MMF: apenas se nao for 32s e se iHeadSize estiver setado para um valor maior que 0
	if( !_bIs32s && iHeadSize > 0 ){
		// pegar o tamanho da janela no .ini
		char	szFullIniName[ MAXPATH ];

		GetAppFullPath( szFullIniName, MAXPATH );


		iMMFWinSize = GetPrivateProfileInt( CONFIG_SESSION, WINDOWSIZE_KEY, 
											WINDOWSIZE_DEFAULT, szFullIniName );

		// se o tamanho da janela for <= 0, significa que o usuario nao quer usar MMF
		hMMF = NULL;
		if( iMMFWinSize > 0 ){
			hMMF = CreateFileMapping( hFile, NULL,
				(dwAccess & GENERIC_WRITE) ? PAGE_READWRITE : PAGE_READONLY,
				0, 0, NULL );
		}
		pHeadView = NULL;
		pWinView = NULL;
		iWinNum = 0;
		iSeekWin = 0;
	}

	bRealLock = _bStaticRealLock;

	return( OK );
}
Пример #30
0
bool Directory::fileIsDir(void) const
{
	if(!mDirent) throw Exception("No more files in directory");
	//return (mDirent->d_type == DT_DIR);
	return Exist(filePath());
}