Search code examples
bashshellunixnpmjobs

Running background process (webserver) for just as long as other process (test suite) executes


I'm looking for a unix shell command that would allow me to run a process in the background (which happens to be a webserver) for just as long as another foreground process (which happens to be a test suite) executes. I.e, after the foreground process exits, the background process should exit as well. What I have so far is

.. preliminary work .. && (webserver & test)

which comes close, but fails in that the webserver process never exits. Is there a good way to express this in a single command or would it be more reasonable to write a more verbose script for that?


To give some further detail (and welcoming any relevant suggestions), I'm in the process of writing a javascript lib which I'd like to test using Selenium - hence the need for the webserver to execute 'alongside' the test suite. And in my attempt to do away with Grunt & co. and follow a leaner, npm-based approach to task management I've hit this shell-related road bump.


Solution

  • You can try this:

    # .. preliminary work ..
    webserver &
    PID=$!
    test_suite &
    (wait $!; kill $PID)
    

    This will work as long as you don't mind both commands being run in the background. What happens here is:

    1. The webserver is started in the background.
    2. The pid of it is assigned to $PID.
    3. The test suite is started in the background.
    4. The last line waits for the test suite to exit, and then kills the webserver.

    If you need either command to be in the foreground, then run this version

    # .. preliminary work ..
    screen -dm -S webserver webserver
    screen -dm -S test_suite test_suite
    (wait "$(screen -ls | awk '/\.test_suite\t/ {print strtonum($1)}')"
    screen -X -S webserver -p 0 kill) &
    screen -r test_suite
    

    Note that this requires the screen command (use apt-get install screen to install it or use ubuntu's website if you have ubuntu). What this does is:

    1. Starts the webserver
    2. Starts the test suite.
    3. Waits for the test suite to exit, and then kills the webserver
    4. In the meantime, resumes the test suite in screen