0

I have a router running uhttpd by default and there is a process using lighttpd I would like to run instead. Since both processes share the same port, I would like to kill uhttpd then start up lighttpd automatically (by setting up the script that contains the commands as a cron job that runs on reboot).

When I run the commands I would like to go into the script individually, they work. When I put them in a script, I get an error message telling me the port number is in use. The commands are:

killall uhttpd

/etc/init.d/lighttpd start

The simple script I have so far is:

#!/bin/sh
killall uhttpd
sleep 5 #To give the device time to release the port
/etc/init.d/lighttpd start
jasonwryan
  • 71,734
  • 34
  • 193
  • 226
  • I have just noticed that `killall uhttpd` is not working the way I thought it would. When I run `ps | grep uhttpd` after, it seems to be still running. I would like to kill `uhttpd` without having to get the PID first. –  Feb 16 '16 at 07:19
  • is it still running, or running again? Compare the process number for uhttpd before and after the `killall` – Anthon Feb 16 '16 at 07:44

1 Answers1

1

I would not wait for 5 seconds and hope that will work, you might wait too long, or too short. You can use nc -z to test whether the port is (still) being used and do the following (I assume they are "fighting" about port 80):

#!/bin/bash

for i in $(seq 5); do
  if ! nc -z localhost 80; then
      break
  fi
  echo $i
  sleep 1
done

if nc -z localhost 80; then
    killall -9 uhttpd
    sleep 1
fi

if ! nc -z localhost 80; then
    /etc/init.d/lighttpd start
else
    echo 'port not free'
fi

If after 5 times waiting the process is still not killed, kick it out with more force and only start lighttpd if the port is free.

You should investigate if something is restarting uhttpd (e.g. the process that starts it in the first place). Maybe the sleep 5 you are using leaves enough time that it restarts (e.g. look at the uhttpd process number before you run your script and after).

Anthon
  • 78,313
  • 42
  • 165
  • 222
  • Thanks, Anthon! You have pointed two out interesting things: the wait time I set was too long and that `uhttpd` was restarting even after being killed. I shortened the delay to 2 seconds and now the script works. I set the cron job to run every 30 seconds and so far so good. Thanks! –  Feb 16 '16 at 09:21
  • @marundu I recommend you do investigate why uhttpd restarts. Also if your Question is answer by this post, please consider to mark it (by clicking the V next to the answer), that way others know that your question has been answered (not everyone reads the comments). – Anthon Feb 16 '16 at 10:33