tty_ctty.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2023-11-30 Shell init ver.
  9. */
  10. #define DBG_TAG "lwp.ctty"
  11. #define DBG_LVL DBG_INFO
  12. #include <rtdbg.h>
  13. #define TTY_CONF_INCLUDE_CCHARS
  14. #include "tty_config.h"
  15. #include "tty_internal.h"
  16. #include "terminal.h"
  17. static int fops_open(struct dfs_file *file)
  18. {
  19. return -EINVAL;
  20. }
  21. static rt_err_t ctty_readlink(struct rt_device *dev, char *buf, int len)
  22. {
  23. int rc = -ENXIO;
  24. lwp_tty_t tp;
  25. rt_session_t sess;
  26. rt_processgroup_t pgrp;
  27. rt_lwp_t lwp;
  28. lwp = lwp_self();
  29. if (lwp)
  30. {
  31. pgrp = lwp->pgrp;
  32. if (pgrp)
  33. {
  34. sess = pgrp->session;
  35. if (sess)
  36. {
  37. tp = sess->ctty;
  38. if (tp)
  39. {
  40. tty_lock(tp);
  41. if (lwp->pgrp == pgrp && pgrp->session == sess && sess->ctty == tp)
  42. {
  43. rt_strncpy(buf, tp->parent.parent.name, len);
  44. rc = RT_EOK;
  45. }
  46. tty_unlock(tp);
  47. }
  48. }
  49. }
  50. }
  51. return rc;
  52. }
  53. static struct dfs_file_ops ctty_file_ops = {
  54. .open = fops_open,
  55. };
  56. /* character device for tty */
  57. #ifdef RT_USING_DEVICE_OPS
  58. const static struct rt_device_ops tty_dev_ops = {
  59. /* IO directly through device is not allowed */
  60. };
  61. #else
  62. #error Must enable RT_USING_DEVICE_OPS in Kconfig
  63. #endif
  64. rt_inline void device_setup(rt_device_t ctty)
  65. {
  66. ctty->type = RT_Device_Class_Char;
  67. #ifdef RT_USING_DEVICE_OPS
  68. ctty->ops = &tty_dev_ops;
  69. #else
  70. #error Must enable RT_USING_DEVICE_OPS in Kconfig
  71. #endif
  72. }
  73. /* register device to DFS */
  74. static int lwp_ctty_register(rt_device_t ctty)
  75. {
  76. rt_err_t rc = -RT_ENOMEM;
  77. const char *tty_name = "tty";
  78. device_setup(ctty);
  79. rc = rt_device_register(ctty, tty_name, RT_DEVICE_FLAG_DYNAMIC);
  80. if (rc == RT_EOK)
  81. {
  82. ctty->readlink = &ctty_readlink;
  83. ctty->fops = &ctty_file_ops;
  84. }
  85. return rc;
  86. }
  87. static struct rt_device ctty;
  88. static int lwp_ctty_init(void)
  89. {
  90. return lwp_ctty_register(&ctty);
  91. }
  92. INIT_DEVICE_EXPORT(lwp_ctty_init);