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 const char* normal =
nullptr;
123 const char* shadow =
nullptr;
128 && ((normal = ::getenv(
"DYLD_LIBRARY_PATH")) ==
nullptr || !*normal)
129 && ((shadow = ::getenv(
"FOAM_LD_LIBRARY_PATH")) !=
nullptr && *shadow)
136 const auto paths = Foam::stringOps::split<Foam::string>(ldPaths,
':');
138 for (
const auto&
p : paths)
143 void* handle = ::dlopen(fullPath.c_str(), ldflags);
154 return ::dlopen(libName.c_str(), ldflags);
177 inline bool accept()
const 181 item_.size() && item_ !=
"." && item_ !=
".." 182 && (hidden_ || item_[0] !=
'.')
196 hidden_(allowHidden),
199 if (!dirName.empty())
201 dirptr_ = ::opendir(dirName.c_str());
202 exists_ = (dirptr_ !=
nullptr);
252 while (dirptr_ && (list = ::readdir(dirptr_)) !=
nullptr)
254 item_ = list->d_name;
316 return !envName.empty() && ::getenv(envName.c_str()) !=
nullptr;
323 char*
env = envName.empty() ? nullptr : ::getenv(envName.c_str());
339 const std::string& value,
347 && ::setenv(envName.c_str(), value.c_str(), overwrite) == 0
355 ::gethostname(buf,
sizeof(buf));
367 ::gethostname(buf,
sizeof(buf));
369 struct hostent *hp = ::gethostbyname(buf);
385 ::gethostname(buf,
sizeof(buf));
388 struct hostent *hp = ::gethostbyname(buf);
391 char *
p = ::strchr(hp->h_name,
'.');
405 struct passwd* pw = ::getpwuid(::getuid());
417 return (::geteuid() == 0);
423 char*
env = ::getenv(
"HOME");
429 struct passwd* pw = ::getpwuid(::getuid());
447 struct passwd* pw = ::getpwnam(
userName.c_str());
467 while (pathLengthLimit ==
path.size())
469 if (::getcwd(
path.data(),
path.size()))
473 else if (errno == ERANGE)
483 <<
"Attempt to increase path length beyond limit of " 488 path.resize(pathLengthLimit);
497 <<
"Couldn't get the current working directory" 508 const char*
env = ::getenv(
"PWD");
511 if (!
env ||
env[0] !=
'/')
514 <<
"PWD is invalid - reverting to physical description" 526 std::string::npos != (
pos = dir.find(
"/.",
pos));
535 !dir[
pos] || dir[
pos] ==
'/' 538 || (dir[
pos] ==
'.' && (!dir[
pos+1] || dir[
pos+1] ==
'/'))
542 <<
"PWD contains /. or /.. - reverting to physical description" 550 if (!fileStat(dir,
true).sameINode(fileStat(
".",
true)))
553 <<
"PWD is not the cwd() - reverting to physical description" 560 return fileName(dir);
586 return !dir.empty() && ::chdir(dir.c_str()) == 0;
598 error::printStack(
Pout);
603 if (pathName.empty())
609 if (::mkdir(pathName.c_str(),
mode) == 0)
620 <<
"The filesystem containing " << pathName
621 <<
" does not support the creation of directories." 636 <<
" points outside your accessible address space." 644 <<
"The parent directory does not allow write " 645 "permission to the process,"<<
nl 646 <<
" or one of the directories in " << pathName
647 <<
" did not allow search (execute) permission." 655 <<
"" << pathName <<
" is too long." 669 <<
"Couldn't create directory " << pathName
677 <<
"A component used as a directory in " << pathName
678 <<
" is not, in fact, a directory." 686 <<
"Insufficient kernel memory was available to make directory " 696 <<
" refers to a file on a read-only filesystem." 704 <<
"Too many symbolic links were encountered in resolving " 713 <<
"The device containing " << pathName
714 <<
" has no room for the new directory or " 715 <<
"the user's disk quota is exhausted." 723 <<
"Couldn't create directory " << pathName
740 error::printStack(
Pout);
745 return !
name.empty() && ::chmod(
name.c_str(), m) == 0;
756 error::printStack(
Pout);
763 fileStat fileStatus(
name, followLink);
764 if (fileStatus.good())
766 return fileStatus.status().st_mode;
777 const bool followLink
783 return fileName::Type::UNDEFINED;
795 return fileName::Type::FILE;
799 return fileName::Type::SYMLINK;
803 return fileName::Type::DIRECTORY;
806 return fileName::Type::UNDEFINED;
812 const fileName&
name,
813 const bool checkGzip,
814 const bool followLink
823 error::printStack(
Pout);
843 error::printStack(
Pout);
848 return !
name.empty() && S_ISDIR(
mode(
name, followLink));
854 const fileName&
name,
855 const bool checkGzip,
856 const bool followLink
865 error::printStack(
Pout);
875 || (checkGzip && S_ISREG(
mode(
name +
".gz", followLink)))
888 error::printStack(
Pout);
895 fileStat fileStatus(
name, followLink);
896 if (fileStatus.good())
898 return fileStatus.status().st_size;
913 error::printStack(
Pout);
929 error::printStack(
Pout);
934 return name.empty() ? 0 : fileStat(
name, followLink).dmodTime();
940 const fileName& directory,
941 const fileName::Type
type,
943 const bool followLink
947 constexpr
int maxNnames = 100;
954 if (!dirIter.exists())
959 <<
"cannot open directory " << directory <<
endl;
971 error::printStack(
Pout);
977 dirEntries.
resize(maxNnames);
980 for (; dirIter; ++dirIter)
982 const std::string& item = *dirIter;
994 (
type == fileName::Type::DIRECTORY)
995 || (
type == fileName::Type::FILE && !fileName::isBackup(
name))
998 fileName::Type detected = (directory/
name).
type(followLink);
1000 if (detected ==
type)
1006 && (detected != fileName::Type::DIRECTORY)
1013 if (nEntries >= dirEntries.
size())
1015 dirEntries.
resize(dirEntries.
size() + maxNnames);
1018 dirEntries[nEntries] = std::move(
name);
1025 dirEntries.
resize(nEntries);
1030 <<
"Foam::readDir() : reading directory " << directory <<
nl 1031 << nFailed <<
" entries with invalid characters in their name" 1039 bool Foam::cp(
const fileName& src,
const fileName& dest,
const bool followLink)
1046 error::printStack(
Pout);
1056 const fileName::Type srcType = src.type(followLink);
1058 fileName destFile(dest);
1061 if (srcType == fileName::FILE)
1064 if (destFile.type() == fileName::DIRECTORY)
1066 destFile /= src.name();
1070 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1076 std::ifstream srcStream(src, ios_base::in | ios_base::binary);
1082 std::ofstream destStream(destFile, ios_base::out | ios_base::binary);
1090 while (srcStream.get(ch))
1096 if (!srcStream.eof() || !destStream)
1101 else if (srcType == fileName::SYMLINK)
1104 if (destFile.type() == fileName::DIRECTORY)
1106 destFile /= src.name();
1110 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1117 else if (srcType == fileName::DIRECTORY)
1119 if (destFile.type() == fileName::DIRECTORY)
1128 const word srcDirName = src.name();
1129 if (destFile.name() != srcDirName)
1131 destFile /= srcDirName;
1141 char* realSrcPath = realpath(src.c_str(),
nullptr);
1142 char* realDestPath = realpath(destFile.c_str(),
nullptr);
1143 const bool samePath = strcmp(realSrcPath, realDestPath) == 0;
1148 <<
"Attempt to copy " << realSrcPath <<
" to itself" <<
endl;
1169 for (
const fileName& item : files)
1174 <<
"Copying : " << src/item
1175 <<
" to " << destFile/item <<
endl;
1179 Foam::cp(src/item, destFile/item, followLink);
1186 fileName::DIRECTORY,
1191 for (
const fileName& item : dirs)
1196 <<
"Copying : " << src/item
1197 <<
" to " << destFile <<
endl;
1201 Foam::cp(src/item, destFile, followLink);
1213 bool Foam::ln(
const fileName& src,
const fileName& dst)
1219 <<
" : Create symlink from : " << src <<
" to " << dst <<
endl;
1222 error::printStack(
Pout);
1229 <<
"source name is empty: not linking." <<
endl;
1236 <<
"destination name is empty: not linking." <<
endl;
1243 <<
"destination " << dst <<
" already exists. Not linking." 1248 if (src.isAbsolute() && !
exists(src))
1251 <<
"source " << src <<
" does not exist." <<
endl;
1255 if (::symlink(src.c_str(), dst.c_str()) == 0)
1261 <<
"symlink from " << src <<
" to " << dst <<
" failed." <<
endl;
1272 <<
" : Returning symlink destination for : " << link <<
endl;
1275 error::printStack(
Pout);
1286 result.resize(1024);
1288 ssize_t len = ::readlink(link.c_str(), &(result.front()), result.size());
1300 bool Foam::mv(
const fileName& src,
const fileName& dst,
const bool followLink)
1308 error::printStack(
Pout);
1313 if (src.empty() || dst.empty())
1320 dst.type() == fileName::DIRECTORY
1321 && src.type(followLink) != fileName::DIRECTORY
1326 return (0 == std::rename(src.c_str(), dstName.c_str()));
1329 return (0 == std::rename(src.c_str(), dst.c_str()));
1333 bool Foam::mvBak(
const fileName& src,
const std::string& ext)
1339 <<
" : moving : " << src <<
" to extension " << ext <<
endl;
1342 error::printStack(
Pout);
1347 if (src.empty() || ext.empty())
1354 constexpr
const int maxIndex = 99;
1357 for (
int n = 0;
n <= maxIndex; ++
n)
1362 ::snprintf(index, 4,
"%02d",
n);
1368 if (!
exists(dstName,
false) ||
n == maxIndex)
1370 return (0 == std::rename(src.c_str(), dstName.c_str()));
1380 bool Foam::rm(
const fileName& file)
1388 error::printStack(
Pout);
1402 0 == ::
remove(file.c_str())
1403 || 0 == ::
remove((file +
".gz").c_str())
1410 const fileName& directory,
1412 const bool emptyOnly
1415 if (directory.empty())
1423 POSIX::directoryIterator dirIter(directory,
true);
1424 if (!dirIter.exists())
1426 if (!silent && !emptyOnly)
1429 <<
"Cannot open directory " << directory <<
endl;
1441 error::printStack(
Pout);
1448 for (; dirIter; ++dirIter)
1450 const std::string& item = *dirIter;
1456 const fileName
path(fileName::concat(directory, item));
1458 fileName::Type detected =
path.type(
false);
1460 if (detected == fileName::Type::DIRECTORY)
1474 if (detected == fileName::Type::SYMLINK)
1476 detected =
path.type(
true);
1478 if (detected == fileName::Type::UNDEFINED)
1508 if (nErrors && !silent && !emptyOnly)
1511 <<
"Failed to remove directory " << directory <<
endl;
1515 Info<<
"could not remove " << nErrors <<
" sub-entries" <<
endl;
1519 return (nErrors == 0);
1534 <<
"close error on " << fd <<
endl 1542 const std::string& destName,
1543 const label destPort,
1547 struct hostent *hostPtr;
1548 volatile int sockfd;
1549 struct sockaddr_in destAddr;
1552 if ((hostPtr = ::gethostbyname(destName.c_str())) ==
nullptr)
1555 <<
"gethostbyname error " << h_errno <<
" for host " << destName
1560 addr = (
reinterpret_cast<struct in_addr*
>(*(hostPtr->h_addr_list)))->s_addr;
1563 sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
1572 std::memset(reinterpret_cast<char *>(&destAddr),
'\0',
sizeof(destAddr));
1573 destAddr.sin_family = AF_INET;
1574 destAddr.sin_port = htons(ushort(destPort));
1575 destAddr.sin_addr.s_addr = addr;
1578 timer myTimer(timeOut);
1592 reinterpret_cast<struct sockaddr*>(&destAddr),
1593 sizeof(
struct sockaddr)
1599 int connectErr = errno;
1603 if (connectErr == ECONNREFUSED)
1618 bool Foam::ping(
const std::string& host,
const label timeOut)
1620 return ping(host, 222, timeOut) ||
ping(host, 22, timeOut);
1627 static int waitpid(
const pid_t
pid)
1638 pid_t wpid = ::waitpid(
pid, &status, WUNTRACED);
1643 <<
"some error occurred in child" 1648 if (WIFEXITED(status))
1651 return WEXITSTATUS(status);
1654 if (WIFSIGNALED(status))
1657 return WTERMSIG(status);
1660 if (WIFSTOPPED(status))
1663 return WSTOPSIG(status);
1667 <<
"programming error, status from waitpid() not handled: " 1678 int Foam::system(
const std::string& command,
const bool bg)
1680 if (command.empty())
1690 const pid_t child_pid = ::vfork();
1692 if (child_pid == -1)
1695 <<
"vfork() failed for system command " << command
1700 else if (child_pid == 0)
1714 reinterpret_cast<char*
>(0)
1719 <<
"exec failed: " << command
1729 return (bg ? 0 : waitpid(child_pid));
1733 int Foam::system(
const CStringList& command,
const bool bg)
1735 if (command.empty())
1750 const pid_t child_pid = ::vfork();
1752 if (child_pid == -1)
1755 <<
"vfork() failed for system command " << command[0]
1760 else if (child_pid == 0)
1768 (void) ::execvp(command[0], command.strings());
1772 <<
"exec(" << command[0] <<
", ...) failed" 1782 return (bg ? 0 : waitpid(child_pid));
1788 if (command.
empty())
1795 const CStringList cmd(command);
1805 <<
"dlopen() of " << libName <<
std::endl;
1814 if (!libName.has_path() && !libName.starts_with(
"lib"))
1817 libso =
"lib" + libName;
1823 <<
" dlopen() as " << libso <<
std::endl;
1841 <<
" dlopen() as " << libso <<
std::endl;
1846 if (!handle &&
check)
1849 <<
"dlopen error : " << ::dlerror() <<
endl;
1855 <<
"dlopen() of " << libName
1863 void*
Foam::dlOpen(
const fileName& libName, std::string& errorMsg)
1871 errorMsg = ::dlerror();
1885 std::initializer_list<fileName> libNames,
1891 for (
const fileName& libName : libNames)
1909 <<
" : dlclose of handle " << handle <<
std::endl;
1911 return ::dlclose(handle) == 0;
1915 void*
Foam::dlSymFind(
void* handle,
const std::string& symbol,
bool required)
1917 if (!required && (!handle || symbol.empty()))
1925 <<
"dlSymFind(void*, const std::string&, bool)" 1926 <<
" : dlsym of " << symbol <<
std::endl;
1933 void* fun = ::dlsym(handle, symbol.c_str());
1936 char *err = ::dlerror();
1946 <<
"Cannot lookup symbol " << symbol <<
" : " << err
1957 struct dl_phdr_info *info,
1964 ptr->
append(info->dlpi_name);
1972 DynamicList<fileName> libs;
1974 for (uint32_t i=0; i < _dyld_image_count(); ++i)
1976 libs.
append(_dyld_get_image_name(i));
1986 <<
" : determined loaded libraries :" << libs.size() <<
std::endl;
void * dlSymFind(void *handle, const std::string &symbol, bool required=false)
Look for symbol in a dlopened library.
bool mvBak(const fileName &src, const std::string &ext="bak")
Rename to a corresponding backup file.
void size(const label n)
Older name for setAddressableSize.
bool mv(const fileName &src, const fileName &dst, const bool followLink=false)
Rename src to dst.
A class for handling file names.
off_t fileSize(const fileName &name, const bool followLink=true)
Return size of file or -1 on failure (normally follows symbolic links).
fileName readLink(const fileName &link)
Return the contents (target) of a symlink.
errorManipArg< error, int > exit(error &err, const int errNo=1)
void close()
Close directory.
void resize(const label len)
Adjust allocated size of list.
bool hasEnv(const std::string &envName)
True if environment variable of given name is defined.
error FatalError
Error stream (stdout output on all processes), with additional 'FOAM FATAL ERROR' header text and sta...
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
void append(const T &val)
Append an element at the end of the list.
int infoDetailLevel
Global for selective suppression of Info output.
pid_t ppid()
Return the parent PID of this process.
constexpr char nl
The newline '\n' character (0x0a)
bool empty() const noexcept
True if List is empty (ie, size() is zero)
Ostream & endl(Ostream &os)
Add newline and flush stream.
bool cp(const fileName &src, const fileName &dst, const bool followLink=true)
Copy the source to the destination (recursively if necessary).
bool dlClose(void *handle)
Close a dlopened library using handle. Return true if successful.
bool chDir(const fileName &dir)
Change current directory to the one specified and return true on success.
fileNameList dlLoaded()
Return all loaded libraries.
static std::string path(const std::string &str)
Return directory path name (part before last /)
static bool isAbsolute(const std::string &str)
Return true if filename starts with a '/' or '\' or (windows-only) with a filesystem-root.
string getEnv(const std::string &envName)
Get environment value for given envName.
~directoryIterator()
Destructor.
fileName home()
Return home directory path name for the current user.
static int collectLibsCallback(struct dl_phdr_info *info, size_t size, void *data)
fileName & replace_ext(const word &ending)
Remove extension (if any) and append a new one.
bool ping(const std::string &destName, const label port, const label timeOut)
Check if machine is up by pinging given port.
bool env(const std::string &envName)
Deprecated(2020-05) check for existence of environment variable.
static Foam::fileName cwd_P()
The physical current working directory path name (pwd -P).
StringType validate(const std::string &str, const UnaryPredicate &accept, const bool invert=false)
Return a copy of the input string with validated characters.
Useful combination of include files which define Sin, Sout and Serr and the use of IO streams general...
bool isDir(const fileName &name, const bool followLink=true)
Does the name exist as a DIRECTORY in the file system?
Functions used by OpenFOAM that are specific to POSIX compliant operating systems and need to be repl...
dimensionedScalar pos(const dimensionedScalar &ds)
fileName::Type type(const fileName &name, const bool followLink=true)
Return the file type: DIRECTORY or FILE, normally following symbolic links.
constexpr label pathLengthChunk
const std::string & val() const noexcept
The current item.
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
word name(const expressions::valueTypeCode typeCode)
A word representation of a valueTypeCode. Empty for expressions::valueTypeCode::INVALID.
bool has_ext() const
Various checks for extensions.
directoryIterator(const std::string &dirName, bool allowHidden=false)
Construct for dirName, optionally allowing hidden files/dirs.
static void * loadLibrary(const Foam::fileName &libName)
string domainName()
Deprecated(2022-01) domain name resolution may be unreliable.
directoryIterator & operator++()
Same as next()
time_t modTime() const
The modification time in seconds, 0 for an invalid file-stat.
static bool cwdPreference_(Foam::debug::optimisationSwitch("cwd", 0))
void fdClose(const int fd)
Close file descriptor.
time_t lastModified(const fileName &name, const bool followLink=true)
Return time of last file modification (normally follows symbolic links).
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?
string userName()
Return the user's login name.
void append(const T &val)
Copy append an element to the end of this list.
const std::string & operator*() const noexcept
Same as val()
graph_traits< Graph >::vertices_size_type size_type
errorManip< error > abort(error &err)
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
string hostName()
Return the system's host name, as per hostname(1)
bool ln(const fileName &src, const fileName &dst)
Create a softlink. dst should not exist. Returns true if successful.
bool rmDir(const fileName &directory, const bool silent=false, const bool emptyOnly=false)
Remove a directory and its contents recursively,.
unsigned int sleep(const unsigned int sec)
Sleep for the specified number of seconds.
pid_t pid()
Return the PID of this process.
int optimisationSwitch(const char *name, const int deflt=0)
Lookup optimisation switch or add default value.
int debug
Static debugging option.
fileName path(UMean.rootPath()/UMean.caseName()/"graphs"/UMean.instance())
defineTypeNameAndDebug(combustionModel, 0)
Wrapper for stat() and lstat() system calls.
static void check(const int retVal, const char *what)
#define timedOut(x)
Check if timeout has occurred.
pid_t pgid()
Return the group PID of this process.
bool chMod(const fileName &name, const mode_t mode)
Set the file/directory mode, return true on success.
bool isAdministrator()
Is the current user the administrator (root)
bool isFile(const fileName &name, const bool checkGzip=true, const bool followLink=true)
Does the name exist as a FILE in the file system?
static void redirects(const bool bg)
#define WarningInFunction
Report a warning using Foam::Warning.
void * dlOpen(const fileName &libName, const bool check=true)
Open a shared library and return handle to library.
fileName cwd()
The physical or logical current working directory path name.
bool good() const noexcept
Directory pointer is valid.
messageStream Info
Information stream (stdout output on master, null elsewhere)
bool has_ext() const
Various checks for extensions.
constexpr label pathLengthMax
int system(const std::string &command, const bool bg=false)
Execute the specified command via the shell.
bool next()
Read next item, always ignoring "." and ".." entries.
List< fileName > fileNameList
List of fileName.
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.
mode_t mode(const fileName &name, const bool followLink=true)
Return the file mode, normally following symbolic links.
static Foam::fileName cwd_L()
The logical current working directory path name.
A class for handling character strings derived from std::string.
bool setEnv(const word &name, const std::string &value, const bool overwrite)
Set an environment variable, return true on success.
prefixOSstream Pout
OSstream wrapped stdout (std::cout) with parallel prefix.
Type
Enumerations to handle directory entry types.
bool exists() const noexcept
Directory open succeeded.
bool remove_ext()
Remove extension, return true if string changed.
double highResLastModified(const fileName &, const bool followLink=true)
Return time of last file modification.
bool rm(const fileName &file)
Remove a file (or its gz equivalent), returning true if successful.
A simple directory contents iterator.
#define InfoInFunction
Report an information message using Foam::Info.