getCachedProcessList returns cached ps output or refreshes if older than 5 seconds
()
| 522 | |
| 523 | // getCachedProcessList returns cached ps output or refreshes if older than 5 seconds |
| 524 | func getCachedProcessList() []string { |
| 525 | psCache.mutex.RLock() |
| 526 | cacheAge := time.Since(psCache.timestamp) |
| 527 | hasValidCache := len(psCache.lines) > 0 && cacheAge < 5*time.Second |
| 528 | if hasValidCache { |
| 529 | cachedLines := make([]string, len(psCache.lines)) |
| 530 | copy(cachedLines, psCache.lines) |
| 531 | psCache.mutex.RUnlock() |
| 532 | return cachedLines |
| 533 | } |
| 534 | psCache.mutex.RUnlock() |
| 535 | |
| 536 | // Cache miss or expired - refresh the cache |
| 537 | psCache.mutex.Lock() |
| 538 | defer psCache.mutex.Unlock() |
| 539 | |
| 540 | // Double-check in case another goroutine refreshed while we were waiting |
| 541 | cacheAge = time.Since(psCache.timestamp) |
| 542 | if len(psCache.lines) > 0 && cacheAge < 5*time.Second { |
| 543 | cachedLines := make([]string, len(psCache.lines)) |
| 544 | copy(cachedLines, psCache.lines) |
| 545 | return cachedLines |
| 546 | } |
| 547 | |
| 548 | // Execute ps command to refresh cache |
| 549 | cmd := exec.Command("ps", "-eo", "pgid,lstart,args") |
| 550 | var out bytes.Buffer |
| 551 | cmd.Stdout = &out |
| 552 | |
| 553 | if err := cmd.Run(); err != nil { |
| 554 | // Return empty cache on error, don't update timestamp so next call will retry |
| 555 | return []string{} |
| 556 | } |
| 557 | |
| 558 | // Parse and cache the output |
| 559 | output := out.String() |
| 560 | psCache.lines = strings.Split(output, "\n") |
| 561 | psCache.timestamp = time.Now() |
| 562 | |
| 563 | // Return a copy to avoid external modifications |
| 564 | cachedLines := make([]string, len(psCache.lines)) |
| 565 | copy(cachedLines, psCache.lines) |
| 566 | return cachedLines |
| 567 | } |
| 568 | |
| 569 | // Simple cache to prevent re-parsing unchanged crontab files |
| 570 | type crontabCache struct { |