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 int safe_int(const char *numstr, int *converted)
31 sli = strtol(numstr, &err, 0);
32 if (errno == ERANGE && (sli == LONG_MAX || sli == LONG_MIN))
35 if (errno != 0 && sli == 0)
38 if (err == numstr || *err != '\0')
41 if (sli > INT_MAX || sli < INT_MIN)
44 *converted = (int)sli;
48 static int char_left_gc(const char *buffer, size_t len)
52 for (i = 0; i < len; i++) {
53 if (buffer[i] == ' ' ||
63 static int char_right_gc(const char *buffer, size_t len)
67 for (i = len - 1; i >= 0; i--) {
68 if (buffer[i] == ' ' ||
80 static char *trim_whitespace_in_place(char *buffer)
82 buffer += char_left_gc(buffer, strlen(buffer));
83 buffer[char_right_gc(buffer, strlen(buffer))] = '\0';
87 static pid_t get_pid_from_fdinfo_file(int pidfd, const char *key, size_t keylen)
96 snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", pidfd);
98 f = fopen(path, "re");
102 while (getline(&line, &n, f) != -1) {
105 if (strncmp(line, key, keylen))
108 numstr = trim_whitespace_in_place(line + 4);
109 ret = safe_int(numstr, &result);
122 int main(int argc, char **argv)
124 int pidfd = -1, ret = 1;
129 pidfd = sys_pidfd_open(-1, 0);
132 "%s - succeeded to open pidfd for invalid pid -1\n",
136 ksft_test_result_pass("do not allow invalid pid test: passed\n");
138 pidfd = sys_pidfd_open(getpid(), 1);
141 "%s - succeeded to open pidfd with invalid flag value specified\n",
145 ksft_test_result_pass("do not allow invalid flag test: passed\n");
147 pidfd = sys_pidfd_open(getpid(), 0);
149 ksft_print_msg("%s - failed to open pidfd\n", strerror(errno));
152 ksft_test_result_pass("open a new pidfd test: passed\n");
154 pid = get_pid_from_fdinfo_file(pidfd, "Pid:", sizeof("Pid:") - 1);
155 ksft_print_msg("pidfd %d refers to process with pid %d\n", pidfd, pid);
163 return !ret ? ksft_exit_pass() : ksft_exit_fail();