Restart process on file change in Linux

2019-04-18 07:32发布

Is there a simple solution (using common shell utils, via a util provided by most distributions, or some simple python/... script) to restart a process when some files change?

It would be nice to simply call sth like watch -cmd "./the_process -arg" deps/*.

Update: A simple shell script together with the proposed inotify-tools (nice!) fit my needs (works for commands w/o arguments):

#!/bin/sh
while true; do
  $@ &
  PID=$!
  inotifywait $1
  kill $PID
done

标签: linux shell
4条回答
来,给爷笑一个
2楼-- · 2019-04-18 07:38

This is an improvement on the answer provided in the question. When one interrupts the script, the run process should be killed.

#!/bin/sh

sigint_handler()
{
  kill $PID
  exit
}

trap sigint_handler SIGINT

while true; do
  $@ &
  PID=$!
  inotifywait -e modify -e move -e create -e delete -e attrib -r `pwd`
  kill $PID
done
查看更多
Emotional °昔
3楼-- · 2019-04-18 07:51

Check out iWatch:

Watch is a realtime filesystem monitoring program. It is a tool for detecting changes in filesystem and reporting it immediately.It uses a simple config file in XML format and is based on inotify, a file change notification system in the Linux kernel.

than, you could watch files easily:

iwatch /path/to/file -c 'run_you_script.sh'
查看更多
可以哭但决不认输i
4楼-- · 2019-04-18 08:00

Yes, you can watch a directory via the inotify system using inotifywait or inotifywatch from the inotify-tools.

inotifywait will exit upon detecting an event. Pass option -r to watch directories recursively. Example: inotifywait -r mydirectory.

You can also specify the event to watch for instead of watching all events. To wait only for file or directory content changes use option -e modify.

查看更多
Deceive 欺骗
5楼-- · 2019-04-18 08:00

I find that this suits the full scenario requested by the PO quite very well:

ls *.py | entr -r python my_main.py 

See also http://eradman.com/entrproject/, although a bit oddly documented. Yes, you need to ls the file pattern you want matched, and pipe that into the entr executable. It will run your program and rerun it when any of the matched files change.

查看更多
登录 后发表回答