Остановка асинхронного цикла while в сценарии оболочки

Эта запись была добавлена ​​более 23 года назад Кевином Далли , а более подробное объяснение было дано в этом отчете об ошибке 19-летней давности:

I have had some trouble verifying the reason for excluding /alex, though I added it many years ago. /alex refers to the Alex file system. One reference to it is:

http://satcom.nic.in/internet1.htm

I'm not sure how common Alex file system is currently. It would probably be better to have the appropriate value in PRUNEFS rather than PRUNEPATHS. /afs may belong in the same category.

I'm leaving /alex and /afs in for the short term, but after I get a few more fixes in findutils, I will attack this problem.

Эта ссылка мертва, но от Wayback Machine:

The Alex file system provides users and applications transparent read access to files in anonymous FTP sites on the Internet. Today there are thousands of anonymous FTP sites with a total of a few millions of files and roughly a terabyte of data. The standard approach to accessing these files involves logging in to the remote machine. This means that an application can not access remote files like local files. This also means that users do not have any of their aliases or local tools available. Users who want to use an application on a remote file first have to manually make a local copy of the file. There is no mechanism for automatically updating this local copy when the remote file changes. The users must keep track of where they get their files from and check to see if there are updates, and then fetch these. In this approach many different users at the same site may have made copies of the same remote file each using up disk space for the same data.

Alex addresses the problems with the existing approach while remaining within the existing FTP protocol so that the large collection of currently available files can be used. To get reasonable performance long term file caching is used. Thus consistency is an issue. Traditional solutions to the cache consistency problem do not work in the Internet FTP domain:callbacks are not an option as the FTP protocol has no provisions for this and polling over the Internet is slow. Therefore, Alex relaxes file cache consistency semantics, on a per file basis, and uses special caching algorithms that take into account the properties of the files and of the network to allow a simple stateless file system to scale to the size of the Internet.

3
18.03.2021, 11:34
2 ответа

Вам нужно kill $!, чтобы убить последний запущенный процесс в фоновом режиме. см. Что означает "$!" в сценариях Bash?

Если есть другие команды, которые вы выполняете в фоновом режиме, вы можете сохранить их PID в переменной из $!, а затем использовать этот идентификатор, чтобы убить этот процесс в любом месте, где вам нужно.

( while... done ) & pid=$!

, затем

kill $pid

или используйте jobs, чтобы определить, какой фоновый процесс там запущен, и убить его с помощью его идентификатора.

kill %Id

см. также Как завершить фоновый процесс?

3
18.03.2021, 22:20

coprocдля имитации именованных циклов

Ближайший к именованным петлям bashможет бытьcoproc:

coproc loop1 { while ((1)) ; do echo a >> aout ; sleep 1 ; done ;} 
echo PID of loop1 $loop1_PID
coproc loop2 { while ((1)) ; do echo b >> bout ; sleep 1 ; done ;} 
echo PID of loop2 $loop2_PID
coproc loop3 { while ((1)) ; do echo c >> cout ; sleep 1 ; done ;}
echo PID of loop3 $loop3_PID

sleep 2
kill $loop1_PID
sleep 2
kill $loop2_PID
sleep 2
kill $loop3_PID

.

coproc NAME simple_command 
#or
coproc NAME { series ; of ; commands ;}

сохранит PID в NAME_PID, и вы можете убить процесс позже, используя это.


Альтернативные:фиктивные файлы

В то время как использование PID, предложенное @αғsнιη, является наиболее правильным способом, вот еще одна идея — просто создать фиктивный файл:

 #!/bin/bash
 dummy="$(mktemp -u -p.)"
 ( while [ ! -e "$dummy" ] ; do./async_command ; done ) &
...
 #condition met
 touch "$dummy"
...

Вы также можете использовать этот файл в качестве индикатора выполнения условия или добавить trap, если хотите, чтобы он был очищен.Опять же :управление через PID должно быть предпочтительнее, но вы можете злоупотреблять им, чтобы «называть» свои циклы и останавливать правильные.

2
18.03.2021, 22:21

Теги

Похожие вопросы