32#if defined(__sun__) && defined(__GNUC__)
60#include <sys/socket.h>
62#include <netinet/in.h>
66 #define EXT_SO "dylib"
67 #include <mach-o/dyld.h>
95static 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"
508static Foam::fileName
cwd_L()
510 const char*
env = ::getenv(
"PWD");
513 if (!
env ||
env[0] !=
'/')
516 <<
"PWD is invalid - reverting to physical description"
527 std::string::size_type
pos = 0;
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;
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
747 return !
name.empty() && ::chmod(
name.c_str(), m) == 0;
766 if (fileStatus.
good())
768 return fileStatus.
status().st_mode;
779 const bool followLink
815 const bool checkGzip,
816 const bool followLink
850 return !
name.empty() && S_ISDIR(
mode(
name, followLink));
857 const bool checkGzip,
858 const bool followLink
877 || (checkGzip && S_ISREG(
mode(
name +
".gz", followLink)))
898 if (fileStatus.good())
900 return fileStatus.status().st_size;
945 const bool followLink
949 constexpr int maxNnames = 100;
956 if (!dirIter.exists())
961 <<
"cannot open directory " << directory <<
endl;
979 dirEntries.
resize(maxNnames);
982 for (; dirIter; ++dirIter)
984 const std::string& item = *dirIter;
1002 if (detected ==
type)
1009 &&
name.has_ext(
"gz")
1015 if (nEntries >= dirEntries.
size())
1017 dirEntries.
resize(dirEntries.
size() + maxNnames);
1020 dirEntries[nEntries] = std::move(
name);
1027 dirEntries.
resize(nEntries);
1029 if (nFailed && POSIX::debug)
1032 <<
"Foam::readDir() : reading directory " << directory <<
nl
1033 << nFailed <<
" entries with invalid characters in their name"
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)
1108 destFile /= src.
name();
1112 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
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;
1147 if (POSIX::debug && samePath)
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);
1198 <<
"Copying : " << src/item
1199 <<
" to " << destFile <<
endl;
1203 Foam::cp(src/item, destFile, followLink);
1221 <<
" : Create symlink from : " << src <<
" to " << dst <<
endl;
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;
1288 result.resize(1024);
1290 ssize_t len = ::readlink(link.c_str(), &(result.front()), result.size());
1315 if (src.empty() || dst.empty())
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;
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()));
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;
1450 for (; dirIter; ++dirIter)
1452 const std::string& item = *dirIter;
1478 detected =
path.type(
true);
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);
1527 return ::sleep(sec);
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)
1620bool Foam::ping(
const std::string& host,
const label timeOut)
1622 return ping(host, 222, timeOut) ||
ping(host, 22, timeOut);
1629static 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: "
1680int 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
1858 <<
" handle " << handle << std::endl;
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;
1917void*
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 redirects(const bool bg)
static void * loadLibrary(const Foam::fileName &libName)
static int collectLibsCallback(struct dl_phdr_info *info, size_t size, void *data)
An adapter for copying a list of C++ strings into a list of C-style strings for passing to C code tha...
bool empty() const noexcept
True if the size (ie, argc) is zero.
char ** strings() const noexcept
Return the list of C-strings (ie, argv).
A 1D vector of objects of type <T> that resizes itself as necessary to accept the new objects.
void append(const T &val)
Copy append an element to the end of this list.
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bound...
void resize(const label len)
Adjust allocated size of list.
A simple directory contents iterator.
~directoryIterator()
Destructor.
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.
const std::string & val() const noexcept
The current item.
bool next()
Read next item, always ignoring "." and ".." entries.
directoryIterator & operator++()
Same as next().
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.
static bool master(const label communicator=worldComm)
True if process corresponds to the master rank in the communicator.
static void printStack(Ostream &os, int size=-1)
Helper function to print a stack, with optional upper limit.
A class for handling file names.
static fileName validate(const std::string &, const bool doClean=true)
Construct fileName without invalid characters, possibly applying other transformations such as changi...
fileName & replace_ext(const word &ending)
Remove extension (if any) and append a new one.
Type
Enumerations to handle directory entry types.
@ SYMLINK
A symbolic link.
@ UNDEFINED
Undefined type.
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.
static fileName concat(const std::string &s1, const std::string &s2, const char delim='/')
Join two strings with a path separator ('/' by default).
static bool isBackup(const std::string &str)
Return true if string ends with "~", ".bak", ".old", ".save".
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.
#define defineTypeNameAndDebug(Type, DebugSwitch)
Define the typeName and debug information.
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.
OS-specific functions implemented in POSIX.
constexpr label pathLengthChunk
constexpr label pathLengthMax
int optimisationSwitch(const char *name, const int deflt=0)
Lookup optimisation switch or add default value.
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.
bool rm(const fileName &file)
Remove a file (or its gz equivalent), returning true if successful.
static Foam::fileName cwd_P()
The physical current working directory path name (pwd -P).
fileName readLink(const fileName &link)
Return the contents (target) of a symlink.
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.
bool isAdministrator()
Is the current user the administrator (root).
bool dlClose(void *handle)
Close a dlopened library using handle. Return true if successful.
bool env(const std::string &envName)
Deprecated(2020-05) check for existence of environment variable.
List< fileName > fileNameList
List of fileName.
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.
static void check(const int retVal, const char *what)
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.
Ostream & endl(Ostream &os)
Add newline and flush stream.
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.
pid_t ppid()
Return the parent PID of this process.
errorManip< error > abort(error &err)
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...
static Foam::fileName cwd_L()
The logical current working directory path name.
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.
errorManipArg< error, int > exit(error &err, const int errNo=1)
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.