Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a cgi shell script in background

Tags:

shell

cgi

I've a cgi shell script like this

#!/bin/sh

# show the page
echo Content-type: text/html
echo
echo "<html><b>Hello world!</b></html>"

# the task I want to do in background
sleep 100
echo $(date) >> log

I want to page to show after the last echo, not at the end of the execution of the script. I've tried putting the code in another file and execute it like this ./background.sh &. It works in console but not in the browser.

I use lighttpd

like image 967
Martin Trigaux Avatar asked Oct 28 '25 13:10

Martin Trigaux


1 Answers

Close stdout with exec >&- before you execute your long-running or background task. Maybe you'll also have to close stderr. That would be

exec >&-
exec 2>&-

(it seems you can't close both in one line)

This will break the pipe and allow your web server to send the data already outputted (such as via echo) to the browser.

like image 123
Aaron Digulla Avatar answered Oct 30 '25 07:10

Aaron Digulla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!