1 //===-- PseudoTerminal.h ----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Created by Greg Clayton on 1/8/08.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef __PseudoTerminal_h__
15 #define __PseudoTerminal_h__
16 
17 #include <fcntl.h>
18 #include <string>
19 #include <termios.h>
20 
21 class PseudoTerminal {
22 public:
23   enum { invalid_fd = -1, invalid_pid = -1 };
24 
25   enum Error {
26     success = 0,
27     err_posix_openpt_failed = -2,
28     err_grantpt_failed = -3,
29     err_unlockpt_failed = -4,
30     err_ptsname_failed = -5,
31     err_open_slave_failed = -6,
32     err_fork_failed = -7,
33     err_setsid_failed = -8,
34     err_failed_to_acquire_controlling_terminal = -9,
35     err_dup2_failed_on_stdin = -10,
36     err_dup2_failed_on_stdout = -11,
37     err_dup2_failed_on_stderr = -12
38   };
39   //------------------------------------------------------------------
40   // Constructors and Destructors
41   //------------------------------------------------------------------
42   PseudoTerminal();
43   ~PseudoTerminal();
44 
45   void CloseMaster();
46   void CloseSlave();
47   Error OpenFirstAvailableMaster(int oflag);
48   Error OpenSlave(int oflag);
49   int MasterFD() const { return m_master_fd; }
50   int SlaveFD() const { return m_slave_fd; }
51   int ReleaseMasterFD() {
52     // Release ownership of the master pseudo terminal file
53     // descriptor without closing it. (the destructor for this
54     // class will close it otherwise!)
55     int fd = m_master_fd;
56     m_master_fd = invalid_fd;
57     return fd;
58   }
59   int ReleaseSlaveFD() {
60     // Release ownership of the slave pseudo terminal file
61     // descriptor without closing it (the destructor for this
62     // class will close it otherwise!)
63     int fd = m_slave_fd;
64     m_slave_fd = invalid_fd;
65     return fd;
66   }
67 
68   const char *SlaveName() const;
69 
70   pid_t Fork(Error &error);
71 
72 protected:
73   //------------------------------------------------------------------
74   // Classes that inherit from PseudoTerminal can see and modify these
75   //------------------------------------------------------------------
76   int m_master_fd;
77   int m_slave_fd;
78 
79 private:
80   //------------------------------------------------------------------
81   // Outlaw copy and assignment constructors
82   //------------------------------------------------------------------
83   PseudoTerminal(const PseudoTerminal &rhs);
84   PseudoTerminal &operator=(const PseudoTerminal &rhs);
85 };
86 
87 #endif // #ifndef __PseudoTerminal_h__
88