25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

62 satır
1.9KB

  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <csignal>
  11. #include <iostream>
  12. #include "Util/logger.h"
  13. #include "Poller/EventPoller.h"
  14. #include "Poller/Pipe.h"
  15. #include "Util/util.h"
  16. using namespace std;
  17. using namespace toolkit;
  18. int main() {
  19. //设置日志
  20. Logger::Instance().add(std::make_shared<ConsoleChannel>());
  21. #if defined(_WIN32)
  22. ErrorL << "该测试程序不能再windows下运行,因为我不会windows下的多进程编程,但是管道模块是可以在windows下正常工作的。" << endl;
  23. #else
  24. //获取父进程的PID
  25. auto parentPid = getpid();
  26. InfoL << "parent pid:" << parentPid << endl;
  27. //定义一个管道,lambada类型的参数是管道收到数据的回调
  28. Pipe pipe([](int size,const char *buf) {
  29. //该管道有数据可读了
  30. InfoL << getpid() << " recv:" << buf;
  31. });
  32. //创建子进程
  33. auto pid = fork();
  34. if (pid == 0) {
  35. //子进程
  36. int i = 10;
  37. while (i--) {
  38. //在子进程每隔一秒把数据写入管道,共计发送10次
  39. sleep(1);
  40. string msg = StrPrinter << "message " << i << " form subprocess:" << getpid();
  41. DebugL << "子进程发送:" << msg << endl;
  42. pipe.send(msg.data(), msg.size());
  43. }
  44. DebugL << "子进程退出" << endl;
  45. } else {
  46. //父进程设置退出信号处理函数
  47. static semaphore sem;
  48. signal(SIGINT, [](int) { sem.post(); });// 设置退出信号
  49. sem.wait();
  50. InfoL << "父进程退出" << endl;
  51. }
  52. #endif // defined(_WIN32)
  53. return 0;
  54. }