1 #include <errno.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <stdio.h> 5 #include <unistd.h> 6 #include <sys/types.h> 7 #include <sys/wait.h> 8 9 #ifdef __FreeBSD__ 10 #include <sys/procdesc.h> 11 #endif 12 13 #ifdef __linux__ 14 #include <sys/syscall.h> 15 int pdfork(int *fd, int flags) { 16 return syscall(__NR_pdfork, fd, flags); 17 } 18 #endif 19 20 int main() { 21 int procfd; 22 int rc = pdfork(&procfd, 0); 23 if (rc < 0) { 24 fprintf(stderr, "pdfork() failed rc=%d errno=%d %s\n", rc, errno, strerror(errno)); 25 exit(1); 26 } 27 if (rc == 0) { // Child process 28 sleep(1); 29 exit(123); 30 } 31 fprintf(stderr, "pdfork()ed child pid=%ld procfd=%d\n", (long)rc, procfd); 32 sleep(2); // Allow child to complete 33 pid_t child = waitpid(-1, &rc, WNOHANG); 34 if (child == 0) { 35 fprintf(stderr, "waitpid(): no completed child found\n"); 36 } else if (child < 0) { 37 fprintf(stderr, "waitpid(): failed errno=%d %s\n", errno, strerror(errno)); 38 } else { 39 fprintf(stderr, "waitpid(): found completed child %ld\n", (long)child); 40 } 41 return 0; 42 } 43