/** * Process Management Demo Page * Demonstrates subprocess utilities for running background tasks */ import { useState } from 'react'; import { Link } from 'react-router-dom'; interface ProcessInfo { id: string; status: 'running' | 'completed' | 'failed'; command: string; startedAt: string; output?: string; exitCode?: number; } export default function ProcessManagementDemo() { const [processes, setProcesses] = useState([]); const [command, setCommand] = useState('echo "Hello from subprocess!"'); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const handleRunProcess = async () => { setLoading(true); setError(null); // Simulate running a process (in real app, this would call the backend API) const newProcess: ProcessInfo = { id: Date.now().toString(), status: 'running', command, startedAt: new Date().toISOString(), }; setProcesses(prev => [newProcess, ...prev]); // Simulate process completion after 2 seconds setTimeout(() => { setProcesses(prev => prev.map(p => p.id === newProcess.id ? { ...p, status: 'completed', output: command.startsWith('echo') ? command.replace(/^echo\s+["']?(.*)["']?$/, '$1') : `Executed: ${command}`, exitCode: 0 } : p )); }, 2000); setLoading(false); }; const handleKillProcess = (id: string) => { setProcesses(prev => prev.map(p => p.id === id ? { ...p, status: 'failed', output: 'Process killed by user' } : p )); }; const clearHistory = () => { setProcesses([]); }; return (
← Back to Home

Process Management Demo

Subprocess utilities for running background tasks and scripts.

{/* Run Process */}

Run Process

setCommand(e.target.value)} className="input font-mono text-sm" placeholder="Enter command to run..." />
{processes.length > 0 && ( )}
{error && (
{error}
)}
{/* Process List */} {processes.length > 0 && (

Process History

{processes.map((process) => (
{process.status} {process.exitCode !== undefined && ( (exit code: {process.exitCode}) )}
{process.status === 'running' && ( )}
$ {process.command} {process.output && (
                      {process.output}
                    
)}
Started: {new Date(process.startedAt).toLocaleTimeString()}
))}
)} {/* Process Manager Code Examples */}

Process Manager API

ProcessManager Class

{`import { spawn, ChildProcess } from 'child_process';
import { EventEmitter } from 'events';

export class ProcessManager extends EventEmitter {
  private processes: Map = new Map();

  async run(command: string, options?: SpawnOptions): Promise {
    const id = crypto.randomUUID();
    const [cmd, ...args] = command.split(' ');

    const child = spawn(cmd, args, {
      shell: true,
      ...options,
    });

    this.processes.set(id, child);

    return new Promise((resolve, reject) => {
      let stdout = '';
      let stderr = '';

      child.stdout?.on('data', (data) => {
        stdout += data;
        this.emit('stdout', { id, data: data.toString() });
      });

      child.stderr?.on('data', (data) => {
        stderr += data;
        this.emit('stderr', { id, data: data.toString() });
      });

      child.on('close', (code) => {
        this.processes.delete(id);
        resolve({ id, code, stdout, stderr });
      });

      child.on('error', (error) => {
        this.processes.delete(id);
        reject(error);
      });
    });
  }

  kill(id: string): boolean {
    const process = this.processes.get(id);
    if (process) {
      process.kill('SIGTERM');
      return true;
    }
    return false;
  }

  killAll(): void {
    for (const [id, process] of this.processes) {
      process.kill('SIGTERM');
      this.processes.delete(id);
    }
  }
}`}
              

Streaming Output with SSE

{`// Server-side: Stream process output
app.get('/api/process/:id/stream', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const processId = req.params.id;

  processManager.on('stdout', ({ id, data }) => {
    if (id === processId) {
      res.write(\`data: \${JSON.stringify({ type: 'stdout', data })}\\n\\n\`);
    }
  });

  processManager.on('stderr', ({ id, data }) => {
    if (id === processId) {
      res.write(\`data: \${JSON.stringify({ type: 'stderr', data })}\\n\\n\`);
    }
  });
});

// Client-side: Consume SSE stream
const eventSource = new EventSource(\`/api/process/\${id}/stream\`);

eventSource.onmessage = (event) => {
  const { type, data } = JSON.parse(event.data);
  console.log(\`[\${type}] \${data}\`);
};`}
              

Express Routes

{`import { Router } from 'express';
import { ProcessManager } from '../lib/process-manager';

const router = Router();
const processManager = new ProcessManager();

// Run a new process
router.post('/run', async (req, res) => {
  try {
    const { command, cwd, env } = req.body;
    const result = await processManager.run(command, { cwd, env });
    res.json({ success: true, ...result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Kill a running process
router.post('/:id/kill', (req, res) => {
  const killed = processManager.kill(req.params.id);
  res.json({ success: killed });
});

// List active processes
router.get('/active', (req, res) => {
  res.json({ processes: processManager.getActiveProcesses() });
});

export default router;`}
              
{/* Use Cases */}

Common Use Cases

Build Automation

  • - Running npm/yarn scripts
  • - Compiling TypeScript
  • - Building Docker images
  • - Running tests

Data Processing

  • - Image/video transcoding
  • - PDF generation
  • - File conversion
  • - Batch operations

System Integration

  • - Git operations
  • - Database backups
  • - Log rotation
  • - Cron-like scheduled tasks

AI/ML Workflows

  • - Running Python scripts
  • - Model training jobs
  • - Data preprocessing
  • - Inference pipelines
); }