5

I need to start and restart a custom web server on travis. Starting in background is fine using a sub-shell (.travis.yml):

- if [ "$TEST_ADAPTER" = "HTTP" ]; then (vendor/bin/httpd.php start &); fi

To stop/kill the process again I'm trying to get its PID and then kill it:

- if [ "$TEST_ADAPTER" = "HTTP" ]; then (vendor/bin/httpd.php start &) && SERVER_PID=$!; fi
- ...
- if [ "$TEST_ADAPTER" = "HTTP" ]; then kill -9 $SERVER_PID && ...; fi

However, SERVER_PID is empty.

What is the right way to obtain the PID of a background process on travis in order to stop it (complication: without using an additional shell script)?

andig
  • 13,378
  • 13
  • 61
  • 98

2 Answers2

9

Answering question here as @xmonk's answer is correct in terms of functionality but requires an external shell script which- in turn- would need to use a temp file to write the pid value to.

I've just found out that travis-ci does actually allow multi-line statements which simplified the whole thing. Put this in .travis.yml:

- |
  if [ "$TEST_ADAPTER" = "HTTP" ]; then
    vendor/bin/httpd.php&
    SERVER_PID=$!
  fi
andig
  • 13,378
  • 13
  • 61
  • 98
  • After this, you can use `- kill $SERVER_PID` in a separate step. The variable `$SERVER_PID` will be preserved across steps. – Mr-IDE Oct 02 '18 at 01:38
3

The following should work:

if [ "$TEST_ADAPTER" = "HTTP" ]; then
    vendor/bin/httpd.php&
    SERVER_PID=$!
fi

The () surrounding the command, creates a sub-shell. The $! comes empty in your examples, because the program is running in the sub-shell, but your $! is running on the parent shell.

xmonk
  • 535
  • 6
  • 13
  • As far as I know I can't write multi-lien statements in travis.yml https://groups.google.com/forum/#!topic/travis-ci/uaAP9zEdiCg – andig Apr 22 '15 at 16:14
  • Right, but you can put the above in a shell script, and run that script from your .travis.yml file. – xmonk Apr 22 '15 at 16:35
  • You can write multi-line statements in Travis CI YAML using the `|` multiline operator, see: https://www.jeffgeerling.com/blog/2017/bash-logic-structures-and-conditionals-if-case-loops-etc-travis-ci – geerlingguy Apr 11 '18 at 20:26