-
Notifications
You must be signed in to change notification settings - Fork 598
/
Copy pathtest_pipe.cpp
69 lines (62 loc) · 2.55 KB
/
test_pipe.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
*
* This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
*
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
*/
#include <csignal>
#include <iostream>
#include "Util/logger.h"
#include "Poller/EventPoller.h"
#include "Poller/Pipe.h"
#include "Util/util.h"
using namespace std;
using namespace toolkit;
int main() {
//设置日志 [AUTO-TRANSLATED:50372045]
// Set up logging
Logger::Instance().add(std::make_shared<ConsoleChannel>());
#if defined(_WIN32)
ErrorL << "该测试程序不能再windows下运行,因为我不会windows下的多进程编程,但是管道模块是可以在windows下正常工作的。" << endl;
#else
//获取父进程的PID [AUTO-TRANSLATED:0a35f39a]
// Get the parent process's PID
auto parentPid = getpid();
InfoL << "parent pid:" << parentPid << endl;
//定义一个管道,lambada类型的参数是管道收到数据的回调 [AUTO-TRANSLATED:d5eeb28a]
// Define a pipe, with a lambda type parameter as the callback for when data is received
Pipe pipe([](int size,const char *buf) {
//该管道有数据可读了 [AUTO-TRANSLATED:e542256f]
// The pipe has data available for reading
InfoL << getpid() << " recv:" << buf;
});
//创建子进程 [AUTO-TRANSLATED:8d5746fc]
// Create a child process
auto pid = fork();
if (pid == 0) {
//子进程 [AUTO-TRANSLATED:3f793797]
// Child process
int i = 10;
while (i--) {
//在子进程每隔一秒把数据写入管道,共计发送10次 [AUTO-TRANSLATED:5a340f4b]
// In the child process, write data to the pipe every second, for a total of 10 times
sleep(1);
string msg = StrPrinter << "message " << i << " form subprocess:" << getpid();
DebugL << "子进程发送:" << msg << endl;
pipe.send(msg.data(), msg.size());
}
DebugL << "子进程退出" << endl;
} else {
//父进程设置退出信号处理函数 [AUTO-TRANSLATED:b2a0b432]
// Parent process sets up exit signal handling function
static semaphore sem;
signal(SIGINT, [](int) { sem.post(); });// 设置退出信号
sem.wait();
InfoL << "父进程退出" << endl;
}
#endif // defined(_WIN32)
return 0;
}