1 /* 2 +----------------------------------------------------------------------+ 3 | Swoole | 4 +----------------------------------------------------------------------+ 5 | This source file is subject to version 2.0 of the Apache license, | 6 | that is bundled with this package in the file LICENSE, and is | 7 | available through the world-wide-web at the following url: | 8 | http://www.apache.org/licenses/LICENSE-2.0.html | 9 | If you did not receive a copy of the Apache2.0 license and are unable| 10 | to obtain it through the world-wide-web, please send a note to | 11 | license@swoole.com so we can mail you a copy immediately. | 12 +----------------------------------------------------------------------+ 13 | Author: Tianfeng Han <mikan.tenny@gmail.com> | 14 | Twosee <twose@qq.com> | 15 +----------------------------------------------------------------------+ 16 */ 17 18 #pragma once 19 20 #include "swoole.h" 21 #include "swoole_socket.h" 22 23 enum swPipe_close_which { 24 SW_PIPE_CLOSE_MASTER = 1, 25 SW_PIPE_CLOSE_WORKER = 2, 26 SW_PIPE_CLOSE_READ = 3, 27 SW_PIPE_CLOSE_WRITE = 4, 28 SW_PIPE_CLOSE_BOTH = 0, 29 }; 30 31 namespace swoole { 32 class SocketPair { 33 protected: 34 bool blocking; 35 double timeout; 36 37 /** 38 * master : socks[1] 39 * worker : socks[0] 40 */ 41 int socks[2]; 42 43 network::Socket *master_socket = nullptr; 44 network::Socket *worker_socket = nullptr; 45 46 bool init_socket(int master_fd, int worker_fd); 47 48 public: SocketPair(bool _blocking)49 SocketPair(bool _blocking) { 50 blocking = _blocking; 51 timeout = network::Socket::default_read_timeout; 52 } 53 ~SocketPair(); 54 55 ssize_t read(void *_buf, size_t length); 56 ssize_t write(const void *_buf, size_t length); 57 bool close(int which = 0); 58 get_socket(bool _master)59 network::Socket *get_socket(bool _master) { 60 return _master ? master_socket : worker_socket; 61 } 62 ready()63 bool ready() { 64 return master_socket != nullptr && worker_socket != nullptr; 65 } 66 set_timeout(double _timeout)67 void set_timeout(double _timeout) { 68 timeout = _timeout; 69 } 70 set_blocking(bool blocking)71 void set_blocking(bool blocking) { 72 if (blocking) { 73 worker_socket->set_block(); 74 master_socket->set_block(); 75 } else { 76 worker_socket->set_nonblock(); 77 master_socket->set_nonblock(); 78 } 79 } 80 }; 81 82 class Pipe : public SocketPair { 83 public: 84 Pipe(bool blocking); 85 }; 86 87 class UnixSocket : public SocketPair { 88 int protocol_; 89 public: 90 UnixSocket(bool blocking, int _protocol); 91 bool set_buffer_size(size_t _size); 92 }; 93 94 } // namespace swoole 95