1 // SPDX-License-Identifier: GPL-2.0
15 #include <sys/syscall.h>
16 #include <sys/types.h>
21 #define CLONE_PIDFD 0x00001000
24 #ifndef __NR_pidfd_send_signal
25 #define __NR_pidfd_send_signal -1
28 static int do_child(void *args)
30 printf("%d\n", getpid());
34 static pid_t pidfd_clone(int flags, int *pidfd)
36 size_t stack_size = 1024;
37 char *stack[1024] = { 0 };
40 return __clone2(do_child, stack, stack_size, flags | SIGCHLD, NULL, pidfd);
42 return clone(do_child, stack + stack_size, flags | SIGCHLD, NULL, pidfd);
46 static inline int sys_pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
49 return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags);
52 static int pidfd_metadata_fd(pid_t pid, int pidfd)
57 snprintf(path, sizeof(path), "/proc/%d", pid);
58 procfd = open(path, O_DIRECTORY | O_RDONLY | O_CLOEXEC);
60 warn("Failed to open %s\n", path);
65 * Verify that the pid has not been recycled and our /proc/<pid> handle
68 ret = sys_pidfd_send_signal(pidfd, 0, NULL, 0);
72 /* Process exists, just not allowed to signal it. */
75 warn("Failed to signal process\n");
84 int main(int argc, char *argv[])
86 int pidfd = -1, ret = EXIT_FAILURE;
87 char buf[4096] = { 0 };
92 pid = pidfd_clone(CLONE_PIDFD, &pidfd);
94 err(ret, "CLONE_PIDFD");
96 warnx("CLONE_PIDFD is not supported by the kernel");
100 procfd = pidfd_metadata_fd(pid, pidfd);
105 statusfd = openat(procfd, "status", O_RDONLY | O_CLOEXEC);
110 bytes = read(statusfd, buf, sizeof(buf));
112 bytes = write(STDOUT_FILENO, buf, bytes);