1 // SPDX-License-Identifier: GPL-2.0
8 #include <linux/types.h>
9 #include <linux/wait.h>
17 #include <sys/mount.h>
18 #include <sys/prctl.h>
23 #include "../kselftest.h"
25 static inline int sys_pidfd_open(pid_t pid, unsigned int flags)
27 return syscall(__NR_pidfd_open, pid, flags);
30 static int safe_int(const char *numstr, int *converted)
36 sli = strtol(numstr, &err, 0);
37 if (errno == ERANGE && (sli == LONG_MAX || sli == LONG_MIN))
40 if (errno != 0 && sli == 0)
43 if (err == numstr || *err != '\0')
46 if (sli > INT_MAX || sli < INT_MIN)
49 *converted = (int)sli;
53 static int char_left_gc(const char *buffer, size_t len)
57 for (i = 0; i < len; i++) {
58 if (buffer[i] == ' ' ||
68 static int char_right_gc(const char *buffer, size_t len)
72 for (i = len - 1; i >= 0; i--) {
73 if (buffer[i] == ' ' ||
85 static char *trim_whitespace_in_place(char *buffer)
87 buffer += char_left_gc(buffer, strlen(buffer));
88 buffer[char_right_gc(buffer, strlen(buffer))] = '\0';
92 static pid_t get_pid_from_fdinfo_file(int pidfd, const char *key, size_t keylen)
101 snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", pidfd);
103 f = fopen(path, "re");
107 while (getline(&line, &n, f) != -1) {
110 if (strncmp(line, key, keylen))
113 numstr = trim_whitespace_in_place(line + 4);
114 ret = safe_int(numstr, &result);
127 int main(int argc, char **argv)
129 int pidfd = -1, ret = 1;
134 pidfd = sys_pidfd_open(-1, 0);
137 "%s - succeeded to open pidfd for invalid pid -1\n",
141 ksft_test_result_pass("do not allow invalid pid test: passed\n");
143 pidfd = sys_pidfd_open(getpid(), 1);
146 "%s - succeeded to open pidfd with invalid flag value specified\n",
150 ksft_test_result_pass("do not allow invalid flag test: passed\n");
152 pidfd = sys_pidfd_open(getpid(), 0);
154 ksft_print_msg("%s - failed to open pidfd\n", strerror(errno));
157 ksft_test_result_pass("open a new pidfd test: passed\n");
159 pid = get_pid_from_fdinfo_file(pidfd, "Pid:", sizeof("Pid:") - 1);
160 ksft_print_msg("pidfd %d refers to process with pid %d\n", pidfd, pid);
168 return !ret ? ksft_exit_pass() : ksft_exit_fail();