@@ -1232,26 +1232,26 @@ func (h *HeadscaleInContainer) writePolicy(pol *policyv2.Policy) error {
12321232}
12331233
12341234func (h * HeadscaleInContainer ) PID () (int , error ) {
1235- cmd := []string {"bash" , "-c" , `ps aux | grep headscale | grep -v grep | awk '{print $2}'` }
1236- output , err := h .Execute (cmd )
1235+ // Use pidof to find the headscale process, which is more reliable than grep
1236+ // as it only looks for the actual binary name, not processes that contain
1237+ // "headscale" in their command line (like the dlv debugger).
1238+ output , err := h .Execute ([]string {"pidof" , "headscale" })
12371239 if err != nil {
1238- return 0 , fmt .Errorf ("failed to execute command: %w" , err )
1240+ // pidof returns exit code 1 when no process is found
1241+ return 0 , os .ErrNotExist
12391242 }
12401243
1241- lines := strings .TrimSpace (output )
1242- if lines == "" {
1243- return 0 , os .ErrNotExist // No output means no process found
1244+ // pidof returns space-separated PIDs on a single line
1245+ pidStrs := strings .Fields (strings .TrimSpace (output ))
1246+ if len (pidStrs ) == 0 {
1247+ return 0 , os .ErrNotExist
12441248 }
12451249
1246- pids := make ([]int , 0 , len (lines ))
1247- for _ , line := range strings .Split (lines , "\n " ) {
1248- line = strings .TrimSpace (line )
1249- if line == "" {
1250- continue
1251- }
1252- pidInt , err := strconv .Atoi (line )
1250+ pids := make ([]int , 0 , len (pidStrs ))
1251+ for _ , pidStr := range pidStrs {
1252+ pidInt , err := strconv .Atoi (pidStr )
12531253 if err != nil {
1254- return 0 , fmt .Errorf ("parsing PID: %w" , err )
1254+ return 0 , fmt .Errorf ("parsing PID %q : %w" , pidStr , err )
12551255 }
12561256 // We dont care about the root pid for the container
12571257 if pidInt == 1 {
@@ -1266,7 +1266,9 @@ func (h *HeadscaleInContainer) PID() (int, error) {
12661266 case 1 :
12671267 return pids [0 ], nil
12681268 default :
1269- return 0 , errors .New ("multiple headscale processes running" )
1269+ // If we still have multiple PIDs, return the first one as a fallback
1270+ // This can happen in edge cases during startup/shutdown
1271+ return pids [0 ], nil
12701272 }
12711273}
12721274
0 commit comments