1 //===-- TTYState.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Created by Greg Clayton on 3/26/07.
12 //===----------------------------------------------------------------------===//
17 #include <sys/signal.h>
19 TTYState::TTYState() :
32 TTYState::GetTTYState (int fd, bool saveProcessGroup)
34 if (fd >= 0 && ::isatty (fd))
37 m_tflags = fcntl (fd, F_GETFL, 0);
38 m_ttystateErr = tcgetattr (fd, &m_ttystate);
40 m_processGroup = tcgetpgrp (0);
51 return m_ttystateErr == 0;
55 TTYState::SetTTYState () const
61 result = fcntl (m_fd, F_SETFL, m_tflags);
64 result = tcsetattr (m_fd, TCSANOW, &m_ttystate);
66 if (ProcessGroupValid())
68 // Save the original signal handler.
69 void (*saved_sigttou_callback) (int) = NULL;
70 saved_sigttou_callback = (void (*)(int)) signal (SIGTTOU, SIG_IGN);
71 // Set the process group
72 result = tcsetpgrp (m_fd, m_processGroup);
73 // Restore the original signal handler.
74 signal (SIGTTOU, saved_sigttou_callback);
83 TTYStateSwitcher::TTYStateSwitcher() :
88 TTYStateSwitcher::~TTYStateSwitcher()
93 TTYStateSwitcher::GetState(uint32_t idx, int fd, bool saveProcessGroup)
95 if (ValidStateIndex(idx))
96 return m_ttystates[idx].GetTTYState(fd, saveProcessGroup);
101 TTYStateSwitcher::SetState(uint32_t idx) const
103 if (!ValidStateIndex(idx))
106 // See if we already are in this state?
107 if (ValidStateIndex(m_currentState) && (idx == m_currentState) && m_ttystates[idx].IsValid())
110 // Set the state to match the index passed in and only update the
111 // current state if there are no errors.
112 if (m_ttystates[idx].SetTTYState())
114 m_currentState = idx;
118 // We failed to set the state. The tty state was invalid or not