32 #if defined(__sun__) && defined(__GNUC__)
57 #include <sys/types.h>
60 #include <sys/socket.h>
62 #include <netinet/in.h>
66 #define EXT_SO "dylib"
67 #include <mach-o/dyld.h>
95 static inline void redirects(
const bool bg)
100 (void) ::close(STDIN_FILENO);
107 (void) ::dup2(STDERR_FILENO, STDOUT_FILENO);
119 constexpr
int ldflags = (RTLD_LAZY|RTLD_GLOBAL);
122 using namespace Foam;
124 const char* normal =
nullptr;
125 const char* shadow =
nullptr;
130 && ((normal = ::getenv(
"DYLD_LIBRARY_PATH")) ==
nullptr || !*normal)
131 && ((shadow = ::getenv(
"FOAM_LD_LIBRARY_PATH")) !=
nullptr && *shadow)
137 const std::string ldPaths(shadow);
140 for (
const auto&
p : paths)
145 void* handle = ::dlopen(fullPath.c_str(), ldflags);
156 return ::dlopen(libName.c_str(), ldflags);
179 inline bool accept()
const
183 item_.size() && item_ !=
"." && item_ !=
".."
184 && (hidden_ || item_[0] !=
'.')
198 hidden_(allowHidden),
201 if (!dirName.empty())
203 dirptr_ = ::opendir(dirName.c_str());
204 exists_ = (dirptr_ !=
nullptr);
254 while (dirptr_ && (list = ::readdir(dirptr_)) !=
nullptr)
256 item_ = list->d_name;
318 return !envName.empty() && ::getenv(envName.c_str()) !=
nullptr;
325 char*
env = envName.empty() ? nullptr : ::getenv(envName.c_str());
341 const std::string& value,
349 && ::setenv(envName.c_str(), value.c_str(), overwrite) == 0
357 ::gethostname(buf,
sizeof(buf));
369 ::gethostname(buf,
sizeof(buf));
371 struct hostent *hp = ::gethostbyname(buf);
387 ::gethostname(buf,
sizeof(buf));
390 struct hostent *hp = ::gethostbyname(buf);
393 char *
p = ::strchr(hp->h_name,
'.');
407 struct passwd* pw = ::getpwuid(::getuid());
419 return (::geteuid() == 0);
425 char*
env = ::getenv(
"HOME");
431 struct passwd* pw = ::getpwuid(::getuid());
449 struct passwd* pw = ::getpwnam(
userName.c_str());
469 while (pathLengthLimit ==
path.size())
471 if (::getcwd(
path.data(),
path.size()))
475 else if (errno == ERANGE)
485 <<
"Attempt to increase path length beyond limit of "
490 path.resize(pathLengthLimit);
499 <<
"Couldn't get the current working directory"
510 const char*
env = ::getenv(
"PWD");
513 if (!
env ||
env[0] !=
'/')
516 <<
"PWD is invalid - reverting to physical description"
528 std::string::npos != (
pos = dir.find(
"/.",
pos));
537 !dir[
pos] || dir[
pos] ==
'/'
540 || (dir[
pos] ==
'.' && (!dir[
pos+1] || dir[
pos+1] ==
'/'))
544 <<
"PWD contains /. or /.. - reverting to physical description"
555 <<
"PWD is not the cwd() - reverting to physical description"
588 return !dir.empty() && ::chdir(dir.c_str()) == 0;
600 error::printStack(
Pout);
605 if (pathName.empty())
611 if (::mkdir(pathName.c_str(),
mode) == 0)
622 <<
"The filesystem containing " << pathName
623 <<
" does not support the creation of directories."
638 <<
" points outside your accessible address space."
646 <<
"The parent directory does not allow write "
647 "permission to the process,"<<
nl
648 <<
" or one of the directories in " << pathName
649 <<
" did not allow search (execute) permission."
657 <<
"" << pathName <<
" is too long."
671 <<
"Couldn't create directory " << pathName
679 <<
"A component used as a directory in " << pathName
680 <<
" is not, in fact, a directory."
688 <<
"Insufficient kernel memory was available to make directory "
698 <<
" refers to a file on a read-only filesystem."
706 <<
"Too many symbolic links were encountered in resolving "
715 <<
"The device containing " << pathName
716 <<
" has no room for the new directory or "
717 <<
"the user's disk quota is exhausted."
725 <<
"Couldn't create directory " << pathName
742 error::printStack(
Pout);
747 return !
name.empty() && ::chmod(
name.c_str(), m) == 0;
758 error::printStack(
Pout);
766 if (fileStatus.
good())
768 return fileStatus.
status().st_mode;
779 const bool followLink
785 return fileName::Type::UNDEFINED;
797 return fileName::Type::FILE;
801 return fileName::Type::SYMLINK;
805 return fileName::Type::DIRECTORY;
808 return fileName::Type::UNDEFINED;
815 const bool checkGzip,
816 const bool followLink
825 error::printStack(
Pout);
845 error::printStack(
Pout);
850 return !
name.empty() && S_ISDIR(
mode(
name, followLink));
857 const bool checkGzip,
858 const bool followLink
867 error::printStack(
Pout);
877 || (checkGzip && S_ISREG(
mode(
name +
".gz", followLink)))
890 error::printStack(
Pout);
898 if (fileStatus.good())
900 return fileStatus.status().st_size;
915 error::printStack(
Pout);
931 error::printStack(
Pout);
945 const bool followLink
949 constexpr
int maxNnames = 100;
956 if (!dirIter.exists())
961 <<
"cannot open directory " << directory <<
endl;
973 error::printStack(
Pout);
979 dirEntries.
resize(maxNnames);
982 for (; dirIter; ++dirIter)
984 const std::string& item = *dirIter;
996 (
type == fileName::Type::DIRECTORY)
997 || (
type == fileName::Type::FILE && !fileName::isBackup(
name))
1002 if (detected ==
type)
1008 && (detected != fileName::Type::DIRECTORY)
1015 if (nEntries >= dirEntries.
size())
1017 dirEntries.
resize(dirEntries.
size() + maxNnames);
1020 dirEntries[nEntries] = std::move(
name);
1027 dirEntries.
resize(nEntries);
1032 <<
"Foam::readDir() : reading directory " << directory <<
nl
1033 << nFailed <<
" entries with invalid characters in their name"
1048 error::printStack(
Pout);
1063 if (srcType == fileName::FILE)
1066 if (destFile.type() == fileName::DIRECTORY)
1068 destFile /= src.
name();
1072 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1078 std::ifstream srcStream(src, ios_base::in | ios_base::binary);
1084 std::ofstream destStream(destFile, ios_base::out | ios_base::binary);
1092 while (srcStream.get(ch))
1098 if (!srcStream.eof() || !destStream)
1103 else if (srcType == fileName::SYMLINK)
1106 if (destFile.type() == fileName::DIRECTORY)
1108 destFile /= src.
name();
1112 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1119 else if (srcType == fileName::DIRECTORY)
1121 if (destFile.type() == fileName::DIRECTORY)
1130 const word srcDirName = src.
name();
1131 if (destFile.name() != srcDirName)
1133 destFile /= srcDirName;
1143 char* realSrcPath = realpath(src.c_str(),
nullptr);
1144 char* realDestPath = realpath(destFile.c_str(),
nullptr);
1145 const bool samePath = strcmp(realSrcPath, realDestPath) == 0;
1150 <<
"Attempt to copy " << realSrcPath <<
" to itself" <<
endl;
1176 <<
"Copying : " << src/item
1177 <<
" to " << destFile/item <<
endl;
1181 Foam::cp(src/item, destFile/item, followLink);
1188 fileName::DIRECTORY,
1198 <<
"Copying : " << src/item
1199 <<
" to " << destFile <<
endl;
1203 Foam::cp(src/item, destFile, followLink);
1221 <<
" : Create symlink from : " << src <<
" to " << dst <<
endl;
1224 error::printStack(
Pout);
1231 <<
"source name is empty: not linking." <<
endl;
1238 <<
"destination name is empty: not linking." <<
endl;
1245 <<
"destination " << dst <<
" already exists. Not linking."
1253 <<
"source " << src <<
" does not exist." <<
endl;
1257 if (::symlink(src.c_str(), dst.c_str()) == 0)
1263 <<
"symlink from " << src <<
" to " << dst <<
" failed." <<
endl;
1274 <<
" : Returning symlink destination for : " << link <<
endl;
1277 error::printStack(
Pout);
1288 result.resize(1024);
1290 ssize_t len = ::readlink(link.c_str(), &(result.front()), result.size());
1310 error::printStack(
Pout);
1315 if (src.empty() || dst.empty())
1322 dst.
type() == fileName::DIRECTORY
1323 && src.
type(followLink) != fileName::DIRECTORY
1328 return (0 == std::rename(src.c_str(), dstName.c_str()));
1331 return (0 == std::rename(src.c_str(), dst.c_str()));
1341 <<
" : moving : " << src <<
" to extension " << ext <<
endl;
1344 error::printStack(
Pout);
1349 if (src.empty() || ext.empty())
1356 constexpr
const int maxIndex = 99;
1359 for (
int n = 0;
n <= maxIndex; ++
n)
1364 ::snprintf(index, 4,
"%02d",
n);
1370 if (!
exists(dstName,
false) ||
n == maxIndex)
1372 return (0 == std::rename(src.c_str(), dstName.c_str()));
1390 error::printStack(
Pout);
1404 0 == ::remove(file.c_str())
1405 || 0 == ::remove((file +
".gz").c_str())
1414 const bool emptyOnly
1417 if (directory.empty())
1426 if (!dirIter.exists())
1428 if (!silent && !emptyOnly)
1431 <<
"Cannot open directory " << directory <<
endl;
1443 error::printStack(
Pout);
1450 for (; dirIter; ++dirIter)
1452 const std::string& item = *dirIter;
1458 const fileName path(fileName::concat(directory, item));
1462 if (detected == fileName::Type::DIRECTORY)
1476 if (detected == fileName::Type::SYMLINK)
1480 if (detected == fileName::Type::UNDEFINED)
1510 if (nErrors && !silent && !emptyOnly)
1513 <<
"Failed to remove directory " << directory <<
endl;
1517 Info<<
"could not remove " << nErrors <<
" sub-entries" <<
endl;
1521 return (nErrors == 0);
1536 <<
"close error on " << fd <<
endl
1544 const std::string& destName,
1545 const label destPort,
1549 struct hostent *hostPtr;
1550 volatile int sockfd;
1551 struct sockaddr_in destAddr;
1554 if ((hostPtr = ::gethostbyname(destName.c_str())) ==
nullptr)
1557 <<
"gethostbyname error " << h_errno <<
" for host " << destName
1562 addr = (
reinterpret_cast<struct in_addr*
>(*(hostPtr->h_addr_list)))->s_addr;
1565 sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
1574 std::memset(
reinterpret_cast<char *
>(&destAddr),
'\0',
sizeof(destAddr));
1575 destAddr.sin_family = AF_INET;
1576 destAddr.sin_port = htons(ushort(destPort));
1577 destAddr.sin_addr.s_addr = addr;
1580 timer myTimer(timeOut);
1594 reinterpret_cast<struct sockaddr*
>(&destAddr),
1595 sizeof(
struct sockaddr)
1601 int connectErr = errno;
1605 if (connectErr == ECONNREFUSED)
1620 bool Foam::ping(
const std::string& host,
const label timeOut)
1622 return ping(host, 222, timeOut) ||
ping(host, 22, timeOut);
1629 static int waitpid(
const pid_t
pid)
1640 pid_t wpid = ::waitpid(
pid, &status, WUNTRACED);
1645 <<
"some error occurred in child"
1650 if (WIFEXITED(status))
1653 return WEXITSTATUS(status);
1656 if (WIFSIGNALED(status))
1659 return WTERMSIG(status);
1662 if (WIFSTOPPED(status))
1665 return WSTOPSIG(status);
1669 <<
"programming error, status from waitpid() not handled: "
1680 int Foam::system(
const std::string& command,
const bool bg)
1682 if (command.empty())
1692 const pid_t child_pid = ::vfork();
1694 if (child_pid == -1)
1697 <<
"vfork() failed for system command " << command
1702 else if (child_pid == 0)
1716 reinterpret_cast<char*
>(0)
1721 <<
"exec failed: " << command
1731 return (bg ? 0 : waitpid(child_pid));
1737 if (command.
empty())
1752 const pid_t child_pid = ::vfork();
1754 if (child_pid == -1)
1757 <<
"vfork() failed for system command " << command[0]
1762 else if (child_pid == 0)
1770 (void) ::execvp(command[0], command.
strings());
1774 <<
"exec(" << command[0] <<
", ...) failed"
1784 return (bg ? 0 : waitpid(child_pid));
1790 if (command.
empty())
1807 <<
"dlopen() of " << libName <<
std::endl;
1819 libso =
"lib" + libName;
1825 <<
" dlopen() as " << libso <<
std::endl;
1843 <<
" dlopen() as " << libso <<
std::endl;
1848 if (!handle &&
check)
1851 <<
"dlopen error : " << ::dlerror() <<
endl;
1857 <<
"dlopen() of " << libName
1873 errorMsg = ::dlerror();
1887 std::initializer_list<fileName> libNames,
1893 for (
const fileName& libName : libNames)
1911 <<
" : dlclose of handle " << handle <<
std::endl;
1913 return ::dlclose(handle) == 0;
1917 void*
Foam::dlSymFind(
void* handle,
const std::string& symbol,
bool required)
1919 if (!required && (!handle || symbol.empty()))
1927 <<
"dlSymFind(void*, const std::string&, bool)"
1928 <<
" : dlsym of " << symbol <<
std::endl;
1935 void* fun = ::dlsym(handle, symbol.c_str());
1938 char *err = ::dlerror();
1948 <<
"Cannot lookup symbol " << symbol <<
" : " << err
1959 struct dl_phdr_info *info,
1966 ptr->
append(info->dlpi_name);
1976 for (uint32_t i=0; i < _dyld_image_count(); ++i)
1978 libs.
append(_dyld_get_image_name(i));
1988 <<
" : determined loaded libraries :" << libs.
size() <<
std::endl;
Useful combination of include files which define Sin, Sout and Serr and the use of IO streams general...
Functions used by OpenFOAM that are specific to POSIX compliant operating systems and need to be repl...
static bool cwdPreference_(Foam::debug::optimisationSwitch("cwd", 0))
static void * loadLibrary(const Foam::fileName &libName)
static void redirects(const bool bg)
static int collectLibsCallback(struct dl_phdr_info *info, size_t size, void *data)
graph_traits< Graph >::vertices_size_type size_type
An adapter for copying a list of C++ strings into a list of C-style strings for passing to C code tha...
char ** strings() const noexcept
Return the list of C-strings (ie, argv)
bool empty() const noexcept
True if the size (ie, argc) is zero.
void append(const T &val)
Copy append an element to the end of this list.
void resize(const label len)
Adjust allocated size of list.
A simple directory contents iterator.
~directoryIterator()
Destructor.
const std::string & val() const noexcept
The current item.
directoryIterator & operator++()
Same as next()
bool exists() const noexcept
Directory open succeeded.
bool good() const noexcept
Directory pointer is valid.
void close()
Close directory.
directoryIterator(const std::string &dirName, bool allowHidden=false)
Construct for dirName, optionally allowing hidden files/dirs.
bool next()
Read next item, always ignoring "." and ".." entries.
const std::string & operator*() const noexcept
Same as val()
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
bool empty() const noexcept
True if List is empty (ie, size() is zero)
void size(const label n)
Older name for setAddressableSize.
A class for handling file names.
fileName & replace_ext(const word &ending)
Remove extension (if any) and append a new one.
Type
Enumerations to handle directory entry types.
Type type(bool followLink=true, bool checkGzip=false) const
Return the directory entry type: UNDEFINED, FILE, DIRECTORY (or SYMLINK).
bool has_path() const
True if it contains a '/' character.
bool has_ext() const
Various checks for extensions.
static std::string path(const std::string &str)
Return directory path name (part before last /)
static std::string name(const std::string &str)
Return basename (part beyond last /), including its extension.
static bool isAbsolute(const std::string &str)
Return true if filename starts with a '/' or '\' or (windows-only) with a filesystem-root.
Wrapper for stat() and lstat() system calls.
const struct stat & status() const noexcept
The raw status.
time_t modTime() const
The modification time in seconds, 0 for an invalid file-stat.
bool good() const noexcept
True if file-stat was successful.
double dmodTime() const
The modification time in seconds (nanosecond resolution), 0 for an invalid file-stat.
A class for handling character strings derived from std::string.
bool starts_with(char c) const
True if string starts with given character (cf. C++20)
Implements a timeout mechanism via sigalarm.
A class for handling words, derived from Foam::string.
bool remove_ext()
Remove extension, return true if string changed.
bool has_ext() const
Various checks for extensions.
fileName path(UMean.rootPath()/UMean.caseName()/"graphs"/UMean.instance())
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
#define WarningInFunction
Report a warning using Foam::Warning.
#define InfoInFunction
Report an information message using Foam::Info.
constexpr label pathLengthChunk
constexpr label pathLengthMax
int optimisationSwitch(const char *name, const int deflt=0)
Lookup optimisation switch or add default value.
int debug
Static debugging option.
Foam::SubStrings split(const std::string &str, const char delim, std::string::size_type pos=0, const bool keepEmpty=false)
Split string into sub-strings at the delimiter character.
StringType validate(const std::string &str, const UnaryPredicate &accept, const bool invert=false)
Return a copy of the input string with validated characters.
bool rm(const fileName &file)
Remove a file (or its gz equivalent), returning true if successful.
static void check(const int retVal, const char *what)
fileName readLink(const fileName &link)
Return the contents (target) of a symlink.
errorManipArg< error, int > exit(error &err, const int errNo=1)
fileName cwd()
The physical or logical current working directory path name.
dimensionedScalar pos(const dimensionedScalar &ds)
string getEnv(const std::string &envName)
Get environment value for given envName.
bool setEnv(const word &name, const std::string &value, const bool overwrite)
Set an environment variable, return true on success.
time_t lastModified(const fileName &name, const bool followLink=true)
Return time of last file modification (normally follows symbolic links).
void fdClose(const int fd)
Close file descriptor.
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?
int system(const std::string &command, const bool bg=false)
Execute the specified command via the shell.
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
Ostream & endl(Ostream &os)
Add newline and flush stream.
bool isAdministrator()
Is the current user the administrator (root)
bool dlClose(void *handle)
Close a dlopened library using handle. Return true if successful.
errorManip< error > abort(error &err)
messageStream Info
Information stream (stdout output on master, null elsewhere)
mode_t mode(const fileName &name, const bool followLink=true)
Return the file mode, normally following symbolic links.
unsigned int sleep(const unsigned int sec)
Sleep for the specified number of seconds.
bool chMod(const fileName &name, const mode_t mode)
Set the file/directory mode, return true on success.
fileName::Type type(const fileName &name, const bool followLink=true)
Return the file type: DIRECTORY or FILE, normally following symbolic links.
string userName()
Return the user's login name.
pid_t pgid()
Return the group PID of this process.
bool env(const std::string &envName)
Deprecated(2020-05) check for existence of environment variable.
string hostName()
Return the system's host name, as per hostname(1)
void * dlSymFind(void *handle, const std::string &symbol, bool required=false)
Look for symbol in a dlopened library.
bool ping(const std::string &destName, const label port, const label timeOut)
Check if machine is up by pinging given port.
static Foam::fileName cwd_P()
The physical current working directory path name (pwd -P).
defineTypeNameAndDebug(combustionModel, 0)
pid_t ppid()
Return the parent PID of this process.
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 rmDir(const fileName &directory, const bool silent=false, const bool emptyOnly=false)
Remove a directory and its contents recursively,.
double highResLastModified(const fileName &, const bool followLink=true)
Return time of last file modification.
void * dlOpen(const fileName &libName, const bool check=true)
Open a shared library and return handle to library.
pid_t pid()
Return the PID of this process.
int infoDetailLevel
Global for selective suppression of Info output.
bool mvBak(const fileName &src, const std::string &ext="bak")
Rename to a corresponding backup file.
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 cp(const fileName &src, const fileName &dst, const bool followLink=true)
Copy the source to the destination (recursively if necessary).
fileNameList dlLoaded()
Return all loaded libraries.
error FatalError
Error stream (stdout output on all processes), with additional 'FOAM FATAL ERROR' header text and sta...
word name(const expressions::valueTypeCode typeCode)
A word representation of a valueTypeCode. Empty for expressions::valueTypeCode::INVALID.
prefixOSstream Pout
OSstream wrapped stdout (std::cout) with parallel prefix.
bool mv(const fileName &src, const fileName &dst, const bool followLink=false)
Rename src to dst.
fileName home()
Return home directory path name for the current user.
string domainName()
Deprecated(2022-01) domain name resolution may be unreliable.
bool ln(const fileName &src, const fileName &dst)
Create a softlink. dst should not exist. Returns true if successful.
bool isDir(const fileName &name, const bool followLink=true)
Does the name exist as a DIRECTORY in the file system?
bool hasEnv(const std::string &envName)
True if environment variable of given name is defined.
fileNameList readDir(const fileName &directory, const fileName::Type type=fileName::Type::FILE, const bool filtergz=true, const bool followLink=true)
Read a directory and return the entries as a fileName List.
constexpr char nl
The newline '\n' character (0x0a)
bool chDir(const fileName &dir)
Change current directory to the one specified and return true on success.
#define timedOut(x)
Check if timeout has occurred.