cmd_test.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "cmd_test.h"
  2. #include <math.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <time.h>
  7. #include <unistd.h>
  8. #define buf_SIZE 256 // 定义消息的最大长度
  9. int shell_pipe_test(int argc, char **argv)
  10. {
  11. int fd[2], i, n;
  12. pid_t pid;
  13. int ret = pipe(fd); // 创建一个管道
  14. if (ret < 0)
  15. {
  16. printf("pipe error");
  17. exit(1);
  18. }
  19. pid = fork(); // 创建一个子进程
  20. if (pid < 0)
  21. {
  22. printf("fork error");
  23. exit(1);
  24. }
  25. if (pid == 0)
  26. { // 子进程
  27. close(fd[1]); // 关闭管道的写端
  28. for (i = 0; i < 3; i++)
  29. { // 循环三次
  30. char buf[buf_SIZE] = {0};
  31. n = read(fd[0], buf, buf_SIZE); // 从管道的读端读取一条消息
  32. if (n > 0)
  33. {
  34. printf("Child process received message: %s\n", buf); // 打印收到的消息
  35. if (strcmp(buf, "quit") == 0)
  36. { // 如果收到的消息是"quit"
  37. printf("Child process exits.\n"); // 打印退出信息
  38. break; // 跳出循环
  39. }
  40. else
  41. { // 如果收到的消息不是"quit"
  42. printf("Child process is doing something...\n"); // 模拟子进程做一些操作
  43. usleep(100);
  44. }
  45. }
  46. }
  47. close(fd[0]); // 关闭管道的读端
  48. exit(0);
  49. }
  50. else
  51. { // 父进程
  52. close(fd[0]); // 关闭管道的读端
  53. for (i = 0; i < 3; i++)
  54. { // 循环三次
  55. char *msg = "hello world";
  56. if (i == 1)
  57. {
  58. msg = "how are you";
  59. usleep(1000);
  60. }
  61. if (i == 2)
  62. {
  63. msg = "quit";
  64. usleep(1000);
  65. }
  66. n = strlen(msg);
  67. printf("Parent process send:%s\n", msg);
  68. write(fd[1], msg, n); // 向管道的写端写入一条消息
  69. if (strcmp(msg, "quit") == 0)
  70. { // 如果发送的消息是"quit"
  71. printf("Parent process exits.\n"); // 打印退出信息
  72. break; // 跳出循环
  73. }
  74. }
  75. close(fd[1]); // 关闭管道的写端
  76. wait(NULL); // 等待子进程结束
  77. }
  78. return 0;
  79. }