Go to the documentation of this file.
32 #if defined(__sun__) && defined(__GNUC__)
56 #include <sys/types.h>
59 #include <sys/socket.h>
61 #include <netinet/in.h>
65 #define EXT_SO "dylib"
66 #include <mach-o/dyld.h>
99 (void) ::close(STDIN_FILENO);
106 (void) ::dup2(STDERR_FILENO, STDOUT_FILENO);
130 inline bool accept()
const
134 item_.size() && item_ !=
"." && item_ !=
".."
135 && (hidden_ || item_[0] !=
'.')
149 hidden_(allowHidden),
152 if (!dirName.empty())
154 dirptr_ = ::opendir(dirName.c_str());
155 exists_ = (dirptr_ !=
nullptr);
193 const std::string&
val()
const
205 while (dirptr_ && (list = ::readdir(dirptr_)) !=
nullptr)
207 item_ = list->d_name;
269 return !envName.empty() && ::getenv(envName.c_str()) !=
nullptr;
276 char*
env = envName.empty() ? nullptr : ::getenv(envName.c_str());
292 const std::string& value,
300 && ::setenv(envName.c_str(), value.c_str(), overwrite) == 0
308 ::gethostname(buf,
sizeof(buf));
313 struct hostent *hp = ::gethostbyname(buf);
327 ::gethostname(buf,
sizeof(buf));
330 struct hostent *hp = ::gethostbyname(buf);
333 char *
p = ::strchr(hp->h_name,
'.');
347 struct passwd* pw = ::getpwuid(::getuid());
359 return (::geteuid() == 0);
365 char*
env = ::getenv(
"HOME");
368 return fileName(
env);
371 struct passwd* pw = ::getpwuid(::getuid());
389 struct passwd* pw = ::getpwnam(
userName.c_str());
409 while (pathLengthLimit ==
path.size())
411 if (::getcwd(
path.data(),
path.size()))
415 else if (errno == ERANGE)
425 <<
"Attempt to increase path length beyond limit of "
430 path.resize(pathLengthLimit);
439 <<
"Couldn't get the current working directory"
450 const char*
env = ::getenv(
"PWD");
453 if (!
env ||
env[0] !=
'/')
456 <<
"PWD is invalid - reverting to physical description"
468 std::string::npos != (
pos = dir.find(
"/.",
pos));
477 !dir[
pos] || dir[
pos] ==
'/'
480 || (dir[
pos] ==
'.' && (!dir[
pos+1] || dir[
pos+1] ==
'/'))
484 <<
"PWD contains /. or /.. - reverting to physical description"
495 <<
"PWD is not the cwd() - reverting to physical description"
528 return !dir.empty() && ::chdir(dir.c_str()) == 0;
540 error::printStack(
Pout);
545 if (pathName.empty())
551 if (::mkdir(pathName.c_str(),
mode) == 0)
562 <<
"The filesystem containing " << pathName
563 <<
" does not support the creation of directories."
578 <<
" points outside your accessible address space."
586 <<
"The parent directory does not allow write "
587 "permission to the process,"<<
nl
588 <<
" or one of the directories in " << pathName
589 <<
" did not allow search (execute) permission."
597 <<
"" << pathName <<
" is too long."
605 if (pathName.path().size() &&
mkDir(pathName.path(),
mode))
611 <<
"Couldn't create directory " << pathName
619 <<
"A component used as a directory in " << pathName
620 <<
" is not, in fact, a directory."
628 <<
"Insufficient kernel memory was available to make directory "
638 <<
" refers to a file on a read-only filesystem."
646 <<
"Too many symbolic links were encountered in resolving "
655 <<
"The device containing " << pathName
656 <<
" has no room for the new directory or "
657 <<
"the user's disk quota is exhausted."
665 <<
"Couldn't create directory " << pathName
682 error::printStack(
Pout);
687 return !
name.empty() && ::chmod(
name.c_str(), m) == 0;
698 error::printStack(
Pout);
705 fileStat fileStatus(
name, followLink);
706 if (fileStatus.valid())
708 return fileStatus.status().st_mode;
721 return fileName::UNDEFINED;
733 return fileName::FILE;
737 return fileName::LINK;
741 return fileName::DIRECTORY;
744 return fileName::UNDEFINED;
750 const fileName&
name,
751 const bool checkGzip,
752 const bool followLink
761 error::printStack(
Pout);
781 error::printStack(
Pout);
786 return !
name.empty() && S_ISDIR(
mode(
name, followLink));
792 const fileName&
name,
793 const bool checkGzip,
794 const bool followLink
803 error::printStack(
Pout);
813 || (checkGzip && S_ISREG(
mode(
name +
".gz", followLink)))
826 error::printStack(
Pout);
833 fileStat fileStatus(
name, followLink);
834 if (fileStatus.valid())
836 return fileStatus.status().st_size;
851 error::printStack(
Pout);
856 return name.empty() ? 0 : fileStat(
name, followLink).modTime();
867 error::printStack(
Pout);
872 return name.empty() ? 0 : fileStat(
name, followLink).dmodTime();
878 const fileName& directory,
879 const fileName::Type
type,
881 const bool followLink
885 constexpr
int maxNnames = 100;
888 const bool stripgz = filtergz && (
type != fileName::DIRECTORY);
889 const word extgz(
"gz");
895 POSIX::directoryIterator dirIter(directory);
896 if (!dirIter.exists())
901 <<
"cannot open directory " << directory <<
endl;
913 error::printStack(
Pout);
919 dirEntries.resize(maxNnames);
922 for (; dirIter; ++dirIter)
924 const std::string& item = *dirIter;
936 (
type == fileName::DIRECTORY)
937 || (
type == fileName::FILE && !fileName::isBackup(
name))
942 if (nEntries >= dirEntries.size())
944 dirEntries.resize(dirEntries.size() + maxNnames);
953 dirEntries[nEntries++] =
name;
960 dirEntries.resize(nEntries);
965 <<
"Foam::readDir() : reading directory " << directory <<
nl
966 << nFailed <<
" entries with invalid characters in their name"
974 bool Foam::cp(
const fileName& src,
const fileName& dest,
const bool followLink)
981 error::printStack(
Pout);
991 const fileName::Type srcType = src.type(followLink);
993 fileName destFile(dest);
996 if (srcType == fileName::FILE)
999 if (destFile.type() == fileName::DIRECTORY)
1001 destFile /= src.name();
1005 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1011 std::ifstream srcStream(src, ios_base::in | ios_base::binary);
1017 std::ofstream destStream(destFile, ios_base::out | ios_base::binary);
1025 while (srcStream.get(ch))
1031 if (!srcStream.eof() || !destStream)
1036 else if (srcType == fileName::LINK)
1039 if (destFile.type() == fileName::DIRECTORY)
1041 destFile /= src.name();
1045 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1052 else if (srcType == fileName::DIRECTORY)
1055 if (destFile.type() == fileName::DIRECTORY)
1057 destFile /= src.components().last();
1066 char* realSrcPath = realpath(src.c_str(),
nullptr);
1067 char* realDestPath = realpath(destFile.c_str(),
nullptr);
1068 const bool samePath = strcmp(realSrcPath, realDestPath) == 0;
1073 <<
"Attempt to copy " << realSrcPath <<
" to itself" <<
endl;
1094 for (
const fileName& item : files)
1099 <<
"Copying : " << src/item
1100 <<
" to " << destFile/item <<
endl;
1104 cp(src/item, destFile/item, followLink);
1111 fileName::DIRECTORY,
1116 for (
const fileName& item : dirs)
1121 <<
"Copying : " << src/item
1122 <<
" to " << destFile <<
endl;
1126 cp(src/item, destFile, followLink);
1138 bool Foam::ln(
const fileName& src,
const fileName& dst)
1144 <<
" : Create softlink from : " << src <<
" to " << dst <<
endl;
1147 error::printStack(
Pout);
1154 <<
"source name is empty: not linking." <<
endl;
1161 <<
"destination name is empty: not linking." <<
endl;
1168 <<
"destination " << dst <<
" already exists. Not linking."
1173 if (src.isAbsolute() && !
exists(src))
1176 <<
"source " << src <<
" does not exist." <<
endl;
1180 if (::symlink(src.c_str(), dst.c_str()) == 0)
1186 <<
"symlink from " << src <<
" to " << dst <<
" failed." <<
endl;
1191 bool Foam::mv(
const fileName& src,
const fileName& dst,
const bool followLink)
1199 error::printStack(
Pout);
1204 if (src.empty() || dst.empty())
1211 dst.type() == fileName::DIRECTORY
1212 && src.type(followLink) != fileName::DIRECTORY
1215 const fileName dstName(dst/src.name());
1217 return (0 == std::rename(src.c_str(), dstName.c_str()));
1220 return (0 == std::rename(src.c_str(), dst.c_str()));
1224 bool Foam::mvBak(
const fileName& src,
const std::string& ext)
1230 <<
" : moving : " << src <<
" to extension " << ext <<
endl;
1233 error::printStack(
Pout);
1238 if (src.empty() || ext.empty())
1245 constexpr
const int maxIndex = 99;
1248 for (
int n = 0;
n <= maxIndex; ++
n)
1250 fileName dstName(src +
"." + ext);
1253 ::sprintf(index,
"%02d",
n);
1259 if (!
exists(dstName,
false) ||
n == maxIndex)
1261 return (0 == std::rename(src.c_str(), dstName.c_str()));
1271 bool Foam::rm(
const fileName& file)
1279 error::printStack(
Pout);
1293 0 == ::remove(file.c_str())
1294 || 0 == ::remove((file +
".gz").c_str())
1299 bool Foam::rmDir(
const fileName& directory,
const bool silent)
1304 POSIX::directoryIterator dirIter(directory,
true);
1305 if (!dirIter.exists())
1310 <<
"cannot open directory " << directory <<
endl;
1322 error::printStack(
Pout);
1329 for (; dirIter; ++dirIter)
1331 const std::string& item = *dirIter;
1337 const fileName
path(fileName::concat(directory, item));
1339 if (
path.type(
false) == fileName::DIRECTORY)
1360 <<
"failed to remove directory " << directory <<
nl
1361 <<
"could not remove " << nErrors <<
" sub-entries" <<
endl;
1372 <<
"failed to remove directory " << directory <<
endl;
1393 <<
"close error on " << fd <<
endl
1401 const std::string& destName,
1402 const label destPort,
1406 struct hostent *hostPtr;
1407 volatile int sockfd;
1408 struct sockaddr_in destAddr;
1411 if ((hostPtr = ::gethostbyname(destName.c_str())) ==
nullptr)
1414 <<
"gethostbyname error " << h_errno <<
" for host " << destName
1419 addr = (
reinterpret_cast<struct in_addr*
>(*(hostPtr->h_addr_list)))->s_addr;
1422 sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
1431 std::memset(
reinterpret_cast<char *
>(&destAddr),
'\0',
sizeof(destAddr));
1432 destAddr.sin_family = AF_INET;
1433 destAddr.sin_port = htons(ushort(destPort));
1434 destAddr.sin_addr.s_addr = addr;
1437 timer myTimer(timeOut);
1451 reinterpret_cast<struct sockaddr*
>(&destAddr),
1452 sizeof(
struct sockaddr)
1458 int connectErr = errno;
1462 if (connectErr == ECONNREFUSED)
1477 bool Foam::ping(
const std::string& host,
const label timeOut)
1479 return ping(host, 222, timeOut) ||
ping(host, 22, timeOut);
1486 static int waitpid(
const pid_t
pid)
1497 pid_t wpid = ::waitpid(
pid, &status, WUNTRACED);
1502 <<
"some error occurred in child"
1507 if (WIFEXITED(status))
1510 return WEXITSTATUS(status);
1513 if (WIFSIGNALED(status))
1516 return WTERMSIG(status);
1519 if (WIFSTOPPED(status))
1522 return WSTOPSIG(status);
1526 <<
"programming error, status from waitpid() not handled: "
1537 int Foam::system(
const std::string& command,
const bool bg)
1539 if (command.empty())
1548 const pid_t child_pid = ::vfork();
1550 if (child_pid == -1)
1553 <<
"vfork() failed for system command " << command
1558 else if (child_pid == 0)
1572 reinterpret_cast<char*
>(0)
1577 <<
"exec failed: " << command
1587 return (bg ? 0 : waitpid(child_pid));
1591 int Foam::system(
const CStringList& command,
const bool bg)
1593 if (command.empty())
1607 const pid_t child_pid = ::vfork();
1609 if (child_pid == -1)
1612 <<
"vfork() failed for system command " << command[0]
1617 else if (child_pid == 0)
1625 (void) ::execvp(command[0], command.strings());
1629 <<
"exec(" << command[0] <<
", ...) failed"
1639 return (bg ? 0 : waitpid(child_pid));
1645 if (command.
empty())
1652 const CStringList cmd(command);
1657 void*
Foam::dlOpen(
const fileName& libName,
const bool check)
1659 constexpr
int ldflags = (RTLD_LAZY|RTLD_GLOBAL);
1664 <<
"dlOpen(const fileName&)"
1665 <<
" : dlopen of " << libName <<
std::endl;
1668 void* handle = ::dlopen(libName.c_str(), ldflags);
1676 libName.find(
'/') == std::string::npos
1677 && !libName.starts_with(
"lib")
1681 libso =
"lib" + libName;
1682 handle = ::dlopen(libso.c_str(), ldflags);
1687 <<
"dlOpen(const fileName&)"
1688 <<
" : dlopen of " << libso <<
std::endl;
1698 if (!handle && !libso.hasExt(
EXT_SO))
1700 libso = libso.lessExt().ext(
EXT_SO);
1701 handle = ::dlopen(libso.c_str(), ldflags);
1706 <<
"dlOpen(const fileName&)"
1707 <<
" : dlopen of " << libso <<
std::endl;
1712 if (!handle && check)
1715 <<
"dlopen error : " << ::dlerror() <<
endl;
1721 <<
"dlOpen(const fileName&)"
1722 <<
" : dlopen of " << libName
1730 void*
Foam::dlOpen(
const fileName& libName, std::string& errorMsg)
1738 errorMsg = ::dlerror();
1752 std::initializer_list<fileName> libNames,
1758 for (
const fileName& libName : libNames)
1776 <<
" : dlclose of handle " << handle <<
std::endl;
1778 return ::dlclose(handle) == 0;
1782 void*
Foam::dlSymFind(
void* handle,
const std::string& symbol,
bool required)
1784 if (!required && (!handle || symbol.empty()))
1792 <<
"dlSymFind(void*, const std::string&, bool)"
1793 <<
" : dlsym of " << symbol <<
std::endl;
1800 void* fun = ::dlsym(handle, symbol.c_str());
1803 char *err = ::dlerror();
1813 <<
"Cannot lookup symbol " << symbol <<
" : " << err
1824 struct dl_phdr_info *info,
1831 ptr->
append(info->dlpi_name);
1839 DynamicList<fileName> libs;
1841 for (uint32_t i=0; i < _dyld_image_count(); ++i)
1843 libs.
append(_dyld_get_image_name(i));
1853 <<
" : determined loaded libraries :" << libs.size() <<
std::endl;
int debug
Static debugging option.
word lessExt() const
Return word without extension (part before last .)
string domainName()
Return the system's domain name, as per hostname(1) with the '-d' option.
constexpr label pathLengthMax
#define InfoInFunction
Report an information message using Foam::Info.
Functions used by OpenFOAM that are specific to POSIX compliant operating systems and need to be repl...
Useful combination of include files which define Sin, Sout and Serr and the use of IO streams general...
bool exists(const fileName &name, const bool checkGzip=true, const bool followLink=true)
Does the name exist (as DIRECTORY or FILE) in the file system?
A class for handling file names.
bool chMod(const fileName &name, const mode_t mode)
Set the file/directory mode, return true on success.
const volScalarField & cp
void close()
Close directory.
int system(const std::string &command, const bool bg=false)
Execute the specified command via the shell.
static void redirects(const bool bg)
thermo validate(args.executable(), "h")
Type
Enumerations to handle directory entry types.
Wrapper for stat() and lstat() system calls.
bool isFile(const fileName &name, const bool checkGzip=true, const bool followLink=true)
Does the name exist as a FILE in the file system?
bool rm(const fileName &file)
Remove a file (or its gz equivalent), returning true if successful.
void append(const T &val)
Append an element at the end of the list.
Ostream & endl(Ostream &os)
Add newline and flush stream.
void fdClose(const int fd)
Close file descriptor.
bool setEnv(const word &name, const std::string &value, const bool overwrite)
Set an environment variable, return true on success.
A class for handling character strings derived from std::string.
const std::string & operator*() const
Same as val()
prefixOSstream Pout
An Ostream wrapper for parallel output to std::cout.
constexpr label pathLengthChunk
bool good() const
Directory pointer is valid.
string getEnv(const std::string &envName)
Get environment value for given envName.
pid_t pgid()
Return the group PID of this process.
#define timedOut(x)
Check if timeout has occurred.
bool isAdministrator()
Is the current user the administrator (root)
mode_t mode(const fileName &name, const bool followLink=true)
Return the file mode, normally following symbolic links.
const std::string & val() const
The current item.
bool hasEnv(const std::string &envName)
True if environment variable of given name is defined.
string userName()
Return the user's login name.
static Foam::fileName cwd_L()
The logical current working directory path name.
off_t fileSize(const fileName &name, const bool followLink=true)
Return size of file or -1 on failure (normally follows symbolic links).
bool hasExt() const
Return true if it has an extension or simply ends with a '.'.
void * dlSymFind(void *handle, const std::string &symbol, bool required=false)
Look for symbol in a dlopened library.
word name(const complex &c)
Return string representation of complex.
DynamicList< T, SizeMin > & append(const T &val)
Append an element to the end of this list.
pid_t pid()
Return the PID of this process.
A simple directory contents iterator.
~directoryIterator()
Destructor.
pid_t ppid()
Return the parent PID of this process.
double highResLastModified(const fileName &, const bool followLink=true)
Return time of last file modification.
graph_traits< Graph >::vertices_size_type size_type
bool ping(const std::string &destName, const label port, const label timeOut)
Check if machine is up by pinging given port.
directoryIterator(const fileName &dirName, bool allowHidden=false)
Construct for dirName, optionally allowing hidden files/dirs.
int optimisationSwitch(const char *name, const int deflt=0)
Lookup optimisation switch or add default value.
bool empty() const noexcept
True if the UList is empty (ie, size() is zero)
bool mv(const fileName &src, const fileName &dst, const bool followLink=false)
Rename src to dst.
errorManip< error > abort(error &err)
int infoDetailLevel
Global for selective suppression of Info output.
errorManipArg< error, int > exit(error &err, const int errNo=1)
List< fileName > fileNameList
A List of fileNames.
bool mvBak(const fileName &src, const std::string &ext="bak")
Rename to a corresponding backup file.
bool chDir(const fileName &dir)
Change current directory to the one specified and return true on success.
static bool cwdPreference_(Foam::debug::optimisationSwitch("cwd", 0))
bool next()
Read next item, always ignoring "." and ".." entries.
fileName home()
Return home directory path name for the current user.
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
bool cp(const fileName &src, const fileName &dst, const bool followLink=true)
Copy the source to the destination (recursively if necessary).
static Foam::fileName cwd_P()
The physical current working directory path name (pwd -P).
bool rmDir(const fileName &directory, const bool silent=false)
Remove a directory and its contents (optionally silencing warnings)
bool env(const std::string &envName)
Deprecated(2020-05) check for existence of environment variable.
directoryIterator & operator++()
Same as next()
bool exists() const
Directory open succeeded.
fileName::Type type(const fileName &name, const bool followLink=true)
Return the file type: DIRECTORY or FILE, normally following symbolic links.
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
string hostName(const bool full=false)
Return the system's host name, as per hostname(1)
fileName path(UMean.rootPath()/UMean.caseName()/"graphs"/UMean.instance())
bool dlClose(void *handle)
Close a dlopened library using handle. Return true if successful.
static int collectLibsCallback(struct dl_phdr_info *info, size_t size, void *data)
bool ln(const fileName &src, const fileName &dst)
Create a softlink. dst should not exist. Returns true if successful.
fileName cwd()
The physical or logical current working directory path name.
fileNameList dlLoaded()
Return all loaded libraries.
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
fileNameList readDir(const fileName &directory, const fileName::Type type=fileName::FILE, const bool filtergz=true, const bool followLink=true)
Read a directory and return the entries as a fileName List.
defineTypeNameAndDebug(combustionModel, 0)
#define WarningInFunction
Report a warning using Foam::Warning.
unsigned int sleep(const unsigned int sec)
Sleep for the specified number of seconds.
void * dlOpen(const fileName &libName, const bool check=true)
Open a shared library and return handle to library.
time_t lastModified(const fileName &name, const bool followLink=true)
Return time of last file modification (normally follows symbolic links).
bool isDir(const fileName &name, const bool followLink=true)
Does the name exist as a DIRECTORY in the file system?
dimensionedScalar pos(const dimensionedScalar &ds)