• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Utilities used with Brillo hosts."""
6
7_RUN_BACKGROUND_TEMPLATE = '( %(cmd)s ) </dev/null >/dev/null 2>&1 & echo -n $!'
8
9_WAIT_CMD_TEMPLATE = """\
10to=%(timeout)d; \
11while test ${to} -ne 0; do \
12  test $(ps %(pid)d | wc -l) -gt 1 || break; \
13  sleep 1; \
14  to=$((to - 1)); \
15done; \
16test ${to} -ne 0 -o $(ps %(pid)d | wc -l) -eq 1 \
17"""
18
19
20def run_in_background(host, cmd):
21    """Runs a command in the background on the DUT.
22
23    @param host: A host object representing the DUT.
24    @param cmd: The command to run.
25
26    @return The background process ID (integer).
27    """
28    background_cmd = _RUN_BACKGROUND_TEMPLATE % {'cmd': cmd}
29    return int(host.run_output(background_cmd).strip())
30
31
32def wait_for_process(host, pid, timeout=-1):
33    """Waits for a process on the DUT to terminate.
34
35    @param host: A host object representing the DUT.
36    @param pid: The process ID (integer).
37    @param timeout: Number of seconds to wait; default is wait forever.
38
39    @return True if process terminated within the alotted time, False otherwise.
40    """
41    wait_cmd = _WAIT_CMD_TEMPLATE % {'pid': pid, 'timeout': timeout}
42    return host.run(wait_cmd, ignore_status=True).exit_status == 0
43