1 #include <errno.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <unistd.h> 6 7 8 int 9 main() 10 { 11 pid_t parentPID = getpid(); 12 printf("parent pid: %d\n", parentPID); 13 printf("parent pgid: %d\n", getpgrp()); 14 15 pid_t childPID = fork(); 16 if (childPID < 0) { 17 fprintf(stderr, "fork() failed: %s\n", strerror(errno)); 18 exit(1); 19 } else if (childPID == 0) { 20 // child 21 childPID = getpid(); 22 printf("child pid: %d, pgid: %d\n", childPID, getpgrp()); 23 24 printf("child setpgid(0, 0)\n"); 25 if (setpgid(0, 0) < 0) { 26 fprintf(stderr, "child: first setpgid() failed: %s\n", strerror(errno)); 27 exit(1); 28 } 29 // printf("child setsid()\n"); 30 // if (setsid() < 0) { 31 // fprintf(stderr, "child: setsid() failed: %s\n", strerror(errno)); 32 // exit(1); 33 // } 34 35 printf("child pgid: %d\n", getpgrp()); 36 37 pid_t grandChildPID = fork(); 38 if (grandChildPID < 0) { 39 fprintf(stderr, "fork() 2 failed: %s\n", strerror(errno)); 40 exit(1); 41 } else if (grandChildPID == 0) { 42 // grand child 43 grandChildPID = getpid(); 44 printf("gchild pid: %d, pgid: %d\n", grandChildPID, getpgrp()); 45 sleep(2); 46 printf("gchild pid: %d, pgid: %d\n", grandChildPID, getpgrp()); 47 } else { 48 // child 49 sleep(1); 50 51 printf("child setpgid(0, %d)\n", parentPID); 52 if (setpgid(0, parentPID) < 0) { 53 // printf("child setpgid(0, 0)\n"); 54 // if (setpgid(0, 0) < 0) { 55 fprintf(stderr, "child: second setpgid() failed: %s\n", strerror(errno)); 56 exit(1); 57 } 58 59 printf("child pgid: %d\n", getpgrp()); 60 } 61 62 } else { 63 // parent 64 sleep(3); 65 } 66 67 return 0; 68 } 69