ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
main.c File Reference

ascii-chat Unified Binary - Mode Dispatcher and Entry Point More...

Go to the source code of this file.

Data Structures

struct  mode_descriptor_t
 Metadata for a mode. More...

Macros

#define MAIN_LOG_OUT_BUFFER_SIZE   64
#define MAIN_JSON_FILENAME_BUFFER_SIZE   256
#define APP_NAME   "ascii-chat"
#define VERSION   ASCII_CHAT_VERSION_FULL
#define REGISTER_GLOBAL_ATOMICS()

Typedefs

typedef int(* mode_entry_point_t) (void)

Functions

atomic_t g_should_exit ATOMIC_INIT_AUTO (g_should_exit)
bool should_exit (void)
void signal_exit (void)
void set_interrupt_callback (void(*cb)(void))
void setup_signal_handlers (void)
int main (int argc, char *argv[])

Detailed Description

ascii-chat Unified Binary - Mode Dispatcher and Entry Point

This file implements the main entry point for the unified ascii-chat binary, which provides server, client, mirror, and discovery service functionality in a single executable.

The dispatcher now delegates ALL option parsing (including mode detection and binary-level options) to options_init(), then simply dispatches to the appropriate mode-specific entry point based on the detected mode.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
2025
Version
3.0

Fix: CMAKE_OSX_SYSROOT properly configured for macOS builds WebRTC: Pass CMAKE_OSX_SYSROOT to subprocess for Threads discovery Test: Running macOS builds with WebRTC Threads fix

Definition in file main.c.

Macro Definition Documentation

◆ APP_NAME

#define APP_NAME   "ascii-chat"

Definition at line 116 of file main.c.

◆ MAIN_JSON_FILENAME_BUFFER_SIZE

#define MAIN_JSON_FILENAME_BUFFER_SIZE   256

Definition at line 4 of file main.c.

Referenced by main().

◆ MAIN_LOG_OUT_BUFFER_SIZE

#define MAIN_LOG_OUT_BUFFER_SIZE   64

Definition at line 3 of file main.c.

◆ REGISTER_GLOBAL_ATOMICS

#define REGISTER_GLOBAL_ATOMICS ( )
Value:
do { \
static bool _global_atomics_registered = false; \
if (!_global_atomics_registered) { \
NAMED_REGISTER_ATOMIC(&g_should_exit, "application_exit_flag", NULL); \
_global_atomics_registered = true; \
} \
} while (0)
atomic_t g_should_exit
Global application exit flag (shared across all modes).
Definition globals.c:31

Definition at line 227 of file main.c.

227#define REGISTER_GLOBAL_ATOMICS() \
228 do { \
229 static bool _global_atomics_registered = false; \
230 if (!_global_atomics_registered) { \
231 NAMED_REGISTER_ATOMIC(&g_should_exit, "application_exit_flag", NULL); \
232 _global_atomics_registered = true; \
233 } \
234 } while (0)

Referenced by main().

◆ VERSION

#define VERSION   ASCII_CHAT_VERSION_FULL

Definition at line 117 of file main.c.

Typedef Documentation

◆ mode_entry_point_t

typedef int(* mode_entry_point_t) (void)

Definition at line 434 of file main.c.

Function Documentation

◆ ATOMIC_INIT_AUTO()

atomic_t g_should_exit ATOMIC_INIT_AUTO ( g_should_exit )

Global flag indicating application should exit (used by all modes)

References g_should_exit.

◆ main()

int main ( int argc,
char * argv[] )

Definition at line 543 of file main.c.

543 {
544 // Configure the console before --help or any early option error can emit
545 // Unicode text.
546 terminal_enable_ansi();
547 if (process_utf8_arguments(&argc, &argv) != ASCIICHAT_OK) {
548 fprintf(stderr, "Failed to convert command-line arguments to UTF-8\n");
549 return 1;
550 }
551 // Set global argc/argv for early argv inspection (e.g., in terminal.c)
552 g_argc = argc;
553 g_argv = argv;
554
555 // Validate basic argument structure
556 if (argc < 1 || argv == NULL || argv[0] == NULL) {
557 return 1;
558 }
559
560 // Initialize the named registry for debugging (allows --debug-state to show registered synchronization primitives)
561#ifndef NDEBUG
562 named_init();
563 // Initialize atomic operations debug tracking
565 // Register global atomics with descriptive names for debug sync state monitoring
567 // Static atomics are now auto-registered via ATOMIC_INIT_AUTO macro at definition time
568 // Register all packet types from the packet_type_t enum
570#endif
571
572 // Register the main thread IMMEDIATELY after named_init() to ensure it's available for all subsequent allocations
573#ifndef NDEBUG
574#ifdef _WIN32
575 NAMED_REGISTER_THREAD(GetCurrentThread(), "main", NULL);
576#else
577 NAMED_REGISTER_THREAD((platform_thread_t)thread_self(), "main", NULL);
578#endif
579 // Also save main thread ID for memory reporting (must be very early)
581#endif
582
583 // Preserve arguments before environment consumers or option parsing retain pointers.
584 asciichat_errno_scope_t title_init_scope = errno_scope_begin();
585 static const platform_application_config_t platform_config = {
586 .name = "ascii-chat",
587 .config_directory = "ascii-chat",
588 .data_directory = "ascii-chat",
589 };
590 // Register the application identity before options_init() so libplatform's
591 // automatic config search uses %APPDATA%\\ascii-chat, not its generic default.
592 (void)platform_set_application_config(&platform_config);
593
594 asciichat_error_t title_init_result = platform_process_title_init(argc, &argv);
595 if (title_init_result == ASCIICHAT_OK)
596 ASSERT_NO_ERRNO_SINCE(title_init_scope);
598 g_argv = argv;
599 (void)atexit(platform_process_title_destroy);
600
601 // Determine the first positional argument without mistaking an option value for a mode.
603 bool mcp_mode_early = false;
604 for (int i = 1; i < argc; ++i) {
605 if (argv[i][0] != '-') {
606 mcp_mode_early = strcmp(argv[i], "mcp-server") == 0;
607 break;
608 }
609 if (!strchr(argv[i], '=')) {
610 const char *name = argv[i] + (argv[i][1] == '-' ? 2 : 1);
611 const registry_entry_t *descriptor = argv[i][1] == '-' ? registry_find_entry_by_name(name) : (name[0] && !name[1] ? registry_find_entry_by_short(name[0]) : NULL);
612 if (descriptor && descriptor->type != OPTION_TYPE_BOOL && descriptor->type != OPTION_TYPE_ACTION && i + 1 < argc) {
613 bool next_is_mode = strcmp(argv[i + 1], "discovery") == 0 || strcmp(argv[i + 1], "acds") == 0;
614 for (const mode_descriptor_t *mode = g_mode_table; mode->name; ++mode)
615 if (strcmp(argv[i + 1], mode->name) == 0)
616 next_is_mode = true;
617 if (!descriptor->optional_arg || (argv[i + 1][0] != '-' && !next_is_mode))
618 ++i;
619 }
620 }
621 }
622 bool help_requested = false;
623 for (int i = 1; i < argc; ++i)
624 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h"))
625 help_requested = true;
626 mcp_mode_early = mcp_mode_early && !help_requested;
627 // Reserve stdout even in HTTP mode: configuration can select the transport later.
628 if (mcp_mode_early && mcp_stdio_reserve() != ASCIICHAT_OK)
630 bool mcp_stdio = mcp_mode_early;
631
632 // Show cursor early in case a previous session crashed with it hidden.
633 if (!mcp_stdio && platform_isatty(STDOUT_FILENO))
634 (void)ui_controller_write(STDOUT_FILENO, "\033[?25h", 6);
635
636 // VERY FIRST: Scan for --color BEFORE ANY logging initialization
637 // This sets global flags that persist through cleanup, enabling --color to force colors
638 for (int i = 1; i < argc; i++) {
639 if (strcmp(argv[i], "--color") == 0 || strcmp(argv[i], "--color=true") == 0) {
640 g_color_flag_passed = true;
641 g_color_flag_value = true;
642 break;
643 } else if (strncmp(argv[i], "--color=", 8) == 0) {
644 g_color_flag_passed = true;
645 g_color_flag_value = strcmp(argv[i], "--color=false") != 0;
646 break;
647 }
648 }
649
650 // SECOND: Scan for --grep BEFORE ANY logging initialization
651 // This ensures ALL logs (including from shared_init) can be filtered
652 // Supports multiple --grep patterns (ORed together)
653 for (int i = 1; i < argc - 1; i++) {
654 if (strcmp(argv[i], "--grep") == 0) {
655 const char *pattern = argv[i + 1];
656 asciichat_error_t filter_result = grep_init(pattern);
657 if (filter_result != ASCIICHAT_OK) {
658 log_error("Invalid --grep pattern or invalid flags: \"%s\" - use /pattern/flags format (e.g., \"/query/ig\" or "
659 "\"/literal/F\")",
660 pattern);
661 return 1;
662 }
663 i++; // Skip the pattern argument
664 }
665 }
666
667 // Detect terminal capabilities early so colored help output works
668 // Logging will be initialized by asciichat_shared_init() before options_init()
670 terminal_capabilities_t caps;
673 platform_color_set_truecolor_supported(caps.color_level == TERM_COLOR_TRUECOLOR);
674
675 // Warn if Release build was built from dirty working tree
676#if ASCII_CHAT_GIT_IS_DIRTY
677 if (strcmp(ASCII_CHAT_BUILD_TYPE, "Release") == 0) {
678 // Dirty git warning will be logged after logging initialization
679 }
680#endif
681
682 // Load color scheme early (from config files and CLI) before logging initialization
683 // This allows logging to use the correct colors from the start
685
686 // Parse --color-scheme from argv early to set logging colors for help output
687 const char *colorscheme_name = "pastel"; // default
688 for (int i = 1; i < argc - 1; i++) {
689 if (strcmp(argv[i], "--color-scheme") == 0) {
690 colorscheme_name = argv[i + 1];
691 break;
692 }
693 }
694
695 // Load and apply colorscheme to logging BEFORE options_init() so help gets colors
696 color_scheme_t scheme;
697 if (colorscheme_load_builtin(colorscheme_name, &scheme) == ASCIICHAT_OK) {
698 log_set_color_scheme(&scheme);
699 } else {
700 // Fall back to default pastel if scheme not found
701 if (colorscheme_load_builtin("pastel", &scheme) == ASCIICHAT_OK) {
702 log_set_color_scheme(&scheme);
703 }
704 }
705
706 // Initialize logging colors so they're ready for help output
708
709 // Keep libplatform diagnostics on the same active ascii-chat palette.
710 platform_color_set_code(PLATFORM_COLOR_DEV, log_level_color(LOG_COLOR_DEV));
711 platform_color_set_code(PLATFORM_COLOR_DEBUG, log_level_color(LOG_COLOR_DEBUG));
712 platform_color_set_code(PLATFORM_COLOR_INFO, log_level_color(LOG_COLOR_INFO));
713 platform_color_set_code(PLATFORM_COLOR_WARN, log_level_color(LOG_COLOR_WARN));
714 platform_color_set_code(PLATFORM_COLOR_ERROR, log_level_color(LOG_COLOR_ERROR));
715 platform_color_set_code(PLATFORM_COLOR_FATAL, log_level_color(LOG_COLOR_FATAL));
716 platform_color_set_code(PLATFORM_COLOR_GREY, log_level_color(LOG_COLOR_GREY));
717 platform_color_set_code(PLATFORM_COLOR_RESET, log_level_color(LOG_COLOR_RESET));
718
719 // EARLY PARSE: Find the mode position (first positional argument)
720 // Binary-level options must appear BEFORE the mode
721 int mode_position = -1;
722 for (int i = 1; i < argc; i++) {
723 if (argv[i][0] != '-') {
724 // Found a positional argument - this is the mode or session string
725 mode_position = i;
726 break;
727 }
728
729 // Skip option and its argument if needed
730 // Check if this is an option that takes a required argument
731 const char *arg = argv[i];
732 const char *opt_name = arg;
733 if (arg[0] == '-') {
734 opt_name = arg + (arg[1] == '-' ? 2 : 1);
735 }
736
737 // Handle --option=value format
738 if (strchr(opt_name, '=')) {
739 continue; // Value is part of this arg, no need to skip next
740 }
741
742 const registry_entry_t *descriptor = arg[1] == '-' ? registry_find_entry_by_name(opt_name) : (opt_name[0] && !opt_name[1] ? registry_find_entry_by_short(opt_name[0]) : NULL);
743 if (descriptor && descriptor->type != OPTION_TYPE_BOOL && descriptor->type != OPTION_TYPE_ACTION && i + 1 < argc) {
744 bool next_is_mode = strcmp(argv[i + 1], "discovery") == 0 || strcmp(argv[i + 1], "acds") == 0;
745 for (const mode_descriptor_t *mode = g_mode_table; mode->name; ++mode)
746 if (strcmp(argv[i + 1], mode->name) == 0)
747 next_is_mode = true;
748 if (!descriptor->optional_arg || (argv[i + 1][0] != '-' && !next_is_mode))
749 ++i;
750 }
751 }
752
753 // EARLY PARSE: Determine mode from argv to know if this is client-like mode
754 // The first positional argument (after options) is the mode: client, server, mirror, discovery, acds
755 bool is_client_like_mode = false;
756 if (mode_position > 0) {
757 const char *first_arg = argv[mode_position];
758 if (strcmp(first_arg, "client") == 0 || strcmp(first_arg, "mirror") == 0 || strcmp(first_arg, "discovery") == 0) {
759 is_client_like_mode = true;
760 }
761 }
762
763 // EARLY PARSE: Extract log file from argv (--log-file or -L)
764 // Must appear BEFORE the mode
765 // Generate default log path based on build type and mode
766 char default_log_path[PATH_MAX];
767 asciichat_mode_t detected_mode = MODE_INVALID;
768 if (mode_position > 0) {
769 const char *mode_str = argv[mode_position];
770 // Convert mode string to enum
771 if (strcmp(mode_str, "server") == 0) {
772 detected_mode = MODE_SERVER;
773 } else if (strcmp(mode_str, "client") == 0) {
774 detected_mode = MODE_CLIENT;
775 } else if (strcmp(mode_str, "mirror") == 0) {
776 detected_mode = MODE_MIRROR;
777 } else if (strcmp(mode_str, "mcp-server") == 0) {
778 detected_mode = MODE_MCP_SERVER;
779 } else if (strcmp(mode_str, "api-server") == 0) {
780 detected_mode = MODE_API_SERVER;
781 } else if (strcmp(mode_str, "acds") == 0 || strcmp(mode_str, "discovery-service") == 0) {
782 detected_mode = MODE_DISCOVERY_SERVICE;
783 } else if (strcmp(mode_str, "discovery") == 0) {
784 detected_mode = MODE_DISCOVERY;
785 }
786 }
787 generate_default_log_path(detected_mode, default_log_path, sizeof(default_log_path));
788
789 const char *log_file = platform_systemd_is_managed() ? "/dev/null" : default_log_path;
790 int max_search = (mode_position > 0) ? mode_position : argc;
791 for (int i = 1; i < max_search - 1; i++) {
792 if ((strcmp(argv[i], "--log-file") == 0 || strcmp(argv[i], "-L") == 0)) {
793 log_file = argv[i + 1];
794 break;
795 }
796 }
797
798 // EARLY PARSE: Check for --json (JSON logging format)
799 // If JSON format is enabled, we'll use the JSON filename during early init
800 // --json MUST appear BEFORE the mode
801 bool early_json_format = false;
802 if (mode_position > 0) {
803 for (int i = 1; i < mode_position; i++) {
804 if (strcmp(argv[i], "--json") == 0) {
805 early_json_format = true;
806 break;
807 }
808 }
809 } else {
810 // If no mode found, search entire argv
811 for (int i = 1; i < argc; i++) {
812 if (strcmp(argv[i], "--json") == 0) {
813 early_json_format = true;
814 break;
815 }
816 }
817 }
818
819 // EARLY PARSE: Extract log template from argv (--log-template)
820 // Note: This is for format templates, different from --log-format which is the output format
821 // Binary-level options must appear BEFORE the mode
822 const char *early_log_template = NULL;
823 bool early_log_template_console_only = false;
824 for (int i = 1; i < max_search - 1; i++) {
825 if (strcmp(argv[i], "--log-template") == 0) {
826 early_log_template = argv[i + 1];
827 break;
828 }
829 }
830 for (int i = 1; i < max_search; i++) {
831 if (strcmp(argv[i], "--log-format-console") == 0 || strcmp(argv[i], "--log-format-console=true") == 0) {
832 early_log_template_console_only = true;
833 } else if (strcmp(argv[i], "--log-format-console=false") == 0) {
834 early_log_template_console_only = false;
835 }
836 }
837
838 // Documentation actions should not be preceded by startup diagnostics.
839 bool early_quiet_output = false;
840 for (int i = 1; i < argc; i++) {
841 if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-V") == 0) {
842 early_quiet_output = true;
843 break;
844 }
845 }
846
847 // Version output is self-contained and must not cross the shared platform
848 // initialization/DLL boundary. Keep this path deterministic for scripts
849 // and package managers, and avoid initializing subsystems that the action
850 // immediately terminates without using.
851 for (int i = 1; i < argc; i++) {
852 if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
853 printf("ascii-chat %s (%s, %s)\n", ASCII_CHAT_VERSION_FULL, ASCII_CHAT_BUILD_TYPE, ASCII_CHAT_BUILD_DATE);
854 fflush(stdout);
855 _Exit(0);
856 }
857 }
858
859 // Initialize shared subsystems BEFORE options_init()
860 // This ensures options parsing can use properly configured logging with colors
861 // If JSON format is requested, don't write text logs to file
862 // All logs will be JSON formatted later once options_init() runs
863 const char *early_log_file = early_json_format ? NULL : log_file;
864 asciichat_error_t init_result = asciichat_shared_init(early_log_file, is_client_like_mode, early_quiet_output);
865 if (init_result != ASCIICHAT_OK) {
866 return init_result;
867 }
868
869 // Install the console handler before option/media initialization. Startup
870 // can create worker threads and begin telemetry before mode dispatch; a
871 // Ctrl-C during that window must still enter the coordinated shutdown path.
873
874 // Route logs to stderr if stdout is piped (MUST happen early, before options_init logs)
875 // This keeps stdout clean for data output (e.g., --snapshot mode piped to file)
878 }
879
880 // Keep documentation output free of diagnostics while parsing the options.
881 if (early_quiet_output) {
883 }
884
885 // Register cleanup of shared subsystems to run on normal exit
886 // Library code doesn't call atexit() - the application is responsible
887 // Handlers run in reverse registration order: restore the cursor, destroy
888 // shared subsystems, then run the compatibility path cleanup.
889 (void)atexit(path_cleanup_thread_locals);
890 (void)atexit(asciichat_shared_destroy);
891 (void)atexit(on_exit_show_cursor);
892
893 // SECRET: Check for --backtrace (debug builds only) BEFORE options_init()
894 // Prints a backtrace and exits immediately - useful for debugging hangs
895#ifndef NDEBUG
896 for (int i = 1; i < argc; i++) {
897 if (strcmp(argv[i], "--backtrace") == 0) {
898 log_info("=== Backtrace at startup ===");
900 log_info("=== End Backtrace ===");
902 return 0;
903 }
904 }
905#endif
906
907 // NOW parse all options - can use logging with colors!
908 asciichat_error_t options_result = options_init(argc, argv);
909 if (options_result != ASCIICHAT_OK) {
911 if (HAS_ERRNO(&error_ctx)) {
912 NOTICE(WARNING, "INVALID OPTIONS", "%s", error_ctx.context_message);
913 } else {
914 NOTICE(WARNING, "OPTIONS INITIALIZATION FAILED", "Failed to initialize options %s", asciichat_error_format(NULL, options_result));
915 }
916
917 // Clean up options state before exiting
919
920 exit(options_result);
921 }
922
923 // Get parsed options
924 const options_t *opts = options_get();
925 if (!opts) {
926 log_error("Options not initialized");
927 return 1;
928 }
929
930 // Apply the parsed level after the early logger has initialized.
932 // Determine output format early to decide on filename and logging strategy
933 bool use_json_logging = GET_OPTION(json);
934
935 // Determine the log filename
936 // Check if user explicitly passed --log-file (not just the mode-specific default from options_init)
937 bool user_specified_log_file = false;
938 for (int i = 1; i < argc - 1; i++) {
939 if (strcmp(argv[i], "--log-file") == 0 || strcmp(argv[i], "-L") == 0) {
940 user_specified_log_file = true;
941 break;
942 }
943 }
944
945 const char *final_log_file = opts->log_file;
946 char json_filename_buf[MAIN_JSON_FILENAME_BUFFER_SIZE];
947
948 if (use_json_logging) {
949 // When JSON logging is enabled, determine JSON output filename
950 if (user_specified_log_file) {
951 // User explicitly specified a log file - use it exactly for JSON output
952 SAFE_STRNCPY(json_filename_buf, final_log_file, sizeof(json_filename_buf) - 1);
953 } else {
954 // Using default: replace .log with .json in the mode-specific default
955 // e.g., server.log -> server.json, mirror.log -> mirror.json, etc.
956 size_t len = strlen(final_log_file);
957 if (len > 4 && strcmp(&final_log_file[len - 4], ".log") == 0) {
958 // File ends with .log - replace with .json
959 SAFE_STRNCPY(json_filename_buf, final_log_file, sizeof(json_filename_buf) - 1);
960 // Replace .log with .json
961 asciichat_error_t strcpy_result = SAFE_STRCPY(&json_filename_buf[len - 4], sizeof(json_filename_buf) - (len - 4), ".json");
962 if (strcpy_result != ASCIICHAT_OK) {
963 log_error("Failed to write .json extension: %s", asciichat_error_format(NULL, strcpy_result));
964 }
965 } else {
966 // File doesn't end with .log - just append .json
967 snprintf(json_filename_buf, sizeof(json_filename_buf), "%s.json", final_log_file);
968 }
969 }
970 final_log_file = json_filename_buf;
971 // For JSON mode: Initialize logging without file (text will be disabled)
972 // We'll set up JSON output separately below
973 // Note: log_init() was already called in asciichat_shared_init()
974 } else {
975 // Text logging mode: use the file from options (which is mode-specific default or user-specified)
976 // Note: log_init() was already called in asciichat_shared_init()
977 }
978
979 // Apply custom log template if specified (use early parsed value if available, otherwise use options)
980 const char *final_format = early_log_template ? early_log_template : GET_OPTION(log_template);
981 bool final_format_console_only = early_log_template ? early_log_template_console_only : GET_OPTION(log_format_console_only);
982 if (final_format && final_format[0] != '\0') {
983 asciichat_error_t fmt_result = log_set_format(final_format, final_format_console_only);
984 if (fmt_result != ASCIICHAT_OK) {
985 log_error("Failed to apply custom log format");
986 }
987 }
988
989 // Configure JSON output if requested
990 if (use_json_logging) {
991 // Close the text sink before truncating the destination for JSON records.
992 // The two descriptors must not write different formats at independent offsets.
994 int json_fd = platform_open("main_log_file", final_log_file, O_CREAT | O_RDWR | O_TRUNC, FILE_PERM_PRIVATE);
995 if (json_fd >= 0) {
996 log_set_json_output(json_fd);
997 } else {
998 // Failed to open JSON file - report error and exit
999 SET_ERRNO(ERROR_CONFIG, "Failed to open JSON output file: %s", final_log_file);
1000 return ERROR_CONFIG;
1001 }
1002 }
1003
1004 // Initialize colors now that logging is fully initialized
1005 // This must happen after log_init() since log_init_colors() checks if g_log.initialized
1007 log_debug("SIMD luminance backend: %s", simd_backend()->name);
1008
1009 // Apply quiet mode - disables terminal output
1010 // Status screen mode only disables terminal output if terminal is interactive
1011 // In non-interactive mode (piped output), logs go to stdout/stderr normally
1012 if (GET_OPTION(quiet) || (opts->detected_mode == MODE_SERVER && GET_OPTION(status_screen) && terminal_is_interactive())) {
1014 }
1015
1016 // Initialize palette based on command line options
1017 const char *custom_chars = opts && opts->palette_custom_set ? opts->palette_custom : NULL;
1018 if (apply_palette_config(GET_OPTION(palette_type), custom_chars) != 0) {
1019 FATAL(ERROR_CONFIG, "Failed to apply palette configuration");
1020 }
1021
1022 // Set quiet mode for memory debugging
1023#if defined(DEBUG_MEMORY) && !defined(USE_MIMALLOC_DEBUG) && !defined(NDEBUG)
1024 debug_memory_set_quiet_mode(GET_OPTION(quiet));
1025#endif
1026
1027 // Truncate log if it's already too large
1029 fflush(stderr);
1030
1031 // Handle --help and --version (these are detected and flagged by options_init)
1032 // Terminal capabilities already initialized before options_init() at startup
1033 if (opts->help) {
1035 print_usage(opts->detected_mode);
1036 fflush(NULL);
1037 asciichat_coverage_flush();
1038 _Exit(0);
1039 }
1040
1041 if (opts->version) {
1044 // action_show_version() calls _Exit(), so we don't reach here
1045 }
1046
1047#ifndef NDEBUG
1048 // Handle --debug-state (debug builds only)
1049 // Sleep for specified time AFTER mode initialization so locks are created
1050 if (opts->debug_sync_state_time > 0.0) {
1051 log_info("Will print sync state after %f seconds", opts->debug_sync_state_time);
1052 }
1053#endif
1054
1055 // For server mode with status screen: disable terminal output only if interactive
1056 // In non-interactive mode (piped output), logs go to stdout/stderr normally
1057 // The status screen (when shown) will capture and display logs in its buffer instead
1060 }
1061
1062 log_dev("Logging initialized to %s", final_log_file);
1063
1064 // Note: We do NOT auto-disable colors when stdout appears to be piped, because:
1065 // 1. Tools like ripgrep can display ANSI colors when piped
1066 // 2. Sandboxed/containerized environments may report false positives for isatty()
1067 // 3. Users can explicitly disable colors with --color=false if needed
1068 // Color behavior is now fully controlled by --color and --color-mode options.
1069
1070#ifndef NDEBUG
1071 // Initialize lock debugging system after logging is fully set up
1072 log_debug("Initializing lock debug system...");
1073 int debug_sync_result = debug_stats_init();
1074 if (debug_sync_result != 0) {
1075 LOG_ERRNO_IF_SET("Debug sync system initialization failed");
1076 FATAL(ERROR_PLATFORM_INIT, "Debug sync system initialization failed");
1077 }
1078 log_debug("Debug sync system initialized successfully");
1079
1080#ifndef _WIN32
1081 // Unblock SIGUSR1 and SIGUSR2 at process level to ensure delivery
1082 sigset_t set;
1083 sigemptyset(&set);
1084 sigaddset(&set, SIGUSR1);
1085 sigaddset(&set, SIGUSR2);
1086 sigprocmask(SIG_UNBLOCK, &set, NULL);
1087
1088 // Register SIGUSR1 to trigger synchronization debugging output in all modes
1089 signal_handler_t old_usr1 = platform_signal(SIGUSR1, common_handle_sigusr1);
1090 if (old_usr1 == SIG_ERR) {
1091 log_warn("Failed to register SIGUSR1 handler");
1092 } else {
1093 log_debug("SIGUSR1 handler registered successfully");
1094 }
1095
1096 // Register SIGUSR2 to trigger memory report in all modes
1097 signal_handler_t old_usr2 = platform_signal(SIGUSR2, common_handle_sigusr2);
1098 if (old_usr2 == SIG_ERR) {
1099 log_warn("Failed to register SIGUSR2 handler");
1100 } else {
1101 log_debug("SIGUSR2 handler registered successfully");
1102 }
1103#endif
1104#endif
1105
1106 if (opts->fps > 0) {
1107 if (opts->fps < 1 || opts->fps > 144) {
1108 log_warn("FPS value %d out of range (1-144), using default", opts->fps);
1109 } else {
1110 log_debug("FPS set from command line: %d", opts->fps);
1111 }
1112 }
1113
1114 // Automatic update check in background thread (once per week maximum)
1115 if (opts->detected_mode != MODE_MCP_SERVER && !GET_OPTION(no_check_update)) {
1117 }
1118
1119 // Register application callbacks so lib code can check exit flags
1120 // This connects the render loop's should_exit check to signal_exit()
1121 static const app_callbacks_t app_callbacks = {
1122 .should_exit = should_exit,
1123 .signal_exit = signal_exit,
1124 .platform_get_monotonic_time_us = platform_get_monotonic_time_us,
1125 .platform_sleep_ms = platform_sleep_ms,
1126 };
1127 app_callbacks_register(&app_callbacks);
1128
1129 static const platform_question_callbacks_t question_callbacks = {
1130 .pop_response = env_pop_prompt_response,
1131 .input = platform_question_input_adapter,
1132 .notice_kind = ui_notice_prompt_kind,
1133 .kind_name = ui_prompt_kind_name,
1134 .error = app_question_error,
1135 .usage = app_question_usage,
1136 };
1137 platform_question_set_callbacks(&question_callbacks);
1138
1139 // Register shutdown callback so splash thread and other code can check for exit
1141
1142 // Diagnostic monitoring is Debug-only; error storage is available in every build.
1143#ifndef NDEBUG
1144 uint64_t sync_state_delay_ns = 0;
1145 uint64_t debug_backtrace_delay_ns = 0;
1146 if (opts->debug_sync_state_time > 0.0)
1147 sync_state_delay_ns = (uint64_t)(opts->debug_sync_state_time * 1000000000.0);
1148 if (opts->debug_backtrace_time > 0.0)
1149 debug_backtrace_delay_ns = (uint64_t)(opts->debug_backtrace_time * 1000000000.0);
1150 if (debug_sync_start_thread(sync_state_delay_ns, debug_backtrace_delay_ns) != 0) {
1151 FATAL(ERROR_THREAD, "Cannot start synchronization worker");
1152 }
1154 FATAL(ERROR_THREAD, "Cannot start errno worker");
1155 }
1157 FATAL(ERROR_THREAD, "Cannot start diagnostics worker");
1158 }
1159#endif
1160
1161 // Find and dispatch to mode entry point
1162 const mode_descriptor_t *mode = find_mode(opts->detected_mode);
1163 if (!mode) {
1164 log_error("Mode not found for detected_mode=%d", opts->detected_mode);
1165 return 1;
1166 }
1167
1168 // Call the mode-specific entry point
1169 // Mode entry points use options_get() to access parsed options
1170 if (title_init_result == ASCIICHAT_OK) {
1172 asciichat_error_t title_result = platform_process_title_set_args("ascii-chat: ", mode->name, argc, argv, opts->mode_arg_index);
1173 if (title_result != ASCIICHAT_OK) {
1174 log_debug("Could not set process title for %s mode", mode->name);
1175 } else {
1176 ASSERT_NO_ERRNO_SINCE(title_scope);
1177 }
1179 } else {
1180 log_debug("Process title initialization was unavailable %s", asciichat_error_format(NULL, title_init_result));
1181 }
1182 asciichat_errno_scope_t terminal_title_scope = errno_scope_begin();
1183 if (opts->detected_mode != MODE_MCP_SERVER || !strcmp(GET_OPTION(mcp_transport), "http"))
1184 (void)ui_controller_title_start(mode->name, platform_isatty(STDOUT_FILENO) ? STDOUT_FILENO : STDERR_FILENO);
1185 errno_scope_end(terminal_title_scope, ASCIICHAT_ERRNO_DISMISSED);
1186 if (strcmp(mode->name, "mirror") != 0) {
1187 asciichat_error_t stats_result = stats_runtime_start(mode->name, (unsigned)GET_OPTION(stats_interval));
1188 if (stats_result != ASCIICHAT_OK)
1189 return stats_result;
1190 }
1191 asciichat_error_t otel_result = ascii_otel_init(mode->name, argc, argv);
1192 if (otel_result != ASCIICHAT_OK) {
1194 const char *detail = HAS_ERRNO(&context) ? context.context_message : NULL;
1195 log_error("Telemetry configuration failed %s", asciichat_error_format(detail, otel_result));
1196 return otel_result;
1197 }
1198 int exit_code = mode->entry_point();
1199 asciichat_error_t requested_exit = errno_exit_code();
1200 if (requested_exit != ASCIICHAT_OK)
1201 exit_code = requested_exit;
1202 if (!shutdown_is_requested())
1204 if (!shutdown_is_requested())
1205 ascii_otel_exit(exit_code);
1206 log_debug("Shutdown: entering telemetry shutdown");
1208 log_debug("Shutdown: telemetry shutdown complete");
1209
1210 // Named registry cleanup is handled by asciichat_shared_destroy()
1211 // (called via atexit handler), which runs AFTER the memory report
1212
1213 if (exit_code == ERROR_USAGE) {
1214 exit(ERROR_USAGE);
1215 }
1216
1217 return exit_code;
1218}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_error_t errno_exit_code(void)
asciichat_errno_scope_t errno_scope_begin(void)
const char * asciichat_error_format(const char *message, asciichat_error_t code)
#define SET_ERRNO(code,...)
#define HAS_ERRNO(context)
#define ASSERT_NO_ERRNO_SINCE(scope)
@ ASCIICHAT_ERRNO_DISMISSED
#define LOG_ERRNO_IF_SET(message)
void debug_atomic_init(void)
void backtrace_print_simple(int skip_frames)
Definition backtrace.c:60
@ OPTION_TYPE_ACTION
Action that executes and may exit (–list-webcams, etc.).
Definition builder.h:176
@ OPTION_TYPE_BOOL
Boolean flag (–flag, no value).
Definition builder.h:171
asciichat_error_t options_colorscheme_init_early(int argc, const char *const argv[])
Initialize color scheme early (before logging).
asciichat_error_t colorscheme_load_builtin(const char *name, color_scheme_t *scheme)
Load a built-in color scheme.
const registry_entry_t * registry_find_entry_by_name(const char *long_name)
Get a registry entry by long name.
Definition core.c:126
const registry_entry_t * registry_find_entry_by_short(char short_name)
Get a registry entry by short name.
Definition core.c:144
void registry_init_size(void)
Initialize registry size and metadata.
Definition core.c:107
const simd_backend_t * simd_backend(void)
Definition dispatch.c:36
bool env_pop_prompt_response(char *response_out, size_t response_size)
Pop the first response from ASCII_CHAT_QUESTION_PROMPT_RESPONSE stack.
Definition env.c:96
asciichat_error_t debug_errno_start_thread(void)
Definition errno.c:90
int platform_open(const char *name, const char *pathname, int flags,...)
Definition filesystem.c:65
asciichat_error_t grep_init(const char *pattern)
Initialize log filtering with PCRE2 regex pattern.
Definition grep.c:411
bool g_color_flag_value
Value of –color flag (true if –color was in argv) Set by options_init() before RCU is initialized,...
Definition common.c:66
char ** g_argv
Global argv for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:62
#define SAFE_STRNCPY(dst, src, size)
int g_argc
Global argc for early argument inspection (e.g., –color flag detection) Set by main() for access from...
Definition common.c:61
bool g_color_flag_passed
Was –color explicitly passed in command-line arguments? Set by options_init() before RCU is initializ...
Definition common.c:65
asciichat_error_t asciichat_shared_init(const char *log_file, bool is_client, bool quiet_startup)
Initialize common subsystems shared by client and server.
Definition common.c:131
#define SAFE_STRCPY(dest, dest_size, src)
#define FATAL(code,...)
Exit with error code and custom message, with stack trace in debug builds.
unsigned long long uint64_t
void asciichat_shared_destroy(void)
Clean up all shared library subsystems.
Definition common.c:219
#define NAMED_REGISTER_THREAD(thread, name, parent_ptr)
Register a thread handle with name and automatic format specifier.
void named_registry_register_packet_types(void)
Register all packet types from packet_type_t enum.
asciichat_error_t named_init(void)
Initialize the named object registry.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_PLATFORM_INIT
Definition error_codes.h:59
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_FILE_OPERATION
@ ERROR_USAGE
Definition error_codes.h:52
@ ERROR_THREAD
void log_truncate_if_large(void)
Manually truncate large log files.
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
void log_init_colors(void)
Initialize logging color system with current terminal capabilities.
#define log_dev(...)
Log a DEV message (most verbose, development only).
Definition log/log.h:575
void log_set_force_stderr(bool enabled)
Force all terminal log output to stderr.
const char * log_level_color(log_color_t color)
Get color string for a given color enum.
void log_disable_file_output(void)
Disable file output and use stderr instead.
#define log_error(...)
Log an ERROR message.
Definition log/log.h:628
void log_set_level(log_level_t level)
Set the minimum log level.
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
asciichat_error_t log_set_format(const char *format_str, bool console_only)
Set a custom log format string.
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define log_file(...)
File-only logging - writes to log file only, no stderr output.
Definition log/log.h:687
void log_set_terminal_output(bool enabled)
Control stderr output to terminal.
void log_set_color_scheme(const color_scheme_t *scheme)
Set the color scheme for logging output.
void log_redetect_terminal_capabilities(void)
Re-detect terminal capabilities after logging is initialized.
@ LOG_COLOR_RESET
Definition log/log.h:154
@ LOG_COLOR_GREY
Definition log/log.h:153
@ LOG_COLOR_FATAL
Definition log/log.h:152
@ LOG_COLOR_ERROR
Definition log/log.h:151
@ LOG_COLOR_DEV
Definition log/log.h:147
@ LOG_COLOR_DEBUG
Definition log/log.h:148
@ LOG_COLOR_INFO
Definition log/log.h:149
@ LOG_COLOR_WARN
Definition log/log.h:150
#define GET_OPTION(field)
Definition options.h:1333
asciichat_mode_t
Mode type for options parsing.
Definition options.h:916
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:495
asciichat_error_t options_init(int argc, char **argv)
Initialize options by parsing command-line arguments with unified mode detection.
Definition options.c:2291
#define options_terminal_settings()
Definition options.h:1287
@ MODE_CLIENT
Client mode - network client options.
Definition options.h:918
@ MODE_MCP_SERVER
Model Context Protocol rendering server.
Definition options.h:922
@ MODE_DISCOVERY_SERVICE
Discovery server mode - session management and WebRTC signaling.
Definition options.h:920
@ MODE_API_SERVER
Image-to-ASCII HTTP API server.
Definition options.h:923
@ MODE_INVALID
Invalid mode.
Definition options.h:924
@ MODE_SERVER
Server mode - network server options.
Definition options.h:917
@ MODE_MIRROR
Mirror mode - local webcam viewing (no network).
Definition options.h:919
@ MODE_DISCOVERY
Discovery mode - participant that can dynamically become host.
Definition options.h:921
int apply_palette_config(palette_type_t type, const char *custom_chars)
Apply palette configuration (set global palette).
Definition palette.c:243
void update_banner_start_check(void)
Start the background update check thread.
bool(* shutdown_check_fn)(void)
Shutdown check callback function type.
Definition shutdown.h:36
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:86
void shutdown_register_callback(shutdown_check_fn callback)
Register application's shutdown check function.
Definition common.c:78
void path_cleanup_thread_locals(void)
Cleanup thread-local path resources.
Definition path.c:32
void debug_stats_set_main_thread_id(void)
asciichat_error_t debug_stats_init(void)
asciichat_error_t debug_stats_start_thread(void)
void log_set_json_output(int fd)
Set the JSON output file descriptor.
void action_show_version(void)
Show version information and exit.
void signal_exit(void)
Definition main.c:252
#define REGISTER_GLOBAL_ATOMICS()
Definition main.c:227
void setup_signal_handlers(void)
Definition main.c:404
#define MAIN_JSON_FILENAME_BUFFER_SIZE
Definition main.c:4
bool should_exit(void)
Definition main.c:248
asciichat_error_t mcp_stdio_reserve(void)
Definition stdio.c:7
signal_handler_t platform_signal(int sig, signal_handler_t handler)
Definition misc.c:123
void(* signal_handler_t)(int)
Definition misc.c:121
ui_prompt_kind_t ui_notice_prompt_kind(void)
Definition notice.c:494
#define NOTICE(severity, title,...)
Definition notice.h:56
void ascii_otel_shutdown(void)
Definition otel.c:445
void ascii_otel_exit(int code)
Definition otel.c:715
asciichat_error_t ascii_otel_init(const char *mode, int argc, char **argv)
Definition otel.c:530
const char * ui_prompt_kind_name(ui_prompt_kind_t kind)
Definition prompt.c:225
void options_state_destroy(void)
Shutdown RCU options system.
Definition rcu.c:465
void stats_runtime_stop(void)
Definition runtime.c:611
asciichat_error_t stats_runtime_start(const char *mode, unsigned interval_seconds)
Definition runtime.c:492
void app_callbacks_register(app_callbacks_reg_t *callbacks)
void apply_color_mode_override_into(const terminal_capabilities_t *caps, const terminal_options_t *options, terminal_capabilities_t *out)
bool terminal_is_interactive(void)
void detect_terminal_capabilities_into(const terminal_options_t *options, terminal_capabilities_t *out)
bool terminal_should_force_stderr(void)
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Color scheme definition.
Definition colorscheme.h:76
mode_entry_point_t entry_point
Definition main.c:439
double debug_sync_state_time
Time parameter for –sync-state.
Definition options.h:1239
asciichat_mode_t detected_mode
Mode detected from command-line arguments.
Definition options.h:978
log_level_t log_level
Log level threshold.
Definition options.h:1160
char palette_custom[256]
Custom palette characters.
Definition options.h:1221
bool status_screen
Show status screen (default: true = show, use –no-status-screen to hide).
Definition options.h:1230
bool palette_custom_set
True if custom palette was set.
Definition options.h:1222
bool version
Show version information.
Definition options.h:985
bool help
Show help message.
Definition options.h:984
int fps
Target framerate (0 = auto, 1-144).
Definition options.h:1091
double debug_backtrace_time
Time parameter for –backtrace option.
Definition options.h:1241
int mode_arg_index
Explicit mode token in original argv, or -1 for implicit discovery/session strings.
Definition options.h:979
char log_file[256]
Log file path.
Definition options.h:1159
Registry entry - stores option definition with mode bitmask and metadata.
option_type_t type
asciichat_error_t ui_controller_title_start(const char *mode, int fd)
asciichat_error_t ui_controller_write(int fd, const char *data, size_t len)
int platform_isatty(int fd)
Definition util.c:70

References action_show_version(), app_callbacks_register(), apply_color_mode_override_into(), apply_palette_config(), ascii_otel_exit(), ascii_otel_init(), ascii_otel_shutdown(), ASCIICHAT_ERRNO_DISMISSED, asciichat_error_format(), ASCIICHAT_OK, asciichat_shared_destroy(), asciichat_shared_init(), ASSERT_NO_ERRNO_SINCE, backtrace_print_simple(), colorscheme_load_builtin(), asciichat_error_context_t::context_message, debug_atomic_init(), options_state::debug_backtrace_time, debug_errno_start_thread(), debug_stats_init(), debug_stats_set_main_thread_id(), debug_stats_start_thread(), options_state::debug_sync_state_time, detect_terminal_capabilities_into(), options_state::detected_mode, mode_descriptor_t::entry_point, env_pop_prompt_response(), errno_exit_code(), errno_scope_begin(), errno_scope_end(), ERROR_CONFIG, ERROR_FILE_OPERATION, ERROR_PLATFORM_INIT, ERROR_THREAD, ERROR_USAGE, FATAL, options_state::fps, g_argc, g_argv, g_color_flag_passed, g_color_flag_value, GET_OPTION, grep_init(), HAS_ERRNO, options_state::help, LOG_COLOR_DEBUG, LOG_COLOR_DEV, LOG_COLOR_ERROR, LOG_COLOR_FATAL, LOG_COLOR_GREY, LOG_COLOR_INFO, LOG_COLOR_RESET, LOG_COLOR_WARN, log_debug, log_dev, log_disable_file_output(), LOG_ERRNO_IF_SET, log_error, log_file, options_state::log_file, log_info, log_init_colors(), options_state::log_level, log_level_color(), log_redetect_terminal_capabilities(), log_set_color_scheme(), log_set_force_stderr(), log_set_format(), log_set_json_output(), log_set_level(), log_set_terminal_output(), log_truncate_if_large(), log_warn, MAIN_JSON_FILENAME_BUFFER_SIZE, mcp_stdio_reserve(), MODE_API_SERVER, options_state::mode_arg_index, MODE_CLIENT, MODE_DISCOVERY, MODE_DISCOVERY_SERVICE, MODE_INVALID, MODE_MCP_SERVER, MODE_MIRROR, MODE_SERVER, mode_descriptor_t::name, named_init(), NAMED_REGISTER_THREAD, named_registry_register_packet_types(), NOTICE, OPTION_TYPE_ACTION, OPTION_TYPE_BOOL, registry_entry_t::optional_arg, options_colorscheme_init_early(), options_get(), options_init(), options_state_destroy(), options_terminal_settings, options_state::palette_custom, options_state::palette_custom_set, path_cleanup_thread_locals(), platform_isatty(), platform_open(), platform_signal(), REGISTER_GLOBAL_ATOMICS, registry_find_entry_by_name(), registry_find_entry_by_short(), registry_init_size(), SAFE_STRCPY, SAFE_STRNCPY, SET_ERRNO, setup_signal_handlers(), should_exit(), shutdown_is_requested(), shutdown_register_callback(), signal_exit(), simd_backend(), stats_runtime_start(), stats_runtime_stop(), options_state::status_screen, terminal_is_interactive(), terminal_should_force_stderr(), registry_entry_t::type, ui_controller_title_start(), ui_controller_write(), ui_notice_prompt_kind(), ui_prompt_kind_name(), update_banner_start_check(), and options_state::version.

◆ set_interrupt_callback()

void set_interrupt_callback ( void(* cb )(void))

Register a mode-specific interrupt callback

Called by mode-specific code to register a callback that will be invoked when signal_exit() is called. Used to shut down network sockets so threads blocked in recv() unblock quickly instead of waiting for timeouts.

The callback is called synchronously from signal_exit(), so it must be async-signal-safe (only atomics, socket_shutdown(), no malloc/etc).

Only one callback can be registered at a time. Setting a new callback replaces the previous one.

Parameters
cbFunction to call on exit signal, or NULL to unregister

Definition at line 272 of file main.c.

272 {
273 g_interrupt_callback = cb;
274}

Referenced by acds_main(), client_main(), and discovery_main().

◆ setup_signal_handlers()

void setup_signal_handlers ( void )

Set up global signal handlers Called once at startup before mode dispatch

Definition at line 404 of file main.c.

404 {
405 if (!platform_set_console_ctrl_handler(console_ctrl_handler)) {
406 log_warn("Failed to register Windows console control handler: %d", platform_get_last_error());
407 }
408
409#ifdef _WIN32
410 /* Keep a CRT fallback for consoles that deliver Ctrl-C as SIGINT rather
411 * than invoking the process console handler (notably private test consoles). */
412 signal(SIGINT, windows_sigint_handler);
413#ifdef SIGBREAK
414 signal(SIGBREAK, windows_sigint_handler);
415#endif
416 log_dev("Signal handlers registered");
417#endif
418
419#ifndef _WIN32
420 platform_signal_handler_t handlers[] = {
421 {SIGINT, handle_sigterm},
422 {SIGTERM, handle_sigterm},
423 {SIGPIPE, SIG_IGN},
424 };
425 platform_register_signal_handlers(handlers, 3);
426 log_dev("Signal handlers registered");
427#endif
428}
int platform_get_last_error(void)
Definition util.c:101

References log_dev, log_warn, and platform_get_last_error().

Referenced by main().

◆ should_exit()

bool should_exit ( void )

Check if the application should exit

Called by mode main loops to detect shutdown requests from signals or errors.

Returns
true if shutdown has been requested, false otherwise

Definition at line 248 of file main.c.

248 {
250}
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.

References atomic_load_bool(), and g_should_exit.

Referenced by api_server_main(), client_connection_start(), display_full_reset(), main(), mcp_http_run(), session_pipeline_run_main(), and session_render_loop().

◆ signal_exit()

void signal_exit ( void )

Signal that the application should exit

Sets the global exit flag and calls the registered interrupt callback if set. Safe to call from signal handlers (uses only atomics and function pointers). Called by signal handlers (SIGTERM, Ctrl+C) and normal code (errors, timeouts).

Definition at line 252 of file main.c.

252 {
253 // Note: This function may be called from a signal handler context where
254 // other threads may hold mutex locks. We avoid log_console() here to prevent
255 // deadlock (render loop holds terminal lock, signal handler can't acquire it).
256 // The shutdown will be logged by normal thread context later.
257 // Ctrl-C can arrive through both the console-control handler and the
258 // terminal input path. Only the first request may run the shutdown
259 // callback; running it twice races teardown and can leave the process stuck.
261 return;
262 log_info("Shutdown signal received");
263 // Interrupt telemetry network I/O immediately. Full drain/free remains in
264 // the normal teardown path, but cancellation must not wait for atexit.
266 void (*cb)(void) = g_interrupt_callback;
267 if (cb) {
268 cb();
269 }
270}
bool atomic_exchange_bool(atomic_t *a, bool new_value)
Atomically exchange a boolean and return the old value.
void ascii_otel_request_shutdown(void)
Definition otel.c:156

References ascii_otel_request_shutdown(), atomic_exchange_bool(), g_should_exit, and log_info.

Referenced by main(), session_display_write_ascii_frame(), session_render_loop(), ui_input_password(), and update_banner_install_update().