Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crit: add FindPs method on PsTree #145

Merged
merged 1 commit into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}