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> 94 static inline void redirects(
const bool bg)
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);
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));
320 ::gethostname(buf,
sizeof(buf));
322 struct hostent *hp = ::gethostbyname(buf);
338 ::gethostname(buf,
sizeof(buf));
341 struct hostent *hp = ::gethostbyname(buf);
344 char *
p = ::strchr(hp->h_name,
'.');
358 struct passwd* pw = ::getpwuid(::getuid());
370 return (::geteuid() == 0);
376 char*
env = ::getenv(
"HOME");
382 struct passwd* pw = ::getpwuid(::getuid());
400 struct passwd* pw = ::getpwnam(
userName.c_str());
420 while (pathLengthLimit ==
path.size())
422 if (::getcwd(
path.data(),
path.size()))
426 else if (errno == ERANGE)
436 <<
"Attempt to increase path length beyond limit of " 441 path.resize(pathLengthLimit);
450 <<
"Couldn't get the current working directory" 461 const char*
env = ::getenv(
"PWD");
464 if (!
env ||
env[0] !=
'/')
467 <<
"PWD is invalid - reverting to physical description" 479 std::string::npos != (
pos = dir.find(
"/.",
pos));
488 !dir[
pos] || dir[
pos] ==
'/' 491 || (dir[
pos] ==
'.' && (!dir[
pos+1] || dir[
pos+1] ==
'/'))
495 <<
"PWD contains /. or /.. - reverting to physical description" 503 if (!fileStat(dir,
true).sameINode(fileStat(
".",
true)))
506 <<
"PWD is not the cwd() - reverting to physical description" 513 return fileName(dir);
539 return !dir.empty() && ::chdir(dir.c_str()) == 0;
551 error::printStack(
Pout);
556 if (pathName.empty())
562 if (::mkdir(pathName.c_str(),
mode) == 0)
573 <<
"The filesystem containing " << pathName
574 <<
" does not support the creation of directories." 589 <<
" points outside your accessible address space." 597 <<
"The parent directory does not allow write " 598 "permission to the process,"<<
nl 599 <<
" or one of the directories in " << pathName
600 <<
" did not allow search (execute) permission." 608 <<
"" << pathName <<
" is too long." 622 <<
"Couldn't create directory " << pathName
630 <<
"A component used as a directory in " << pathName
631 <<
" is not, in fact, a directory." 639 <<
"Insufficient kernel memory was available to make directory " 649 <<
" refers to a file on a read-only filesystem." 657 <<
"Too many symbolic links were encountered in resolving " 666 <<
"The device containing " << pathName
667 <<
" has no room for the new directory or " 668 <<
"the user's disk quota is exhausted." 676 <<
"Couldn't create directory " << pathName
693 error::printStack(
Pout);
698 return !
name.empty() && ::chmod(
name.c_str(), m) == 0;
709 error::printStack(
Pout);
716 fileStat fileStatus(
name, followLink);
717 if (fileStatus.valid())
719 return fileStatus.status().st_mode;
730 const bool followLink
736 return fileName::Type::UNDEFINED;
748 return fileName::Type::FILE;
752 return fileName::Type::SYMLINK;
756 return fileName::Type::DIRECTORY;
759 return fileName::Type::UNDEFINED;
765 const fileName&
name,
766 const bool checkGzip,
767 const bool followLink
776 error::printStack(
Pout);
796 error::printStack(
Pout);
801 return !
name.empty() && S_ISDIR(
mode(
name, followLink));
807 const fileName&
name,
808 const bool checkGzip,
809 const bool followLink
818 error::printStack(
Pout);
828 || (checkGzip && S_ISREG(
mode(
name +
".gz", followLink)))
841 error::printStack(
Pout);
848 fileStat fileStatus(
name, followLink);
849 if (fileStatus.valid())
851 return fileStatus.status().st_size;
866 error::printStack(
Pout);
882 error::printStack(
Pout);
887 return name.empty() ? 0 : fileStat(
name, followLink).dmodTime();
893 const fileName& directory,
894 const fileName::Type
type,
896 const bool followLink
900 constexpr
int maxNnames = 100;
907 if (!dirIter.exists())
912 <<
"cannot open directory " << directory <<
endl;
924 error::printStack(
Pout);
930 dirEntries.
resize(maxNnames);
933 for (; dirIter; ++dirIter)
935 const std::string& item = *dirIter;
947 (
type == fileName::Type::DIRECTORY)
948 || (
type == fileName::Type::FILE && !fileName::isBackup(
name))
951 fileName::Type detected = (directory/
name).
type(followLink);
953 if (detected ==
type)
959 && (detected != fileName::Type::DIRECTORY)
966 if (nEntries >= dirEntries.
size())
968 dirEntries.
resize(dirEntries.
size() + maxNnames);
971 dirEntries[nEntries] = std::move(
name);
978 dirEntries.
resize(nEntries);
983 <<
"Foam::readDir() : reading directory " << directory <<
nl 984 << nFailed <<
" entries with invalid characters in their name" 992 bool Foam::cp(
const fileName& src,
const fileName& dest,
const bool followLink)
999 error::printStack(
Pout);
1009 const fileName::Type srcType = src.type(followLink);
1011 fileName destFile(dest);
1014 if (srcType == fileName::FILE)
1017 if (destFile.type() == fileName::DIRECTORY)
1019 destFile /= src.name();
1023 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1029 std::ifstream srcStream(src, ios_base::in | ios_base::binary);
1035 std::ofstream destStream(destFile, ios_base::out | ios_base::binary);
1043 while (srcStream.get(ch))
1049 if (!srcStream.eof() || !destStream)
1054 else if (srcType == fileName::SYMLINK)
1057 if (destFile.type() == fileName::DIRECTORY)
1059 destFile /= src.name();
1063 if (!
isDir(destFile.path()) && !
mkDir(destFile.path()))
1070 else if (srcType == fileName::DIRECTORY)
1072 if (destFile.type() == fileName::DIRECTORY)
1081 const word srcDirName = src.name();
1082 if (destFile.name() != srcDirName)
1084 destFile /= srcDirName;
1094 char* realSrcPath = realpath(src.c_str(),
nullptr);
1095 char* realDestPath = realpath(destFile.c_str(),
nullptr);
1096 const bool samePath = strcmp(realSrcPath, realDestPath) == 0;
1101 <<
"Attempt to copy " << realSrcPath <<
" to itself" <<
endl;
1122 for (
const fileName& item : files)
1127 <<
"Copying : " << src/item
1128 <<
" to " << destFile/item <<
endl;
1132 Foam::cp(src/item, destFile/item, followLink);
1139 fileName::DIRECTORY,
1144 for (
const fileName& item : dirs)
1149 <<
"Copying : " << src/item
1150 <<
" to " << destFile <<
endl;
1154 Foam::cp(src/item, destFile, followLink);
1166 bool Foam::ln(
const fileName& src,
const fileName& dst)
1172 <<
" : Create symlink from : " << src <<
" to " << dst <<
endl;
1175 error::printStack(
Pout);
1182 <<
"source name is empty: not linking." <<
endl;
1189 <<
"destination name is empty: not linking." <<
endl;
1196 <<
"destination " << dst <<
" already exists. Not linking." 1201 if (src.isAbsolute() && !
exists(src))
1204 <<
"source " << src <<
" does not exist." <<
endl;
1208 if (::symlink(src.c_str(), dst.c_str()) == 0)
1214 <<
"symlink from " << src <<
" to " << dst <<
" failed." <<
endl;
1225 <<
" : Returning symlink destination for : " << link <<
endl;
1228 error::printStack(
Pout);
1239 result.resize(1024);
1241 ssize_t len = ::readlink(link.c_str(), &(result.front()), result.size());
1253 bool Foam::mv(
const fileName& src,
const fileName& dst,
const bool followLink)
1261 error::printStack(
Pout);
1266 if (src.empty() || dst.empty())
1273 dst.type() == fileName::DIRECTORY
1274 && src.type(followLink) != fileName::DIRECTORY
1279 return (0 == std::rename(src.c_str(), dstName.c_str()));
1282 return (0 == std::rename(src.c_str(), dst.c_str()));
1286 bool Foam::mvBak(
const fileName& src,
const std::string& ext)
1292 <<
" : moving : " << src <<
" to extension " << ext <<
endl;
1295 error::printStack(
Pout);
1300 if (src.empty() || ext.empty())
1307 constexpr
const int maxIndex = 99;
1310 for (
int n = 0;
n <= maxIndex; ++
n)
1315 ::sprintf(index,
"%02d",
n);
1321 if (!
exists(dstName,
false) ||
n == maxIndex)
1323 return (0 == std::rename(src.c_str(), dstName.c_str()));
1333 bool Foam::rm(
const fileName& file)
1341 error::printStack(
Pout);
1355 0 == ::
remove(file.c_str())
1356 || 0 == ::
remove((file +
".gz").c_str())
1363 const fileName& directory,
1365 const bool emptyOnly
1368 if (directory.empty())
1376 POSIX::directoryIterator dirIter(directory,
true);
1377 if (!dirIter.exists())
1379 if (!silent && !emptyOnly)
1382 <<
"Cannot open directory " << directory <<
endl;
1394 error::printStack(
Pout);
1401 for (; dirIter; ++dirIter)
1403 const std::string& item = *dirIter;
1409 const fileName
path(fileName::concat(directory, item));
1411 fileName::Type detected =
path.type(
false);
1413 if (detected == fileName::Type::DIRECTORY)
1427 if (detected == fileName::Type::SYMLINK)
1429 detected =
path.type(
true);
1431 if (detected == fileName::Type::UNDEFINED)
1461 if (nErrors && !silent && !emptyOnly)
1464 <<
"Failed to remove directory " << directory <<
endl;
1468 Info<<
"could not remove " << nErrors <<
" sub-entries" <<
endl;
1472 return (nErrors == 0);
1487 <<
"close error on " << fd <<
endl 1495 const std::string& destName,
1496 const label destPort,
1500 struct hostent *hostPtr;
1501 volatile int sockfd;
1502 struct sockaddr_in destAddr;
1505 if ((hostPtr = ::gethostbyname(destName.c_str())) ==
nullptr)
1508 <<
"gethostbyname error " << h_errno <<
" for host " << destName
1513 addr = (
reinterpret_cast<struct in_addr*
>(*(hostPtr->h_addr_list)))->s_addr;
1516 sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
1525 std::memset(reinterpret_cast<char *>(&destAddr),
'\0',
sizeof(destAddr));
1526 destAddr.sin_family = AF_INET;
1527 destAddr.sin_port = htons(ushort(destPort));
1528 destAddr.sin_addr.s_addr = addr;
1531 timer myTimer(timeOut);
1545 reinterpret_cast<struct sockaddr*>(&destAddr),
1546 sizeof(
struct sockaddr)
1552 int connectErr = errno;
1556 if (connectErr == ECONNREFUSED)
1571 bool Foam::ping(
const std::string& host,
const label timeOut)
1573 return ping(host, 222, timeOut) ||
ping(host, 22, timeOut);
1580 static int waitpid(
const pid_t
pid)
1591 pid_t wpid = ::waitpid(
pid, &status, WUNTRACED);
1596 <<
"some error occurred in child" 1601 if (WIFEXITED(status))
1604 return WEXITSTATUS(status);
1607 if (WIFSIGNALED(status))
1610 return WTERMSIG(status);
1613 if (WIFSTOPPED(status))
1616 return WSTOPSIG(status);
1620 <<
"programming error, status from waitpid() not handled: " 1631 int Foam::system(
const std::string& command,
const bool bg)
1633 if (command.empty())
1642 const pid_t child_pid = ::vfork();
1644 if (child_pid == -1)
1647 <<
"vfork() failed for system command " << command
1652 else if (child_pid == 0)
1666 reinterpret_cast<char*
>(0)
1671 <<
"exec failed: " << command
1681 return (bg ? 0 : waitpid(child_pid));
1685 int Foam::system(
const CStringList& command,
const bool bg)
1687 if (command.empty())
1701 const pid_t child_pid = ::vfork();
1703 if (child_pid == -1)
1706 <<
"vfork() failed for system command " << command[0]
1711 else if (child_pid == 0)
1719 (void) ::execvp(command[0], command.strings());
1723 <<
"exec(" << command[0] <<
", ...) failed" 1733 return (bg ? 0 : waitpid(child_pid));
1739 if (command.
empty())
1746 const CStringList cmd(command);
1753 constexpr
int ldflags = (RTLD_LAZY|RTLD_GLOBAL);
1758 <<
"dlOpen(const fileName&)" 1759 <<
" : dlopen of " << libName <<
std::endl;
1762 void* handle = ::dlopen(libName.c_str(), ldflags);
1768 if (!libName.has_path() && !libName.starts_with(
"lib"))
1771 libso =
"lib" + libName;
1772 handle = ::dlopen(libso.c_str(), ldflags);
1777 <<
"dlOpen(const fileName&)" 1778 <<
" : dlopen of " << libso <<
std::endl;
1791 handle = ::dlopen(libso.c_str(), ldflags);
1796 <<
"dlOpen(const fileName&)" 1797 <<
" : dlopen of " << libso <<
std::endl;
1802 if (!handle &&
check)
1805 <<
"dlopen error : " << ::dlerror() <<
endl;
1811 <<
"dlOpen(const fileName&)" 1812 <<
" : dlopen of " << libName
1820 void*
Foam::dlOpen(
const fileName& libName, std::string& errorMsg)
1828 errorMsg = ::dlerror();
1842 std::initializer_list<fileName> libNames,
1848 for (
const fileName& libName : libNames)
1866 <<
" : dlclose of handle " << handle <<
std::endl;
1868 return ::dlclose(handle) == 0;
1872 void*
Foam::dlSymFind(
void* handle,
const std::string& symbol,
bool required)
1874 if (!required && (!handle || symbol.empty()))
1882 <<
"dlSymFind(void*, const std::string&, bool)" 1883 <<
" : dlsym of " << symbol <<
std::endl;
1890 void* fun = ::dlsym(handle, symbol.c_str());
1893 char *err = ::dlerror();
1903 <<
"Cannot lookup symbol " << symbol <<
" : " << err
1914 struct dl_phdr_info *info,
1921 ptr->
append(info->dlpi_name);
1929 DynamicList<fileName> libs;
1931 for (uint32_t i=0; i < _dyld_image_count(); ++i)
1933 libs.
append(_dyld_get_image_name(i));
1943 <<
" : 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 the UList 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 /)
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 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.
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.
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.
List< fileName > fileNameList
A List of fileNames.
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.