Изменения в файлах
#
FileWatching.poll_fd — Function
poll_fd(fd, timeout_s::Real=-1; readable=false, writable=false)
Отслеживает изменение доступности файла с дескриптором fd для чтения или записи с временем ожидания timeout_s секунд.
Именованные аргументы определяют, какие состояния (чтение и (или) запись) следует отслеживать; по крайней мере один из них должен иметь значение true.
Возвращается объект с логическими полями readable, writable и timedout, представляющими результат опроса.
#
FileWatching.poll_file — Function
poll_file(path::AbstractString, interval_s::Real=5.007, timeout_s::Real=-1) -> (previous::StatStruct, current)
Отслеживает изменение файла, выполняя опрос каждые interval_s секунд, пока не произойдет изменение или не пройдет timeout_s секунд. Период interval_s должен быть длительным; значение по умолчанию — 5,007 секунды.
Возвращает пару объектов состояния (previous, current) при обнаружении изменения. Состояние previous — это всегда структура StatStruct, но все ее поля могут быть нулевыми (это означает, что файл ранее не существовал или не был доступен).
Объект состояния current может быть структурой StatStruct, исключением EOFError (с указанием прошедшего времени ожидания) или другим подтипом Exception (если операция stat не удалась, например, если путь не существует).
Чтобы определить время изменения файла, выполните сравнение current isa StatStruct && mtime(prev) != mtime(current) для обнаружения уведомления об изменениях. Однако для этой операции предпочтительнее использовать функцию watch_file, так как она надежнее и эффективнее, хотя в некоторых ситуациях она может быть недоступна.
#
FileWatching.watch_file — Function
watch_file(path::AbstractString, timeout_s::Real=-1)
Отслеживает изменения в файле или каталоге path, пока не произойдет изменение или не пройдет timeout_s секунд. Эта функция не опрашивает файловую систему, а вместо этого использует возможности платформы для получения уведомлений от операционной системы (например, inotify в Linux). Подробные сведения см. в документации по NodeJS по приведенной ниже ссылке.
Возвращается объект с логическими полями renamed, changed и timedout, представляющими результат отслеживания файла.
Поведение этой функции на разных платформах немного различается. Дополнительные сведения см. в разделе https://nodejs.org/api/fs.html#fs_caveats.
#
FileWatching.watch_folder — Function
watch_folder(path::AbstractString, timeout_s::Real=-1)
Отслеживает изменения в файле или каталоге path, пока не произойдет изменение или не пройдет timeout_s секунд. Эта функция не опрашивает файловую систему, а вместо этого использует возможности платформы для получения уведомлений от операционной системы (например, inotify в Linux). Подробные сведения см. в документации по NodeJS по приведенной ниже ссылке.
Отслеживание изменений по пути path будет продолжаться в фоновом режиме, пока для того же пути path не будет вызвана функция unwatch_folder.
Возвращаемое значение представляет собой пару полей, первое из которых — это имя измененного файла (если доступно), а второе — это объект с логическими полями renamed, changed и timedout, описывающими событие.
Поведение этой функции на разных платформах немного различается. Дополнительные сведения см. в разделе https://nodejs.org/api/fs.html#fs_caveats.
#
FileWatching.unwatch_folder — Function
unwatch_folder(path::AbstractString)
Останавливает отслеживание изменений по пути path в фоновом режиме. Это не рекомендуется делать, пока другая задача ожидает возврата управления функцией watch_folder, выполняющейся для того же пути, так как результат может быть непредсказуемым.
#
FileWatching.FileMonitor — Type
FileMonitor(path::AbstractString)
Watch file or directory path (which must exist) for changes until a change occurs. This function does not poll the file system and instead uses platform-specific functionality to receive notifications from the operating system (e.g. via inotify on Linux). See the NodeJS documentation linked below for details.
fm = FileMonitor(path) acts like an auto-reset Event, so wait(fm) blocks until there has been at least one event in the file originally at the given path and then returns an object with boolean fields renamed, changed, timedout summarizing all changes that have occurred since the last call to wait returned.
This behavior of this function varies slightly across platforms. See https://nodejs.org/api/fs.html#fs_caveats for more detailed information.
#
FileWatching.FolderMonitor — Type
FolderMonitor(folder::AbstractString)
Watch a file or directory path for changes until a change has occurred. This function does not poll the file system and instead uses platform-specific functionality to receive notifications from the operating system (e.g. via inotify on Linux). See the NodeJS documentation linked below for details.
This acts similar to a Channel, so calling take! (or wait) blocks until some change has occurred. The wait function will return a pair where the first field is the name of the changed file (if available) and the second field is an object with boolean fields renamed and changed, giving the event that occurred on it.
This behavior of this function varies slightly across platforms. See https://nodejs.org/api/fs.html#fs_caveats for more detailed information.
#
FileWatching.PollingFileWatcher — Type
PollingFileWatcher(path::AbstractString, interval_s::Real=5.007)
Monitor a file for changes by polling stat every interval_s seconds until a change occurs or timeout_s seconds have elapsed. The interval_s should be a long period; the default is 5.007 seconds. Call stat on it to get the most recent, but old, result.
This acts like an auto-reset Event, so calling wait blocks until the stat result has changed since the previous value captured upon entry to the wait call. The wait function will return a pair of status objects (previous, current) once any stat change is detected since the previous time that wait was called. The previous status is always a StatStruct, but it may have all of the fields zeroed (indicating the file didn’t previously exist, or wasn’t previously accessible).
The current status object may be a StatStruct, an EOFError (if the wait is canceled by closing this object), or some other Exception subtype (if the stat operation failed: for example, if the path is removed). Note that stat value may be outdated if the file has changed again multiple times.
Using FileMonitor for this operation is preferred, since it is more reliable and efficient, although in some situations it may not be available.
#
FileWatching.FDWatcher — Type
FDWatcher(fd::Union{RawFD,WindowsRawSocket}, readable::Bool, writable::Bool)
Monitor a file descriptor fd for changes in the read or write availability.
The keyword arguments determine which of read and/or write status should be monitored; at least one of them must be set to true.
The returned value is an object with boolean fields readable, writable, and timedout, giving the result of the polling.
This acts like a level-set event, so calling wait blocks until one of those conditions is met, but then continues to return without blocking until the condition is cleared (either there is no more to read, or no more space in the write buffer, or both).
|
Warning You must call |
Pidfile
Простое вспомогательное средство для создания справочных файлов pidfile (файлов блокировки).
Основные функции
#
FileWatching.Pidfile.mkpidlock — Function
mkpidlock([f::Function], at::String, [pid::Cint]; kwopts...)
mkpidlock(at::String, proc::Process; kwopts...)
Создает блокировку pidfile для пути «at» для текущего процесса или процесса, на который указывает pid или proc. Может принимать функцию для выполнения после блокировки в блоках do, после чего блокировка будет автоматически закрыта. Если блокировка не удалась и wait имеет значение false, выдается ошибка.
Блокировка будет снята либо функцией close, либо функцией finalizer, либо вскоре после выхода из proc. Возвращаемое значение должно существовать до конца критического раздела программы, чтобы finalizer не отозвал его раньше времени.
Необязательные именованные аргументы:
-
mode: режим доступа к файлу (изменяется при размаскировке процесса). По умолчанию предоставляется глобальный доступ для чтения. -
poll_interval: указывает максимальное время между попытками (еслиwatch_fileне работает). -
stale_age: существующий pidfile удаляется (игнорируя блокировку), если он старше указанного количества секунд с учетом его mtime. Файл не будет удален, пока его возраст не превысит указанное значение, умноженное на 5, если pid в файле указывает, что он может быть действительным. Или умноженное на 25, еслиrefreshпереопределено значением 0 для отключения обновления блокировки. По умолчанию этот параметр отключен (stale_age= 0), но типичное рекомендуемое значение будет примерно в 3—5 раз больше предполагаемого обычного времени завершения. -
refresh: предотвращает устаревание блокировки путем обновления mtime через каждый прошедший интервал времени. По умолчанию установлено значениеstale_age/2, которое является рекомендуемым. -
wait: если задано значение true, блокировка действует до тех пор, пока не будет получена; если задано false, то при сбое блокировки выдается ошибка.
#
FileWatching.Pidfile.trymkpidlock — Function
trymkpidlock([f::Function], at::String, [pid::Cint]; kwopts...)
trymkpidlock(at::String, proc::Process; kwopts...)
Аналогично mkpidlock, за исключением того, что возвращает false вместо ожидания, если файл уже заблокирован.
|
Совместимость
Julia 1.10 Для этой функции требуется версия Julia не ниже 1.10. |
|
Missing docstring. Missing docstring for |
Вспомогательные функции
#
FileWatching.Pidfile.open_exclusive — Function
open_exclusive(path::String; mode, poll_interval, wait, stale_age, refresh) :: File
Create a new a file for read-write advisory-exclusive access. If wait is false then error out if the lock files exist otherwise block until we get the lock.
For a description of the keyword arguments, see mkpidlock.
#
FileWatching.Pidfile.tryopen_exclusive — Function
tryopen_exclusive(path::String, mode::Integer = 0o444) :: Union{Void, File}
Try to create a new file for read-write advisory-exclusive access, return nothing if it already exists.
#
FileWatching.Pidfile.write_pidfile — Function
write_pidfile(io, pid)
Write our pidfile format to an open IO descriptor.
#
FileWatching.Pidfile.parse_pidfile — Function
parse_pidfile(file::Union{IO, String}) => (pid, hostname, age)
Attempt to parse our pidfile format, replaced an element with (0, "", 0.0), respectively, for any read that failed.
#
FileWatching.Pidfile.stale_pidfile — Function
stale_pidfile(path::String, stale_age::Real, refresh::Real) :: Bool
Helper function for open_exclusive for deciding if a pidfile is stale.
#
FileWatching.Pidfile.isvalidpid — Function
isvalidpid(hostname::String, pid::Cuint) :: Bool
Attempt to conservatively estimate whether pid is a valid process id.