Skip to content

sudeepSubedi01/Terminal-Multiplexer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Enhanced Terminal Multiplexer

A lightweight, feature-rich terminal multiplexer implementation in C that allows users to create, manage, and switch between multiple terminal sessions. This project provides functionality similar to tmux/screen with enhanced session management and real-time screen buffer synchronization.

Project Description

This terminal multiplexer consists of a client-server architecture where:

  • Server: Manages multiple terminal sessions, handles PTY operations, and maintains screen buffers
  • Client: Provides user interface for session interaction and implements hotkey-based session switching

The system uses Unix domain sockets for inter-process communication and pseudo-terminals (PTY) for shell process management. Each session maintains its own screen buffer with ANSI escape sequence processing for proper terminal emulation.

Features

Core Features

  • Multi-session Management: Create and manage up to 16 concurrent terminal sessions
  • Client Multiplexing: Support for up to 8 clients per session
  • Real-time Screen Synchronization: Maintains screen buffers with scrollback history
  • ANSI Terminal Emulation: Proper handling of escape sequences, cursor positioning, and screen clearing
  • Dynamic Window Resizing: Automatic terminal size propagation to shell processes

Session Management

  • Session Creation: Create named sessions with custom shell environments
  • Session Attachment: Attach/detach from existing sessions without data loss
  • Session Persistence: Sessions continue running even when no clients are attached
  • Session Listing: View all active sessions with client counts and dimensions

Hotkey Navigation (tmux-style)

  • Ctrl+B + 1-4: Quick switch to sessions 0-3
  • Ctrl+B + s: Display session status and help
  • Ctrl+B + d: Detach from current session
  • Ctrl+D: Alternative detach method

Screen Buffer Management

  • Real-time Output Processing: Live terminal output with proper character positioning
  • Scrollback Buffer: 1000 lines of history per session
  • Screen Restoration: New clients receive current screen state upon attachment
  • Terminal State Preservation: Cursor position and screen content maintained across client connections

Usage

Starting the Server

# Compile the program
make build

# Start the server (daemon mode)
./tmux

Basic Commands

# Create a new session
./tmux new [session_name]

# Attach to an existing session
./tmux attach [session_id]

# List all active sessions
./tmux list

# Examples:
./tmux new development    # Creates session named "development"
./tmux new               # Creates session with auto-generated name
./tmux attach 0          # Attaches to session ID 0
./tmux attach            # Attaches to session ID 0 (default)

Session Navigation Hotkeys

Once attached to a session:

  • Ctrl+B, then 1: Switch to session 0
  • Ctrl+B, then 2: Switch to session 1
  • Ctrl+B, then 3: Switch to session 2
  • Ctrl+B, then 4: Switch to session 3
  • Ctrl+B, then s: Show session status and help
  • Ctrl+B, then d: Detach from current session
  • Ctrl+D: Detach from session (alternative method)

Example Workflow

# Terminal 1: Start server
./tmux

# Terminal 2: Create and work in multiple sessions
./tmux new webapp        # Create web development session
# Work in webapp session, then press Ctrl+B + d to detach

./tmux new database      # Create database session
# Work in database session, then press Ctrl+B + 1 to switch back to webapp

./tmux list             # View all sessions
# Output: Active sessions:
#   0: webapp (0 clients) [80x24]
#   1: database (1 clients) [80x24]

System Calls Used

Process Management

  • fork(): Creates child processes for shell sessions
  • execl(): Replaces child process image with shell (/bin/bash)
  • waitpid(): Waits for child process termination and cleans up zombies
  • kill(): Sends termination signals to shell processes during cleanup
  • getpid(): Generates unique session names and process identification

Pseudo-Terminal Operations

  • openpty(): Creates master/slave pseudo-terminal pairs for shell communication
  • setsid(): Creates new session for shell process (session leader)
  • ioctl() with TIOCSCTTY: Sets controlling terminal for shell process
  • ioctl() with TIOCGWINSZ: Gets current terminal window size
  • ioctl() with TIOCSWINSZ: Sets terminal window size for shell processes

File Descriptor Operations

  • read(): Reads input from clients and output from shell processes
  • write(): Writes data to shells and clients
  • dup2(): Redirects stdin/stdout/stderr to pseudo-terminal slave
  • close(): Closes file descriptors during cleanup and disconnection
  • select(): Multiplexes I/O operations across multiple file descriptors

Socket Communication

  • socket(): Creates Unix domain sockets for client-server communication
  • bind(): Binds socket to filesystem path (/tmp/tmux_socket)
  • listen(): Sets socket to listening mode for incoming connections
  • accept(): Accepts new client connections
  • connect(): Connects clients to server socket
  • send()/recv(): Sends/receives structured messages between client and server

Terminal Control

  • tcgetattr(): Gets current terminal attributes for raw mode setup
  • tcsetattr(): Sets terminal to raw mode for character-by-character input
  • unlink(): Removes socket file during server startup

Signal Handling

  • signal(): Registers signal handlers for cleanup and window resize events
  • SIGWINCH: Window resize signal handling for dynamic terminal resizing
  • SIGINT/SIGTERM/SIGHUP: Graceful cleanup on termination signals

Memory and Environment

  • malloc(): Allocates memory for screen content serialization
  • free(): Deallocates dynamically allocated memory
  • setenv(): Sets TERM environment variable for proper shell terminal detection

Architecture

Message Protocol

The client-server communication uses a structured message format:

typedef struct {
    msg_type_t type;           // Message type (CREATE, ATTACH, DATA, etc.)
    int session_id;            // Target session identifier
    char session_name[64];     // Session name for creation
    int rows, cols;            // Terminal dimensions
    int data_len;              // Data payload length
    char data[1024];           // Message payload
} message_t;

Screen Buffer System

Each session maintains a comprehensive screen buffer:

  • Primary Screen: Current visible terminal content (200x200 max)
  • Scrollback Buffer: Historical content (1000 lines)
  • Cursor Tracking: Real-time cursor position
  • ANSI Processing: Escape sequence interpretation and execution

Session State Management

  • Process Lifecycle: Shell process creation, monitoring, and cleanup
  • Client Tracking: Multiple client attachment with connection management
  • Screen Synchronization: Real-time screen state sharing across clients
  • Terminal Emulation: Complete VT100/ANSI terminal compatibility

Building and Installation

Prerequisites

  • GCC compiler with C99 support
  • Linux/Unix system with PTY support
  • libutil development library

Compilation

# clean previous build
make clean

# build
make build

Installation

# Install system-wide
sudo make install

Technical Details

Performance Characteristics

  • Memory Usage: ~50KB per session + screen buffer overhead
  • Latency: Sub-millisecond session switching
  • Scalability: Up to 16 sessions × 8 clients = 128 concurrent connections
  • Screen Buffer: 200×200 cells + 1000 line scrollback per session

Error Handling

  • Automatic cleanup of orphaned processes
  • Graceful handling of client disconnections
  • Session recovery from shell process termination
  • Socket communication error recovery

Security Considerations

  • Unix domain sockets for local communication only
  • No network exposure by design
  • Process isolation through separate PTY sessions
  • Proper file descriptor cleanup prevents resource leaks

Limitations and Future Enhancements

Current Limitations

  • Maximum 16 sessions (configurable in source)
  • Session switching limited to sessions 0-3 via hotkeys
  • No session persistence across server restarts
  • Limited to local machine operation only

Potential Enhancements

  • Session configuration file support
  • Extended hotkey mapping for more sessions
  • Network socket support for remote access
  • Session logging and replay functionality
  • Custom shell command execution
  • Pane splitting within sessions

About

Terminal Multiplexer in Operating System

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors