惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cisco Talos Blog
Cisco Talos Blog
P
Privacy & Cybersecurity Law Blog
I
Intezer
Y
Y Combinator Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
Netflix TechBlog - Medium
The Hacker News
The Hacker News
AWS News Blog
AWS News Blog
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Stack Overflow Blog
Stack Overflow Blog
Hacker News: Ask HN
Hacker News: Ask HN
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
B
Blog
T
Tor Project blog
C
Cybersecurity and Infrastructure Security Agency CISA
云风的 BLOG
云风的 BLOG
博客园_首页
V2EX - 技术
V2EX - 技术
T
Threat Research - Cisco Blogs
腾讯CDC
宝玉的分享
宝玉的分享
博客园 - 叶小钗
罗磊的独立博客
S
Securelist
The Last Watchdog
The Last Watchdog
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
博客园 - 司徒正美
W
WeLiveSecurity
有赞技术团队
有赞技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Secure Thoughts
NISL@THU
NISL@THU
N
News and Events Feed by Topic
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
IT之家
IT之家

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
TIL: lsof for Process Scanning and Advanced kill Command Usage
2020-11-03 · via Stonecharioteer on Tech

Today I discovered powerful Unix tools for process investigation and management that make system debugging much more efficient and safer.

Using lsof to Scan Processes by Path

The lsof (list open files) command can identify processes that are using files in a specific directory path, which is invaluable for debugging and system maintenance.

Basic lsof Path Scanning:

Find Processes Using a Directory:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# See all processes accessing files in /var/log
lsof +D /var/log

# More efficient for large directories (doesn't recurse)
lsof +d /var/log

# Find processes with files open in current directory
lsof +d .

# Find processes using any files under /home/user
lsof +D /home/user

Practical Use Cases:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Before unmounting a filesystem
lsof +D /mnt/external-drive

# Debug why a directory can't be deleted
lsof +D /tmp/app-cache

# Find processes preventing package updates
lsof +D /usr/lib/myapp

# Identify processes holding log files open
lsof +D /var/log/myapp

Advanced lsof Usage:

Combine with Other Filters:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Processes in path owned by specific user
lsof +D /home/user -u user

# Network connections from processes in specific path
lsof +D /opt/myapp -i

# Find processes with deleted files still open
lsof +D /var/lib/myapp | grep '(deleted)'

# Monitor real-time file access
lsof +D /var/log -r 2  # refresh every 2 seconds

Output Interpretation:

1
2
3
4
# lsof output columns explained
$ lsof +d /tmp
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF   NODE NAME
chrome   1234 user   15u   REG    8,1    12345  67890 /tmp/temp_file
  • COMMAND: Process name
  • PID: Process ID
  • USER: Process owner
  • FD: File descriptor (15u = file descriptor 15, read/write)
  • TYPE: File type (REG = regular file, DIR = directory)
  • DEVICE: Device identifier
  • SIZE/OFF: File size or offset
  • NODE: Inode number
  • NAME: Full path to file

Troubleshooting Scenarios:

“Device or resource busy” Errors:

1
2
3
4
5
6
7
8
9
# Can't unmount filesystem
umount: /mnt/data: device is busy.

# Find the culprit
lsof +D /mnt/data
# Shows processes still accessing files on the mounted filesystem

# Alternative approach
fuser -v /mnt/data  # Shows processes using the mount point

Disk Space Issues:

1
2
3
4
5
# Find processes with large deleted files still open
lsof +D /var/log | grep deleted | sort -k7 -nr

# Find processes writing to a specific directory
lsof +D /var/log -a -w  # -a = AND, -w = write access only

Advanced kill Command with Verbose Signals

The kill command accepts human-readable signal names, making process management safer and more self-documenting.

Verbose Signal Usage:

Common Readable Signals:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# Graceful termination (allows cleanup)
kill -TERM 1234
kill -SIGTERM 1234

# Force termination (immediate, no cleanup)
kill -KILL 1234
kill -SIGKILL 1234

# Stop/pause process (can be resumed)
kill -STOP 1234
kill -TSTP 1234   # Terminal stop (Ctrl+Z equivalent)

# Resume stopped process
kill -CONT 1234
kill -SIGCONT 1234

# Reload configuration (common in daemons)
kill -HUP 1234
kill -SIGHUP 1234

Advanced Signal Management:

 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
# Check if process is running (signal 0 doesn't affect process)
if kill -0 1234 2>/dev/null; then
    echo "Process 1234 is running"
else
    echo "Process 1234 is not running"
fi

# Graceful restart script
graceful_restart() {
    local pid=$1

    echo "Sending TERM signal to process $pid"
    kill -TERM $pid

    # Wait up to 10 seconds for graceful shutdown
    for i in {1..10}; do
        if ! kill -0 $pid 2>/dev/null; then
            echo "Process terminated gracefully"
            return 0
        fi
        sleep 1
    done

    echo "Process didn't terminate gracefully, forcing..."
    kill -KILL $pid
}

Combining lsof and kill:

Advanced Process Management:

 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
# Kill all processes using files in a directory
lsof +D /path/to/app | awk 'NR>1 {print $2}' | sort -u | xargs kill -TERM

# More precise version with error handling
kill_processes_in_path() {
    local path=$1
    local signal=${2:-TERM}

    echo "Finding processes using files in $path"
    local pids=$(lsof +D "$path" 2>/dev/null | awk 'NR>1 {print $2}' | sort -u)

    if [ -z "$pids" ]; then
        echo "No processes found using files in $path"
        return 0
    fi

    echo "Found processes: $pids"
    echo "Sending $signal signal..."

    for pid in $pids; do
        if kill -0 "$pid" 2>/dev/null; then
            echo "Killing process $pid"
            kill -"$signal" "$pid"
        fi
    done
}

# Usage
kill_processes_in_path /opt/myapp TERM

Service Management Patterns:

 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
# Safe service restart
restart_service() {
    local service_path=$1

    # Find main process
    local main_pid=$(pgrep -f "$service_path/bin/main")

    if [ -n "$main_pid" ]; then
        echo "Stopping service (PID: $main_pid)"
        kill -TERM "$main_pid"

        # Wait and verify
        sleep 5
        if kill -0 "$main_pid" 2>/dev/null; then
            echo "Service didn't stop gracefully, forcing..."
            kill -KILL "$main_pid"
        fi
    fi

    # Clean up any remaining processes
    lsof +D "$service_path" | awk 'NR>1 {print $2}' | sort -u | while read pid; do
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            echo "Cleaning up remaining process: $pid"
            kill -TERM "$pid"
        fi
    done
}

These tools provide powerful capabilities for system administration, debugging, and process management, making it easier to understand what processes are doing and manage them safely.