MasterPTY.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "MasterPTY.h"
  2. #include "SlavePTY.h"
  3. #include "PTYMultiplexer.h"
  4. #include <Kernel/Process.h>
  5. #include <LibC/errno_numbers.h>
  6. #include <LibC/signal_numbers.h>
  7. MasterPTY::MasterPTY(unsigned index)
  8. : CharacterDevice(10, index)
  9. , m_slave(adopt(*new SlavePTY(*this, index)))
  10. , m_index(index)
  11. {
  12. set_uid(current->uid());
  13. set_gid(current->gid());
  14. }
  15. MasterPTY::~MasterPTY()
  16. {
  17. dbgprintf("~MasterPTY(%u)\n", m_index);
  18. PTYMultiplexer::the().notify_master_destroyed(Badge<MasterPTY>(), m_index);
  19. }
  20. String MasterPTY::pts_name() const
  21. {
  22. return String::format("/dev/pts/%u", m_index);
  23. }
  24. ssize_t MasterPTY::read(Process&, byte* buffer, size_t size)
  25. {
  26. if (!m_slave && m_buffer.is_empty())
  27. return 0;
  28. return m_buffer.read(buffer, size);
  29. }
  30. ssize_t MasterPTY::write(Process&, const byte* buffer, size_t size)
  31. {
  32. if (!m_slave)
  33. return -EIO;
  34. m_slave->on_master_write(buffer, size);
  35. return size;
  36. }
  37. bool MasterPTY::can_read(Process&) const
  38. {
  39. if (!m_slave)
  40. return true;
  41. return !m_buffer.is_empty();
  42. }
  43. bool MasterPTY::can_write(Process&) const
  44. {
  45. return true;
  46. }
  47. void MasterPTY::notify_slave_closed(Badge<SlavePTY>)
  48. {
  49. dbgprintf("MasterPTY(%u): slave closed, my retains: %u, slave retains: %u\n", m_index, retain_count(), m_slave->retain_count());
  50. // +1 retain for my MasterPTY::m_slave
  51. // +1 retain for FileDescriptor::m_device
  52. if (m_slave->retain_count() == 2)
  53. m_slave = nullptr;
  54. }
  55. ssize_t MasterPTY::on_slave_write(const byte* data, size_t size)
  56. {
  57. if (m_closed)
  58. return -EIO;
  59. m_buffer.write(data, size);
  60. return size;
  61. }
  62. bool MasterPTY::can_write_from_slave() const
  63. {
  64. if (m_closed)
  65. return true;
  66. return m_buffer.bytes_in_write_buffer() < 4096;
  67. }
  68. void MasterPTY::close()
  69. {
  70. if (retain_count() == 2) {
  71. InterruptDisabler disabler;
  72. // After the closing FileDescriptor dies, slave is the only thing keeping me alive.
  73. // From this point, let's consider ourselves closed.
  74. m_closed = true;
  75. m_slave->hang_up();
  76. }
  77. }