stdio.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * File : stdio.c
  3. * Brief : stdio for newlib
  4. *
  5. * This file is part of RT-Thread RTOS
  6. * COPYRIGHT (C) 2006 - 2017, RT-Thread Development Team
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * Change Logs:
  23. * Date Author Notes
  24. * 2017/10/15 bernard the first version
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <rtthread.h>
  29. #include "libc.h"
  30. #define STDIO_DEVICE_NAME_MAX 32
  31. int _EXFUN(fileno, (FILE *));
  32. static FILE* std_console = NULL;
  33. int libc_stdio_set_console(const char* device_name, int mode)
  34. {
  35. FILE *fp;
  36. char name[STDIO_DEVICE_NAME_MAX];
  37. char *file_mode;
  38. snprintf(name, sizeof(name) - 1, "/dev/%s", device_name);
  39. name[STDIO_DEVICE_NAME_MAX - 1] = '\0';
  40. if (mode == O_RDWR) file_mode = "r+";
  41. else if (mode == O_WRONLY) file_mode = "wb";
  42. else file_mode = "rb";
  43. fp = fopen(name, file_mode);
  44. if (fp)
  45. {
  46. setvbuf(fp, NULL, _IONBF, 0);
  47. if (std_console)
  48. {
  49. fclose(std_console);
  50. std_console = NULL;
  51. }
  52. std_console = fp;
  53. if (mode == O_RDWR)
  54. {
  55. _GLOBAL_REENT->_stdin = std_console;
  56. }
  57. else
  58. {
  59. _GLOBAL_REENT->_stdin = NULL;
  60. }
  61. if (mode == O_RDONLY)
  62. {
  63. _GLOBAL_REENT->_stdout = NULL;
  64. _GLOBAL_REENT->_stderr = NULL;
  65. }
  66. else
  67. {
  68. _GLOBAL_REENT->_stdout = std_console;
  69. _GLOBAL_REENT->_stderr = std_console;
  70. }
  71. _GLOBAL_REENT->__sdidinit = 1;
  72. }
  73. if (std_console) return fileno(std_console);
  74. return -1;
  75. }
  76. int libc_stdio_get_console(void) {
  77. if (std_console)
  78. return fileno(std_console);
  79. else
  80. return -1;
  81. }