main.c 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.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", \
  12. fail_msg, \
  13. (unsigned long)(right), \
  14. (unsigned long)(left)); \
  15. } \
  16. } while (0)
  17. #define TEST_CONDITION(condition, success_msg, fail_msg) \
  18. do { \
  19. if (condition) { \
  20. printf("[PASS] %s\n", success_msg); \
  21. } else { \
  22. printf("[FAIL] %s\n", fail_msg); \
  23. } \
  24. } while (0)
  25. // 打印进程信息
  26. void print_ids(const char *name) {
  27. printf("[%s] PID=%d, PPID=%d, PGID=%d, SID=%d\n",
  28. name,
  29. getpid(),
  30. getppid(),
  31. getpgid(0), // 获取当前进程的 PGID
  32. getsid(0)); // 获取当前进程的 SID
  33. }
  34. int main() {
  35. printf("===== 测试 getsid =====\n");
  36. print_ids("Parent");
  37. pid_t child = fork();
  38. if (child == 0) {
  39. // 子进程
  40. printf("\n[Child] 子进程启动...\n");
  41. print_ids("Child (before setsid)");
  42. // 创建新会话
  43. pid_t newsid = setsid();
  44. if (newsid == -1) {
  45. perror("setsid failed");
  46. exit(EXIT_FAILURE);
  47. }
  48. printf("[Child] 创建新会话成功,新 SID = %d\n", newsid);
  49. print_ids("Child (after setsid)");
  50. TEST_ASSERT(newsid, getpid(), "New sid equal to child pid", "failed to set new sid");
  51. TEST_ASSERT(getsid(0), getpid(), "Child sid equal to child pid", "failed to set new sid");
  52. TEST_ASSERT(getpgid(0), getpid(), "Child pgid equal to child pid", "failed to set new sid");
  53. exit(EXIT_SUCCESS);
  54. } else if (child > 0) {
  55. // 父进程
  56. waitpid(child, NULL, 0); // 等待子进程结束
  57. printf("\n[Parent] 子进程结束后...\n");
  58. print_ids("Parent");
  59. TEST_CONDITION(getsid(0)!=child, "Parent sid unchanged", "Parent sid changed");
  60. TEST_CONDITION(getpgid(0)!=child, "Parent pgid unchanged", "Parent pgid changed");
  61. } else {
  62. perror("fork failed");
  63. exit(EXIT_FAILURE);
  64. }
  65. return 0;
  66. }