Skip to content

Commit

Permalink
Merge pull request #145 from behouba/find-ps-method
Browse files Browse the repository at this point in the history
crit: add `FindPs` method on `PsTree`
  • Loading branch information
rst0git committed Aug 3, 2023
2 parents 7e6c665 + 1cd3730 commit a74ef62
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
14 changes: 14 additions & 0 deletions crit/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,17 @@ func getUnixSkFilePath(dir string, file *fdinfo.FileEntry, fID uint32) (string,

return "unix[?]", nil
}

// FindPs performs a short-circuiting depth-first search to find
// a process with a given PID in a process tree.
func (ps *PsTree) FindPs(pid uint32) *PsTree {
if ps.PID == pid {
return ps
}
for _, child := range ps.Children {
if process := child.FindPs(pid); process != nil {
return process
}
}
return nil
}
45 changes: 45 additions & 0 deletions crit/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package crit

import (
"testing"
)

func TestFindPs(t *testing.T) {
root := &PsTree{
PID: 1,
Children: []*PsTree{
{
PID: 2,
Children: []*PsTree{
{
PID: 3,
},
},
},
{
PID: 4,
Children: []*PsTree{
{
PID: 5,
},
},
},
},
}

// Test Case 1: Find an existing process with a valid PID
ps := root.FindPs(3)
if ps == nil {
t.Errorf("FindPs(3) returned nil, expected a valid process")
}
if ps != nil && ps.PID != 3 {
t.Errorf("FindPs(3) returned a process with PID %d, expected 3", ps.PID)
}

// Test Case 2: Find a non-existing process with an invalid PID
nonExistentPID := uint32(999)
notFoundProcess := root.FindPs(nonExistentPID)
if notFoundProcess != nil {
t.Errorf("FindPs(%d) returned a process, expected nil", nonExistentPID)
}
}

0 comments on commit a74ef62

Please sign in to comment.