test_processgroup.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <unistd.h>
  6. #define TEST_ASSERT(left, right, success_msg, fail_msg) \
  7. do { \
  8. if ((left) == (right)) { \
  9. printf("[PASS] %s\n", success_msg); \
  10. } else { \
  11. printf("[FAIL] %s: Expected 0x%lx, but got 0x%lx\n", fail_msg, \
  12. (unsigned long)(right), (unsigned long)(left)); \
  13. } \
  14. } while (0)
  15. // 打印进程信息
  16. void print_ids(const char *name) {
  17. printf("[%s] PID=%d, PPID=%d, PGID=%d, SID=%d\n", name, getpid(), getppid(),
  18. getpgid(0), // 获取当前进程的 PGID
  19. getsid(0)); // 获取当前进程的 SID
  20. }
  21. int main() {
  22. printf("===== 测试进程组 =====\n");
  23. print_ids("Parent");
  24. // 创建第一个子进程
  25. pid_t child1 = fork();
  26. if (child1 == 0) {
  27. // 子进程1:设置自己的进程组
  28. printf("\n[Child1] 子进程启动...\n");
  29. print_ids("Child1 (before setpgid)");
  30. if (setpgid(0, 0) == -1) { // 将自己的 PGID 设置为自己的 PID
  31. perror("setpgid failed");
  32. exit(EXIT_FAILURE);
  33. }
  34. print_ids("Child1 (after setpgid)");
  35. // Assert: PGID 应该等于 PID
  36. // assert(getpgid(0) == getpid());
  37. TEST_ASSERT(getpgid(0), getpid(),
  38. "Successfully set child1 as processgroup leader",
  39. "Child1 PGID check failed");
  40. sleep(2); // 保持运行,便于观察
  41. exit(EXIT_SUCCESS);
  42. }
  43. // 创建第二个子进程
  44. pid_t child2 = fork();
  45. if (child2 == 0) {
  46. // 子进程2:加入第一个子进程的进程组
  47. printf("\n[Child2] 子进程启动...\n");
  48. print_ids("Child2 (before setpgid)");
  49. if (setpgid(0, child1) == -1) { // 将自己的 PGID 设置为 child1 的 PID
  50. perror("setpgid failed");
  51. exit(EXIT_FAILURE);
  52. }
  53. print_ids("Child2 (after setpgid)");
  54. // Assert: PGID 应该等于 child1 的 PID
  55. // assert(getpgid(0) == child1);
  56. TEST_ASSERT(getpgid(0), child1, "Child2 PGID is equal to Child1",
  57. "Child2 PGID check failed");
  58. sleep(2); // 保持运行,便于观察
  59. exit(EXIT_SUCCESS);
  60. }
  61. // 父进程:等待子进程结束
  62. waitpid(child1, NULL, 0);
  63. waitpid(child2, NULL, 0);
  64. printf("\n[Parent] 所有子进程结束后...\n");
  65. print_ids("Parent");
  66. return 0;
  67. }