📄 os.cpp
字号:
/* File: OS.cpp Contains: OS utility functions */#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#ifndef WIN32 #include <dirent.h>#include <unistd.h>#include <sys/stat.h>#else//#include <windows.h>#endif#ifndef __Win32__ #include <sys/time.h> #include <unistd.h>#else #include <sys/timeb.h>#endif#include <time.h>#include "OS.h"#include "MyAssert.h"#ifdef __linux__ #include "StringParser.h"#endif#include "StrOperation.h"double OS::sDivisor = 0;double OS::sMicroDivisor = 0;Int64 OS::sMsecSince1970 = 0;Int64 OS::sMsecSince1900 = 0;Int64 OS::sInitialMsec = 0;Int64 OS::sWrapTime = 0;Int64 OS::sCompareWrap = 0;Int64 OS::sLastTimeMilli = 0;void OS::Initialize(){ sDivisor = 0; sMicroDivisor = 0; sMsecSince1970 = 0; sMsecSince1900 = 0; sInitialMsec = 0; sWrapTime = 0; sCompareWrap = 0; sLastTimeMilli = 0; Assert (sInitialMsec == 0); // do only once if (sInitialMsec != 0) return; //setup t0 value for msec since 1900 //t.tv_sec is number of seconds since Jan 1, 1970. Convert to seconds since 1900 Int64 the1900Sec = (Int64) (24 * 60 * 60) * (Int64) ((70 * 365) + 17) ; sMsecSince1900 = the1900Sec * 1000; sWrapTime = (Int64) 0x00000001 << 32; sCompareWrap = (Int64) 0xffffffff << 32; sLastTimeMilli = 0; sInitialMsec = OS::Milliseconds(); //Milliseconds uses sInitialMsec so this assignment is valid only once. sMsecSince1970 = ::time(NULL); // POSIX time always returns seconds since 1970 sMsecSince1970 *= 1000; // Convert to msec }#ifdef __Win32__OS_Error OS::GetErrno(){ int winErr = ::GetLastError(); // Convert to a POSIX errorcode. The *major* assumption is that // the meaning of these codes is 1-1 and each Winsock, etc, etc // function is equivalent in errors to the POSIX standard. This is // a big assumption, but the server only checks for a small subset of // the real errors, on only a small number of functions, so this is probably ok. switch (winErr) { case ERROR_FILE_NOT_FOUND: return ENOENT; case ERROR_PATH_NOT_FOUND: return ENOENT; case WSAEINTR: return EINTR; case WSAENETRESET: return EPIPE; case WSAENOTCONN: return ENOTCONN; case WSAEWOULDBLOCK:return EAGAIN; case WSAECONNRESET: return ECONNRESET; case WSAEADDRINUSE: return EADDRINUSE; case WSAEMFILE: return EMFILE; case WSAEINPROGRESS:return EINPROGRESS; case WSAEADDRNOTAVAIL: return EADDRNOTAVAIL; case WSAECONNABORTED: return EPIPE; case 0: return 0; default: return ENOTCONN; }}#elseOS_Error OS::GetErrno(){ return errno; }#endif#define IS_REGFILE 0100000 // otcal constents ,begin with 0#define IS_DIRECTORY 0040000Bool OS::DelFile(const char* pFile){#ifdef WIN32 if( DeleteFile(pFile)==0) { printf("IN RSF BUFFER MODULE--->DELETE FILE:%s ERROR\n",pFile); return FALSE; }#else if( unlink(pFile) == -1) { printf("IN RSF BUFFER MODULE-->UNLINK FILE %s ERROR!\n",pFile); return FALSE; }#endif return TRUE;}// DEL DIRECTORYBool OS::DelDir(const char* pDir){#ifndef WIN32 if( rmdir( pDir ) == -1 ) return FALSE; #else if( RemoveDirectory( pDir ) == 0 ) return FALSE;#endif return TRUE;}Bool OS::RecursiveDelDir(const char *inPath){ struct stat st; int ret = stat(inPath,&st); if( ret == -1 ) return TRUE; if( st.st_mode & IS_DIRECTORY ) // IS DIRECTORY { std::string fname;#ifndef WIN32 DIR* dp; if( (dp = opendir(inPath)) == 0 ) // read dir error return FALSE; struct dirent* dirp; while( (dirp=readdir(dp)) !=0 ) // get a file { fname = dirp->d_name; if( fname == "." || fname == ".." ) continue; fname = inPath; fname += "/"; fname += dirp->d_name; CStrOperate::ModifyPath(fname); if( RecursiveDelDir( fname.c_str() ) ==FALSE ) return FALSE; } if( closedir(dp)<0 ) return FALSE;#else WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(inPath,&fd); if( hFind == INVALID_HANDLE_VALUE ) return TRUE; while( FindNextFile(hFind,&fd)!=0 ) { fname = inPath; fname += "/"; fname += fd.cFileName; CStrOperate::ModifyPath(fname); if(RecursiveDelDir( fname.c_str() ) ==FALSE ) return FALSE; } if( !FindClose( hFind ) ) return FALSE;#endif if( DelDir( inPath )==FALSE ) //if( DelDir( "/home/samsmith/movie/sh0.sdp.rfh" )==FALSE ) return FALSE; return TRUE; } else if( st.st_mode & IS_REGFILE ) // is regular file { if( DelFile( inPath ) == FALSE ) return FALSE; return TRUE; } return FALSE;}Bool OS::ConvertTimeToString(time_t v_t,char* v_str){ struct tm *p; struct tm t; p = localtime(&v_t); if( !p ) return FALSE; ::memcpy(&t,p,sizeof(t)); t.tm_year += 1900; t.tm_mon += 1; ::sprintf(v_str,"%04d-%02d-%02d %02d:%02d:%02d",t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec); return TRUE;}Int64 OS::Milliseconds(){ struct timeval t; Int64 curTime;#if __Win32__ struct _timeb temp; _ftime(&temp); t.tv_sec = temp.time; t.tv_usec = temp.millitm * 1000;#else struct timezone tz; int theErr = ::gettimeofday(&t, &tz); Assert(theErr == 0);#endif curTime = t.tv_sec; curTime *= 1000; // sec -> msec curTime += t.tv_usec / 1000; // usec -> msec return (curTime - sInitialMsec) + sMsecSince1970;}Int64 OS::Microseconds(){ struct timeval t; Int64 curTime; #if __Win32__ struct _timeb temp; _ftime(&temp); t.tv_sec = temp.time; t.tv_usec = temp.millitm * 1000;#else struct timezone tz; int theErr = ::gettimeofday(&t, &tz); Assert(theErr == 0);#endif curTime = t.tv_sec; curTime *= 1000000; // sec -> usec curTime += t.tv_usec; return curTime - (sInitialMsec * 1000);}Int32 OS::GetGMTOffset(){#ifdef __Win32__ TIME_ZONE_INFORMATION tzInfo; DWORD theErr = ::GetTimeZoneInformation(&tzInfo); if (theErr == TIME_ZONE_ID_INVALID) return 0; return ((tzInfo.Bias / 60) * -1);#else struct timeval tv; struct timezone tz; int err = ::gettimeofday(&tv, &tz); if (err != 0) return 0; return ((tz.tz_minuteswest / 60) * -1);//return hours before or after GMT#endif}char * OS::CTime(const time_t *timep, char* buffer, int buffLen){ ::strncpy( buffer, ::ctime(timep), buffLen); buffer[buffLen -1] = 0; return buffer; }OS_Error OS::MakeDir(char *inPath){
#ifdef WIN32
if(inPath[strlen(inPath)-1] == ':')
return OS_NoErr;
#endif
struct stat theStatBuffer; if (::stat(inPath, &theStatBuffer) == -1) { //this directory doesn't exist, so let's try to create it#ifdef __Win32__ if (::mkdir(inPath) == -1)#else if (::mkdir(inPath, S_IRWXU) == -1)#endif return (OS_Error)GetErrno(); }
#ifdef __Win32__ else if (!(theStatBuffer.st_mode & _S_IFDIR)) // MSVC++ doesn't define the S_ISDIR macro return EEXIST; // there is a file at this point in the path!#else else if (!S_ISDIR(theStatBuffer.st_mode)) return EEXIST;//there is a file at this point in the path!#endif //directory exists return OS_NoErr;}OS_Error OS::RecursiveMakeDir(char *inPath){ Assert(inPath != NULL); //iterate through the path, replacing '/' with '\0' as we go char *thePathTraverser = inPath; //skip over the first / in the path. if (*thePathTraverser == kPathDelimiterChar) thePathTraverser++; while (*thePathTraverser != '\0') { if (*thePathTraverser == kPathDelimiterChar) { //we've found a filename divider. Now that we have a complete //filename, see if this partial path exists. //make the partial path into a C string *thePathTraverser = '\0';
OS_Error theErr = MakeDir(inPath); //there is a directory here. Just continue in our traversal *thePathTraverser = kPathDelimiterChar; if (theErr != OS_NoErr && theErr != EEXIST)
return theErr;
} thePathTraverser++; } //need to create the last directory in the path return MakeDir(inPath);}UInt32 OS::GetNumProcessors(){#if (__Win32__) SYSTEM_INFO theSystemInfo; ::GetSystemInfo(&theSystemInfo); return (UInt32)theSystemInfo.dwNumberOfProcessors;#endif#if __linux__ char cpuBuffer[8192] = ""; StrPtrLen cpuInfoBuf(cpuBuffer, sizeof(cpuBuffer)); FILE *cpuFile = ::fopen( "/proc/cpuinfo", "r" ); if (cpuFile) { cpuInfoBuf.Len = ::fread(cpuInfoBuf.Ptr, sizeof(char), cpuInfoBuf.Len, cpuFile); ::fclose(cpuFile); } StringParser cpuInfoFileParser(&cpuInfoBuf); StrPtrLen line; StrPtrLen word; UInt32 numCPUs = 0; while( cpuInfoFileParser.GetDataRemaining() != 0 ) { cpuInfoFileParser.GetThruEOL(&line); // Read each line StringParser lineParser(&line); lineParser.ConsumeWhitespace(); //skip over leading whitespace if (lineParser.GetDataRemaining() == 0) // must be an empty line continue; lineParser.ConsumeUntilWhitespace(&word); if ( word.Equal("processor") ) // found a processor as first word in line { numCPUs ++; } } if (numCPUs == 0) numCPUs = 1; return numCPUs;#endif return 1;}void OS::Sleep(UInt32 inMsec){#ifdef __Win32__ ::Sleep(inMsec); #else usleep(inMsec*1000); #endif}
Bool OS::IsFileExist(const char* fileName)
{
struct stat st;
int ret;
ret = stat(fileName, &st);
if (ret < 0) return FALSE;
return TRUE;
}
UInt64 OS::LocalTimeToTime(const std::string& strLocalTime)
{
//验证合法性
if(strLocalTime.length() < 20 &&
strLocalTime.length() > 20 && strLocalTime.at(4) != '-' &&
strLocalTime.at(7) != '-' &&
strLocalTime.at(10) != ' ' &&
strLocalTime.at(13) != ':' &&
strLocalTime.at(16) != ':' &&
strLocalTime.at(19) != '\0')
{
return 0;
}
for(Int32 i=0; i<strLocalTime.length(); i++)
{
char a = strLocalTime.at(i);
if(a == '-' || a == ':')
continue;
if(a<30 && a>39)
return 0;
}
//end
Int32 nYear=0, nMounth=0, nDay=0, nHour=0, nMin=0, nSec=0;
sscanf(strLocalTime.c_str(), "%d-%d-%d %d:%d:%d",
&nYear, &nMounth, &nDay, &nHour, &nMin, &nSec);
if(nYear == 0 ||
nMounth == 0 ||
nDay == 0)
{
return 0;
}
struct tm t;
::memset(&t,0,sizeof(t));
t.tm_year = nYear - 1900;
t.tm_mon = nMounth - 1;
t.tm_mday = nDay;
t.tm_hour = nHour;
t.tm_min = nMin;
t.tm_sec = nSec;
return mktime(&t);
}
UInt64 OS::DateToSecond(Int32 nYear, Int32 nMounth, Int32 nDay, Int32 nHour, Int32 nMin, Int32 nSec)
{
if(nMounth == 1 || nMounth == 3 || nMounth == 5 || nMounth == 7 ||nMounth == 8 ||nMounth == 10 ||nMounth == 12)
{
nMounth *= 60 * 60 * 24 * 31;
}
else if(nMounth == 4 || nMounth == 6 || nMounth == 9 || nMounth == 11)
{
nMounth *= 60 * 60 * 24 * 30;
}
else
{
if(nYear%4 != 0)
{
nMounth *= 60 * 60 * 24 * 28;
}
else
{
if(nYear%100 != 0)
{
nMounth *= 60 * 60 * 24 * 29;
}
else
{
if(nYear%400 != 0)
{
nMounth *= 60 * 60 * 24 * 28;
}
else
{
nMounth *= 60 * 60 * 24 * 29;
}
}
}
}
UInt64 nTmpYear = nYear;
nTmpYear*= 60 * 60 * 24 * 365;
nDay *= 60 * 60 * 24;
nHour *= 60 * 60;
nMin *= 60;
return nTmpYear+nMounth+nDay+nHour+nMin+nSec;
}
Int32 OS::Rand()
{
srand(OS::Milliseconds() % RAND_MAX);
return rand();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -