1 | /** |
2 | * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | |
16 | * \author Dianzhang.Chen |
17 | * \date Feb 2021 |
18 | * \brief PortHelper definition |
19 | */ |
20 | |
21 | #pragma once |
22 | |
23 | #include <fstream> |
24 | #include <iostream> |
25 | #include <string> |
26 | |
27 | namespace proxima { |
28 | namespace be { |
29 | |
30 | class PortHelper { |
31 | public: |
32 | static void GetPort(int *port, int *pid) { |
33 | *pid = getpid(); |
34 | static std::string cmd = |
35 | "export PORT=$(python -c 'import socket; s=socket.socket(); " |
36 | "s.bind((\"\", 0)); print(s.getsockname()[1]); s.close()')" |
37 | "&& echo ${PORT} > %s.txt" ; |
38 | char cmd_buf[1024]; |
39 | snprintf(cmd_buf, 1024, cmd.c_str(), std::to_string(*pid).c_str()); |
40 | system(cmd_buf); |
41 | char filename_buf[1024]; |
42 | snprintf(filename_buf, 1024, "%s.txt" , std::to_string(*pid).c_str()); |
43 | std::string filename = std::string(filename_buf); |
44 | std::ifstream infile(filename); |
45 | std::string port_str; |
46 | std::getline(infile, port_str); |
47 | *port = std::stoi(port_str); |
48 | } |
49 | |
50 | static void RemovePortFile(int pid) { |
51 | static std::string cmd = "rm %s.txt" ; |
52 | char cmd_buf[1024]; |
53 | snprintf(cmd_buf, 1024, cmd.c_str(), std::to_string(pid).c_str()); |
54 | std::cout << "Execute: " << std::string(cmd_buf) << std::endl; |
55 | system(cmd_buf); |
56 | } |
57 | }; |
58 | |
59 | } // namespace be |
60 | } // end namespace proxima |
61 | |