diff --git a/src/utils.cpp b/src/utils.cpp index 296915981a..745cb72b56 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -109,14 +109,11 @@ std::string utils::getsyserror() return std::string(strerror(errno)); } -/** \brief try to detect pathname from FILE pointer. Currently only supported on Linux, otherwise will report "(unknown)". - * - * \param buf storage buffer for pathname. output will be truncated if not large enough - * \param len size of storage buffer. output will be truncated to this length - 1 - * \param fp FILE pointer structe from STDIO library for which we want to detect the name - * \return pointer to the storage buffer, i.e. buf +/* + * On Linux the folder /proc/self/fd holds symbolic links to the actual + * pathnames associated with each open file descriptor of the current process. */ -static const char *guesspath(char *buf, int len, FILE *fp) +const char *utils::guesspath(char *buf, int len, FILE *fp) { memset(buf,0,len); @@ -124,9 +121,9 @@ static const char *guesspath(char *buf, int len, FILE *fp) int fd = fileno(fp); // get pathname from /proc or copy (unknown) if (readlink(fmt::format("/proc/self/fd/{}",fd).c_str(),buf,len-1) <= 0) - strcpy(buf,"(unknown)"); + strncpy(buf,"(unknown)",len-1); #else - strcpy(buf,"(unknown)"); + strncpy(buf,"(unknown)",len-1); #endif return buf; } diff --git a/src/utils.h b/src/utils.h index 047f6be296..abaa87ca5f 100644 --- a/src/utils.h +++ b/src/utils.h @@ -210,6 +210,17 @@ namespace LAMMPS_NS { */ bool is_double(const std::string & str); + /** \brief try to detect pathname from FILE pointer. + * + * Currently only supported on Linux, otherwise will report "(unknown)". + * + * \param buf storage buffer for pathname. output will be truncated if not large enough + * \param len size of storage buffer. output will be truncated to this length - 1 + * \param fp FILE pointer structe from STDIO library for which we want to detect the name + * \return pointer to the storage buffer, i.e. buf + */ + const char *guesspath(char *buf, int len, FILE *fp); + /** * \brief Strip off leading part of path, return just the filename * \param path file path diff --git a/unittest/utils/test_utils.cpp b/unittest/utils/test_utils.cpp index c4b4042bf9..8e23f7dd97 100644 --- a/unittest/utils/test_utils.cpp +++ b/unittest/utils/test_utils.cpp @@ -22,6 +22,7 @@ using namespace LAMMPS_NS; using ::testing::Eq; +using ::testing::EndsWith; TEST(Utils, trim_comment) { @@ -277,6 +278,20 @@ TEST(Utils, strmatch_opt_range) ASSERT_TRUE(utils::strmatch("rigid", "^[0-9]*[p-s]igid")); } +TEST(Utils, guesspath) +{ + char buf[128]; + FILE *fp = fopen("test_guesspath.txt","w"); +#if defined(__linux__) + const char *path = utils::guesspath(buf,sizeof(buf),fp); + ASSERT_THAT(path,EndsWith("test_guesspath.txt")); +#else + const char *path = utils::guesspath(buf,sizeof(buf),fp); + ASSERT_THAT(path,EndsWith("(unknown)")); +#endif + fclose(fp); +} + TEST(Utils, path_join) { #if defined(_WIN32)