Debian Codegraph @

CodeLite/UnixProcess.h

raw
1 #ifndef UNIX_PROCESS_H
2 #define UNIX_PROCESS_H
3 #if defined(__WXGTK__) || defined(__WXOSX__)
4 #include <exception>
5 #include <functional>
6 #include <iostream>
7 #include <memory>
8 #include <sys/wait.h>
9 #include <thread>
10 #include <unistd.h>
11 #include <wx/thread.h>
12 #include <wx/msgqueue.h>
13 #include <atomic>
14 #include <wx/event.h>
15
16 // Wrapping pipe in a class makes sure they are closed when we leave scope
17 #define CLOSE_FD(fd) \
18 if(fd != wxNOT_FOUND) { \
19 ::close(fd); \
20 fd = wxNOT_FOUND; \
21 }
22
23 class CPipe
24 {
25 private:
26 int m_readFd = wxNOT_FOUND;
27 int m_writeFd = wxNOT_FOUND;
28
29 public:
30 const inline int GetReadFd() const { return m_readFd; }
31 const inline int GetWriteFd() const { return m_writeFd; }
32 CPipe() {}
33 void Close()
34 {
35 CLOSE_FD(m_readFd);
36 CLOSE_FD(m_writeFd);
37 }
38 ~CPipe() { Close(); }
39 bool Open()
40 {
41 int fd[2];
42 if(pipe(fd) == 0) {
43 m_readFd = fd[0];
44 m_writeFd = fd[1];
45 return true;
46 }
47 return false;
48 }
49 void CloseWriteFd() { CLOSE_FD(m_writeFd); }
50 void CloseReadFd() { CLOSE_FD(m_readFd); }
51 };
52
53 class UnixProcess
54 {
55 private:
56 CPipe m_childStdin;
57 CPipe m_childStdout;
58 CPipe m_childStderr;
59 std::thread* m_writerThread = nullptr;
60 std::thread* m_readerThread = nullptr;
61 wxMessageQueue<std::string> m_outgoingQueue;
62 std::atomic_bool m_goingDown;
63 wxEvtHandler* m_owner = nullptr;
64
65 protected:
66 // sync operations
67 static bool ReadAll(int fd, std::string& content, int timeoutMilliseconds);
68 static bool Write(int fd, const std::string& message, std::atomic_bool& shutdown);
69
70 void StartWriterThread();
71 void StartReaderThread();
72
73 public:
74 int child_pid = -1;
75
76 UnixProcess(wxEvtHandler* owner, const wxArrayString& args);
77 ~UnixProcess();
78
79 // wait for process termination
80 int Wait();
81
82 // Async calls with callbacks
83 void Write(const std::string& message);
84
85 // stop the running process
86 void Stop();
87
88 /**
89 * @brief stop sending events from the process
90 */
91 void Detach();
92 };
93 #endif // defined(__WXGTK__)||defined(__WXOSX__)
94 #endif // UNIX_PROCESS_H