Przejdź do treści

📁 Linux Proc and FS Semantics

Linux's /proc filesystem and virtual filesystem semantics provide powerful introspection and control capabilities unavailable on other Unix-like systems.

🧭 The /proc Filesystem

The /proc filesystem is a pseudo-filesystem that provides an interface to kernel data structures. It's commonly mounted at /proc and contains runtime system information.

Process Information

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Process directories
ls /proc/[0-9]*  # Lists all process directories

# Current process information
cat /proc/self/status
cat /proc/self/cmdline
cat /proc/self/environ

# Specific process information
cat /proc/1/status   # init process
cat /proc/1/cmdline  # init command line

System Information

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# CPU information
cat /proc/cpuinfo

# Memory information
cat /proc/meminfo

# Kernel version
cat /proc/version

# Boot command line
cat /proc/cmdline

# Mounted filesystems
cat /proc/mounts

Hardware Information

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Interrupts
cat /proc/interrupts

# I/O ports
cat /proc/ioports

# DMA channels
cat /proc/dma

# Partitions
cat /proc/partitions

🧪 /proc File Operations

Reading Process Information

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Process status details
parse_proc_status() {
    local pid="$1"
    local proc_file="/proc/$pid/status"

    if [ ! -f "$proc_file" ]; then
        echo "Process $pid not found" >&2
        return 1
    fi

    # Extract key information
    echo "PID: $(grep "^Pid:" "$proc_file" | awk '{print $2}')"
    echo "PPID: $(grep "^PPid:" "$proc_file" | awk '{print $2}')"
    echo "Name: $(grep "^Name:" "$proc_file" | awk '{print $2}')"
    echo "State: $(grep "^State:" "$proc_file" | awk '{print $2}')"
    echo "Threads: $(grep "^Threads:" "$proc_file" | awk '{print $2}')"
    echo "VmSize: $(grep "^VmSize:" "$proc_file" | awk '{print $2 $3}')"
    echo "VmRSS: $(grep "^VmRSS:" "$proc_file" | awk '{print $2 $3}')"
}

# Usage
# parse_proc_status 1

Memory Statistics

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Detailed memory analysis
analyze_memory() {
    local meminfo="/proc/meminfo"

    # Parse memory information
    local total=$(grep "^MemTotal:" "$meminfo" | awk '{print $2}')
    local free=$(grep "^MemFree:" "$meminfo" | awk '{print $2}')
    local available=$(grep "^MemAvailable:" "$meminfo" | awk '{print $2}')
    local buffers=$(grep "^Buffers:" "$meminfo" | awk '{print $2}')
    local cached=$(grep "^Cached:" "$meminfo" | awk '{print $2}')

    # Calculate usage percentages
    local used=$((total - free))
    local usage_percent=$((used * 100 / total))

    echo "Memory Analysis:"
    echo "  Total: ${total}kB"
    echo "  Used: ${used}kB (${usage_percent}%)"
    echo "  Free: ${free}kB"
    echo "  Available: ${available}kB"
    echo "  Buffers: ${buffers}kB"
    echo "  Cached: ${cached}kB"
}

# Real-time memory monitoring
monitor_memory() {
    local interval="${1:-5}"

    while true; do
        clear
        echo "=== Memory Monitor ==="
        echo "Updated: $(date)"
        echo
        analyze_memory
        echo
        echo "Press Ctrl+C to stop"
        sleep "$interval"
    done
}

🧠 Virtual Filesystem Features

/sys Filesystem

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Hardware information via sysfs
ls /sys/class/  # Device classes

# CPU information
ls /sys/devices/system/cpu/
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

# Block devices
ls /sys/block/
cat /sys/block/sda/size

# Network devices
ls /sys/class/net/
cat /sys/class/net/eth0/address

/dev Filesystem

1
2
3
4
5
6
7
8
9
# Device files
ls -la /dev/sd*   # Storage devices
ls -la /dev/tty*  # Terminal devices
ls -la /dev/pts/* # Pseudo-terminals

# Device management
ls -la /dev/disk/by-id/    # Devices by ID
ls -la /dev/disk/by-label/ # Devices by label
ls -la /dev/disk/by-path/  # Devices by path

tmpfs and Other Virtual Filesystems

1
2
3
4
5
6
7
8
9
# tmpfs usage
df -h | grep tmpfs

# Create tmpfs mount
sudo mount -t tmpfs -o size=100M tmpfs /mnt/temp

# RAM disk creation
sudo mkdir /mnt/ramdisk
sudo mount -t ramfs ramfs /mnt/ramdisk

🧪 Advanced /proc Operations

Process Memory Maps

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Memory mapping information
show_memory_maps() {
    local pid="$1"
    local maps_file="/proc/$pid/maps"

    if [ ! -f "$maps_file" ]; then
        echo "Process $pid maps not found" >&2
        return 1
    fi

    echo "Memory Maps for PID $pid:"
    echo "Address           Perms Offset  Dev   Inode Path"
    echo "=================================================="

    while IFS= read -r line; do
        # Parse map entry
        local address=$(echo "$line" | awk '{print $1}')
        local perms=$(echo "$line" | awk '{print $2}')
        local offset=$(echo "$line" | awk '{print $3}')
        local dev=$(echo "$line" | awk '{print $4}')
        local inode=$(echo "$line" | awk '{print $5}')
        local path=$(echo "$line" | awk '{for(i=6;i<=NF;i++) printf "%s ", $i; print ""}' | sed 's/ $//')

        printf "%-17s %-5s %-7s %-5s %-5s %s\n" \
            "$address" "$perms" "$offset" "$dev" "$inode" "$path"
    done < "$maps_file"
}

Process File Descriptors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File descriptor analysis
analyze_fds() {
    local pid="$1"
    local fd_dir="/proc/$pid/fd"

    if [ ! -d "$fd_dir" ]; then
        echo "Process $pid FDs not found" >&2
        return 1
    fi

    echo "File Descriptors for PID $pid:"
    echo "FD Type        Target"
    echo "========================"

    for fd in "$fd_dir"/*; do
        if [ -L "$fd" ]; then
            local fd_num=$(basename "$fd")
            local target=$(readlink "$fd" 2>/dev/null || echo "unknown")

            # Determine FD type
            local fd_type="unknown"
            if echo "$target" | grep -q "^pipe:"; then
                fd_type="pipe"
            elif echo "$target" | grep -q "^socket:"; then
                fd_type="socket"
            elif echo "$target" | grep -q "^anon_inode:"; then
                fd_type="anon_inode"
            elif [ -f "$target" ]; then
                fd_type="file"
            elif [ -d "$target" ]; then
                fd_type="directory"
            fi

            printf "%-2s %-10s %s\n" "$fd_num" "$fd_type" "$target"
        fi
    done
}

Network Statistics

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Network connection analysis
analyze_connections() {
    local net_tcp="/proc/net/tcp"
    local net_udp="/proc/net/udp"

    echo "TCP Connections:"
    echo "Local Address          Foreign Address        State      PID/Program"
    echo "=================================================================="

    # Parse TCP connections
    tail -n +2 "$net_tcp" | while read -r line; do
        local local_addr=$(echo "$line" | awk '{print $2}')
        local remote_addr=$(echo "$line" | awk '{print $3}')
        local state=$(echo "$line" | awk '{print $4}')

        # Convert hex addresses to dotted notation
        local local_ip=$(printf "%d.%d.%d.%d" \
            $((0x$(echo "$local_addr" | cut -d: -f1 | cut -c7-8))) \
            $((0x$(echo "$local_addr" | cut -d: -f1 | cut -c5-6))) \
            $((0x$(echo "$local_addr" | cut -d: -f1 | cut -c3-4))) \
            $((0x$(echo "$local_addr" | cut -d: -f1 | cut -c1-2))))
        local local_port=$((0x$(echo "$local_addr" | cut -d: -f2)))

        local remote_ip=$(printf "%d.%d.%d.%d" \
            $((0x$(echo "$remote_addr" | cut -d: -f1 | cut -c7-8))) \
            $((0x$(echo "$remote_addr" | cut -d: -f1 | cut -c5-6))) \
            $((0x$(echo "$remote_addr" | cut -d: -f1 | cut -c3-4))) \
            $((0x$(echo "$remote_addr" | cut -d: -f1 | cut -c1-2))))
        local remote_port=$((0x$(echo "$remote_addr" | cut -d: -f2)))

        # Map state to readable format
        local state_name="UNKNOWN"
        case "$state" in
            01) state_name="ESTABLISHED" ;;
            02) state_name="SYN_SENT" ;;
            03) state_name="SYN_RECV" ;;
            04) state_name="FIN_WAIT1" ;;
            05) state_name="FIN_WAIT2" ;;
            06) state_name="TIME_WAIT" ;;
            07) state_name="CLOSE" ;;
            08) state_name="CLOSE_WAIT" ;;
            09) state_name="LAST_ACK" ;;
            0A) state_name="LISTEN" ;;
            0B) state_name="CLOSING" ;;
        esac

        printf "%-15s:%-5d %-15s:%-5d %-10s\n" \
            "$local_ip" "$local_port" "$remote_ip" "$remote_port" "$state_name"
    done
}

🧠 Linux-Specific Filesystem Semantics

Extended Attributes and ACLs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Extended attributes management
manage_xattrs() {
    local file="$1"

    echo "Extended Attributes for $file:"

    # List all extended attributes
    if command -v getfattr >/dev/null 2>&1; then
        getfattr --dump "$file"
    else
        echo "getfattr not available"
    fi

    # Set custom attribute
    if command -v setfattr >/dev/null 2>&1; then
        setfattr -n user.description -v "Sample file" "$file" 2>/dev/null && \
            echo "Set user.description attribute"
    fi
}

# ACL management
manage_acls() {
    local file="$1"

    echo "ACLs for $file:"

    # List ACLs
    if command -v getfacl >/dev/null 2>&1; then
        getfacl "$file"
    else
        echo "getfacl not available"
    fi

    # Set ACL
    if command -v setfacl >/dev/null 2>&1; then
        setfacl -m u:nobody:rx "$file" 2>/dev/null && \
            echo "Added ACL for nobody user"
    fi
}

Capabilities System

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# File capabilities management
manage_capabilities() {
    local file="$1"

    echo "Capabilities for $file:"

    # View capabilities
    if command -v getcap >/dev/null 2>&1; then
        getcap "$file"
    else
        echo "getcap not available"
    fi

    # Set capabilities (requires root)
    if [ "$(id -u)" -eq 0 ] && command -v setcap >/dev/null 2>&1; then
        # Example: allow binding to privileged ports
        setcap cap_net_bind_service=+ep "$file" 2>/dev/null && \
            echo "Set CAP_NET_BIND_SERVICE capability"
    fi
}

Inode and Filesystem Information

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Detailed file information
detailed_file_info() {
    local file="$1"

    echo "Detailed Information for $file:"
    echo "================================"

    # Standard stat information
    stat "$file"

    echo
    echo "Inode Information:"

    # Inode details via stat command
    local inode=$(stat -c %i "$file")
    local device=$(stat -c %d "$file")
    local links=$(stat -c %h "$file")

    echo "  Inode: $inode"
    echo "  Device: $device"
    echo "  Links: $links"

    # Access /proc/self/fd to see file descriptor info
    if [ -e "$file" ]; then
        local fd_info=$(ls -la /proc/self/fd/ | grep "$(basename "$file")")
        if [ -n "$fd_info" ]; then
            echo "  FD Info: $fd_info"
        fi
    fi
}

🧪 Monitoring and Debugging Tools

Process Monitoring Scripts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Advanced process monitor
advanced_process_monitor() {
    local pid="$1"
    local interval="${2:-1}"

    if [ ! -d "/proc/$pid" ]; then
        echo "Process $pid not found" >&2
        return 1
    fi

    echo "Monitoring PID $pid (Ctrl+C to stop)"
    echo

    while [ -d "/proc/$pid" ]; do
        clear
        echo "=== Process Monitor: PID $pid ==="
        echo "Time: $(date)"
        echo

        # Process status
        echo "--- Status ---"
        grep -E "^(Name|State|Pid|PPid|Threads|VmSize|VmRSS| voluntary|nonvoluntary)" "/proc/$pid/status" 2>/dev/null || echo "Status info unavailable"

        echo
        echo "--- I/O Stats ---"
        if [ -f "/proc/$pid/io" ]; then
            cat "/proc/$pid/io"
        else
            echo "I/O stats unavailable"
        fi

        echo
        echo "--- File Descriptors ---"
        ls -la "/proc/$pid/fd" 2>/dev/null | head -10 || echo "FD info unavailable"

        sleep "$interval"
    done

    echo "Process $pid terminated"
}

System Resource Analysis

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Comprehensive system analysis
system_analysis() {
    echo "=== Linux System Analysis ==="
    echo "Timestamp: $(date)"
    echo "Host: $(hostname)"
    echo "Kernel: $(uname -r)"
    echo

    echo "--- CPU Information ---"
    lscpu | head -10

    echo
    echo "--- Memory Information ---"
    free -h

    echo
    echo "--- Disk Usage ---"
    df -h | head -10

    echo
    echo "--- Top Processes ---"
    ps aux --sort=-%cpu | head -10

    echo
    echo "--- Network Interfaces ---"
    ip addr show | grep -E "(^[0-9]|inet )" | head -10

    echo
    echo "--- Load Average ---"
    cat /proc/loadavg

    echo
    echo "--- Uptime ---"
    uptime
}

🧾 Linux Filesystem Advantages

Linux's /proc and virtual filesystem features provide:

Unique Capabilities

  • Real-time process introspection - Detailed runtime information
  • Hardware abstraction - Unified device interface
  • Dynamic configuration - Runtime system tuning
  • Performance monitoring - Comprehensive metrics collection
  • Security auditing - Process and system monitoring

Enterprise Benefits

  • Troubleshooting - Deep system diagnostics
  • Automation - Programmatic system management
  • Monitoring - Continuous health assessment
  • Compliance - Audit trail generation
  • Optimization - Performance tuning capabilities

Developer Advantages

  • System programming - Low-level access APIs
  • Debugging - Process and memory analysis
  • Instrumentation - Custom monitoring solutions
  • Integration - Seamless toolchain incorporation
  • Innovation - Advanced feature utilization

👉 Continue to: Linux Init Systems and Services