You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用GDB为运行中的Node.js进程生成Core Dump(内存溢出场景)

How to Generate a Core Dump for the Current Node.js Process in a Container (Without System/Kernel Commands)

Absolutely, you can generate a core dump for your running Node.js process directly from within the process itself—let's fix your approach and get this working.

Why Your Current Code Fails

Your existing code throws errors because when you spawn gdb with ['generate-core-file'], GDB misinterprets that argument as an executable file to load (which doesn't exist). To create a core dump for your Node.js process, you first need to tell GDB to attach to your running process, then execute the core dump command.

Corrected Code Implementation

Here's the revised code that properly uses GDB to generate a core dump for your Node.js process:

const spawnProcess = require('spawn-process');
const express = require('express')
const app = express()
const port = 3000

app.get('/', async (req, res) => {
  const currentPid = process.pid;
  console.log(`Initiating core dump for PID ${currentPid}`);

  try {
    // Spawn GDB with batch commands to attach and generate core dump
    await spawnProcess('gdb', [
      '--batch',               // Run in non-interactive mode (no user input needed)
      `-p ${currentPid}`,      // Attach to our running Node.js process
      `-ex generate-core-file`,// Execute core dump generation
      `-ex detach`,            // Detach from the process so it keeps running
      `-ex quit`               // Exit GDB cleanly
    ], {
      stdio: ['ignore', process.stdout, process.stderr], // Avoid blocking on stdin
    });
    console.log('Core dump generated successfully (file: core)');
  } catch (err) {
    console.error('Failed to generate core dump:', err);
  }

  res.send('Core dump initiated!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Key GDB Command Explanations

  • --batch: Runs GDB in automated mode, so it exits once all commands are executed (no manual interaction required).
  • -p ${currentPid}: Targets your Node.js process by its PID (retrieved via Node.js's built-in process.pid).
  • -ex generate-core-file: Triggers the core dump creation (the resulting file is named core by default in your working directory).
  • -ex detach: Ensures GDB releases the Node.js process, so it continues running after the core dump is saved.
  • -ex quit: Closes GDB cleanly after the task is done.

Critical Container Permission Fix

In a container environment, you need to grant the process permission to use ptrace (required for GDB to attach to a process). When starting your container, add the SYS_PTRACE capability:

docker run --cap-add=SYS_PTRACE your-node-container-image

Without this, GDB will throw a ptrace: Operation not permitted error.

Alternative: Heap Snapshots for Memory Issues

If you're specifically debugging memory leaks (rather than low-level process crashes), Node.js's built-in inspector can generate heap snapshots (lighter than full core dumps):

const inspector = require('inspector');
const fs = require('fs');

async function takeHeapSnapshot() {
  const session = new inspector.Session();
  session.connect();
  const snapshot = await new Promise((resolve, reject) => {
    session.post('HeapProfiler.takeHeapSnapshot', (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
  fs.writeFileSync('memory-heap-snapshot.heapsnapshot', JSON.stringify(snapshot));
  session.disconnect();
}

This creates a file you can analyze in Chrome DevTools' Memory tab.

内容的提问来源于stack exchange,提问作者Raz Ronen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:37:41