github.com/Lephar/snapd@v0.0.0-20210825215435-c7fba9cef4d2/sandbox/cgroup/pids.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2019-2020 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package cgroup
    21  
    22  import (
    23  	"bufio"
    24  	"fmt"
    25  	"io"
    26  	"os"
    27  	"strconv"
    28  )
    29  
    30  // pidsInFile returns the list of process IDs in a given file.
    31  func pidsInFile(fname string) ([]int, error) {
    32  	file, err := os.Open(fname)
    33  	if os.IsNotExist(err) {
    34  		return nil, nil
    35  	}
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	defer file.Close()
    40  	return parsePids(bufio.NewReader(file))
    41  }
    42  
    43  // parsePids parses a list of pids, one per line, from a reader.
    44  func parsePids(reader io.Reader) ([]int, error) {
    45  	scanner := bufio.NewScanner(reader)
    46  	var pids []int
    47  	for scanner.Scan() {
    48  		s := scanner.Text()
    49  		pid, err := parsePid(s)
    50  		if err != nil {
    51  			return nil, err
    52  		}
    53  		pids = append(pids, pid)
    54  	}
    55  	if err := scanner.Err(); err != nil {
    56  		return nil, err
    57  	}
    58  	return pids, nil
    59  }
    60  
    61  // parsePid parses a string as a process identifier.
    62  func parsePid(text string) (int, error) {
    63  	pid, err := strconv.Atoi(text)
    64  	if err != nil || (err == nil && pid <= 0) {
    65  		return 0, fmt.Errorf("cannot parse pid %q", text)
    66  	}
    67  	return pid, err
    68  }