[LTP] [PATCH 1/2] Add tst_getpid() helper function

Martin Doucha mdoucha@suse.cz
Wed May 10 14:38:49 CEST 2023


tst_getpid() returns current process ID using direct syscall to bypass
PID caching in some glibc versions. The getpid() cache causes issues
for example in child processes created by direct clone() syscall.

Also use the function in tst_test.c whenever the current test process
may be a child created through unknown means.

Signed-off-by: Martin Doucha <mdoucha@suse.cz>
---
 include/tst_pid.h | 8 ++++++++
 lib/tst_pid.c     | 6 ++++++
 lib/tst_test.c    | 8 ++++----
 3 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/include/tst_pid.h b/include/tst_pid.h
index 8d999a655..774c845ce 100644
--- a/include/tst_pid.h
+++ b/include/tst_pid.h
@@ -42,4 +42,12 @@ static inline int tst_get_free_pids(void (*cleanup_fn)(void))
 }
 #endif
 
+/*
+ * Direct getpid() syscall. Some glibc versions cache getpid() return value
+ * which can cause confusing issues for example in processes created by
+ * direct clone() syscall (without using the glibc wrapper). Use this function
+ * whenever the current process may be a child of the main test process.
+ */
+pid_t tst_getpid(void);
+
 #endif /* TST_PID_H__ */
diff --git a/lib/tst_pid.c b/lib/tst_pid.c
index 2fa0c04cd..cfaa5db36 100644
--- a/lib/tst_pid.c
+++ b/lib/tst_pid.c
@@ -30,6 +30,7 @@
 #include "tst_pid.h"
 #include "old_safe_file_ops.h"
 #include "tst_safe_macros.h"
+#include "lapi/syscalls.h"
 
 #define PID_MAX_PATH "/proc/sys/kernel/pid_max"
 #define THREADS_MAX_PATH "/proc/sys/kernel/threads-max"
@@ -160,3 +161,8 @@ int tst_get_free_pids_(void (*cleanup_fn) (void))
 	}
 	return max_pids - used_pids;
 }
+
+pid_t tst_getpid(void)
+{
+	return syscall(SYS_getpid);
+}
diff --git a/lib/tst_test.c b/lib/tst_test.c
index 04d6b13bf..04da456c6 100644
--- a/lib/tst_test.c
+++ b/lib/tst_test.c
@@ -336,7 +336,7 @@ void tst_vbrk_(const char *file, const int lineno, int ttype,
 	 * specified but CLONE_THREAD is not. Use direct syscall to avoid
 	 * cleanup running in the child.
 	 */
-	if (syscall(SYS_getpid) == main_pid)
+	if (tst_getpid() == main_pid)
 		do_test_cleanup();
 
 	if (getpid() == lib_pid)
@@ -1316,7 +1316,7 @@ static void do_test_setup(void)
 	if (tst_test->setup)
 		tst_test->setup();
 
-	if (main_pid != getpid())
+	if (main_pid != tst_getpid())
 		tst_brk(TBROK, "Runaway child in setup()!");
 
 	if (tst_test->caps)
@@ -1379,7 +1379,7 @@ static void run_tests(void)
 		heartbeat();
 		tst_test->test_all();
 
-		if (getpid() != main_pid) {
+		if (tst_getpid() != main_pid) {
 			exit(0);
 		}
 
@@ -1395,7 +1395,7 @@ static void run_tests(void)
 		heartbeat();
 		tst_test->test(i);
 
-		if (getpid() != main_pid) {
+		if (tst_getpid() != main_pid) {
 			exit(0);
 		}
 
-- 
2.40.0



More information about the ltp mailing list