/* * This file is part of fwm-sysdaemon * fwatch.c - watch single file for updates * * Copyright (c) 2022 firk (firk@cantconnect.ru) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The origin of this software must not be misrepresented; you must * not claim that you wrote the original software. * 4. Altered versions in any form must be plainly marked as such, and * must not be misinterpreted as being the original software. * * This software is provided by the author and contributors `as is' * without any express or implied warranty. */ #include #include #include #include #include #include "fwatch.h" static int qfd = -2; static int err; extern int fwatch_add(char const *fn) { int wd; if(qfd==-2 && (qfd = inotify_init1(IN_NONBLOCK))<0) { err=errno; qfd = -1; } if(qfd<0) { errno=err; return -1; } return inotify_add_watch(qfd, fn, IN_MODIFY); } extern int fwatch_check(void) { struct inotify_event e[3]; ssize_t len; int r; if(qfd==-2) return 0; if(qfd<0) { errno=EBADF; return -1; } r = 0; while(1) { if((len = read(qfd, e, sizeof(e)))<0) { if(errno==EAGAIN) return r; return -1; } if(!r) { errno=-1; return -1; } r = 1; } } extern int fwatch_wait(int ms) { struct pollfd pfd; int r; if(qfd==-2) { usleep(ms*1000); return 0; } if(qfd<0) { errno=EBADF; return -1; } pfd.fd = qfd; pfd.events = POLLIN; pfd.revents = 0; r = poll(&pfd, 1, ms); /* ret. -1/EINTR or -1/errno or 0(timeout) or 1(have) */ return fwatch_check(); }