test_session.c 2.8 KB

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