1 /* 2 * Copyright (c) 2018 Oticon A/S 3 * Copyright (c) 2023 Nordic Semiconductor ASA 4 * 5 * SPDX-License-Identifier: Apache-2.0 6 */ 7 8 #include <zephyr/init.h> 9 #include <zephyr/arch/posix/posix_trace.h> 10 #include <zephyr/sys/printk-hooks.h> 11 #include <zephyr/sys/libc-hooks.h> 12 13 #define _STDOUT_BUF_SIZE 256 14 static char stdout_buff[_STDOUT_BUF_SIZE]; 15 static int n_pend; /* Number of pending characters in buffer */ 16 print_char(int c)17static int print_char(int c) 18 { 19 int printnow = 0; 20 21 if ((c != '\n') && (c != '\r')) { 22 stdout_buff[n_pend++] = c; 23 stdout_buff[n_pend] = 0; 24 } else { 25 printnow = 1; 26 } 27 28 if (n_pend >= _STDOUT_BUF_SIZE - 1) { 29 printnow = 1; 30 } 31 32 if (printnow) { 33 posix_print_trace("%s\n", stdout_buff); 34 n_pend = 0; 35 stdout_buff[0] = 0; 36 } 37 return c; 38 } 39 40 /** 41 * Ensure that whatever was written thru printk is displayed now 42 */ posix_flush_stdout(void)43void posix_flush_stdout(void) 44 { 45 if (n_pend) { 46 stdout_buff[n_pend] = 0; 47 posix_print_trace("%s", stdout_buff); 48 n_pend = 0; 49 stdout_buff[0] = 0; 50 } 51 } 52 posix_arch_console_init(void)53static int posix_arch_console_init(void) 54 { 55 #ifdef CONFIG_PRINTK 56 __printk_hook_install(print_char); 57 #endif 58 #ifdef CONFIG_STDOUT_CONSOLE 59 __stdout_hook_install(print_char); 60 #endif 61 return 0; 62 } 63 64 SYS_INIT(posix_arch_console_init, PRE_KERNEL_1, 65 CONFIG_POSIX_ARCH_CONSOLE_INIT_PRIORITY); 66