1 // SPDX-License-Identifier: GPL-2.0
15 #include <sys/syscall.h>
16 #include <sys/types.h>
21 #define CLONE_PIDFD 0x00001000
24 static int do_child(void *args)
26 printf("%d\n", getpid());
30 static pid_t pidfd_clone(int flags, int *pidfd)
32 size_t stack_size = 1024;
33 char *stack[1024] = { 0 };
36 return __clone2(do_child, stack, stack_size, flags | SIGCHLD, NULL, pidfd);
38 return clone(do_child, stack + stack_size, flags | SIGCHLD, NULL, pidfd);
42 static inline int sys_pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
45 return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags);
48 static int pidfd_metadata_fd(pid_t pid, int pidfd)
53 snprintf(path, sizeof(path), "/proc/%d", pid);
54 procfd = open(path, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
56 warn("Failed to open %s\n", path);
61 * Verify that the pid has not been recycled and our /proc/<pid> handle
64 ret = sys_pidfd_send_signal(pidfd, 0, NULL, 0);
68 /* Process exists, just not allowed to signal it. */
71 warn("Failed to signal process\n");
80 int main(int argc, char *argv[])
82 int pidfd = 0, ret = EXIT_FAILURE;
83 char buf[4096] = { 0 };
88 pid = pidfd_clone(CLONE_PIDFD, &pidfd);
92 procfd = pidfd_metadata_fd(pid, pidfd);
97 statusfd = openat(procfd, "status", O_RDONLY | O_CLOEXEC);
102 bytes = read(statusfd, buf, sizeof(buf));
104 bytes = write(STDOUT_FILENO, buf, bytes);