Introduction. dnotify



Similar documents
Linux Syslog Messages in IBM Director

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

System Calls Related to File Manipulation

Example of Standard API

CS 103 Lab Linux and Virtual Machines

Incremental Backup Script. Jason Healy, Director of Networks and Systems

Setting up PostgreSQL

Greenstone Documentation

µtasker Document FTP Client

Have both hardware and software. Want to hide the details from the programmer (user).

Operating System Structures

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Operating System Structure

Setting Up a CLucene and PostgreSQL Federation

White Paper. Real-time Capabilities for Linux SGI REACT Real-Time for Linux

Version control. HEAD is the name of the latest revision in the repository. It can be used in subversion rather than the latest revision number.

Lecture 24 Systems Programming in C

Jorix kernel: real-time scheduling

Leak Check Version 2.1 for Linux TM

Linux/UNIX System Programming. POSIX Shared Memory. Michael Kerrisk, man7.org c February 2015

1 Posix API vs Windows API

Unix System Calls. Dept. CSIE

Q N X S O F T W A R E D E V E L O P M E N T P L A T F O R M v Steps to Developing a QNX Program Quickstart Guide

Virtuozzo Virtualization SDK

System Security Fundamentals

System Calls and Standard I/O

Xcode Project Management Guide. (Legacy)

CS3600 SYSTEMS AND NETWORKS

To connect to the cluster, simply use a SSH or SFTP client to connect to:

TFTP Usage and Design. Diskless Workstation Booting 1. TFTP Usage and Design (cont.) CSCE 515: Computer Network Programming TFTP + Errors

WhatsUp Gold v11 Features Overview

Thirty Useful Unix Commands

Installing F-Secure Anti-Virus (FSAV) Table of Contents. FSAV 8.x and FSLS 7.x End of Life. FSAV 9.x and FSLS 9.x End of Life

Green Telnet. Making the Client/Server Model Green

Instrumentation for Linux Event Log Analysis

Data Migration from Magento 1 to Magento 2 Including ParadoxLabs Authorize.Net CIM Plugin Last Updated Jan 4, 2016

CS355 Hw 3. Extended Shell with Job Control

Command-Line Operations : The Shell. Don't fear the command line...

PuTTY/Cygwin Tutorial. By Ben Meister Written for CS 23, Winter 2007

Linux Kernel Architecture

PetaLinux SDK User Guide. Application Development Guide

6.828 Operating System Engineering: Fall Quiz II Solutions THIS IS AN OPEN BOOK, OPEN NOTES QUIZ.

CSC230 Getting Starting in C. Tyler Bletsch

Command Line Interface Specification Linux Mac

Installing Magento Extensions

Introduction. What is an Operating System?

HARFORD COMMUNITY COLLEGE 401 Thomas Run Road Bel Air, MD Course Outline CIS INTRODUCTION TO UNIX

IBM Redistribute Big SQL v4.x Storage Paths IBM. Redistribute Big SQL v4.x Storage Paths

FileBench's Multi-Client feature

Programmation Systèmes Cours 7 IPC: FIFO

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY Operating System Engineering: Fall 2005

LSN 10 Linux Overview

How to Add a New System Call for Minix 3

Title: Documentation for the Pi-UPS-Monitor-App

Statel Robot Service Help Eurostat

Using NSM for Event Notification. Abstract. with DM3, R4, and Win32 Devices

How to Write a Simple Makefile

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Automatic Generation of Time-lapse Animations

CLC Server Command Line Tools USER MANUAL

Source Code Management for Continuous Integration and Deployment. Version 1.0 DO NOT DISTRIBUTE

NBU651 BMR. Avi Weinberger

OLCF Best Practices. Bill Renaud OLCF User Assistance Group

Tail call elimination. Michel Schinz

Frysk The Systems Monitoring and Debugging Tool. Andrew Cagney

CS197U: A Hands on Introduction to Unix

Source Code Management/Version Control

Type-C Ubuntu Product & Strategy Canonical Ltd.

Title: SharePoint Advanced Training

Parallelization: Binary Tree Traversal

Computer Systems II. Unix system calls. fork( ) wait( ) exit( ) How To Create New Processes? Creating and Executing Processes

Performance analysis of a Linux based FTP server

QuickBooks Enterprise Solutions. Linux Database Server Manager Installation and Configuration Guide

CS420: Operating Systems OS Services & System Calls

An Example VHDL Application for the TM-4

Writing Scripts with PHP s PEAR DB Module

Hadoop Basics with InfoSphere BigInsights

Improved metrics collection and correlation for the CERN cloud storage test framework

Device Management API for Windows* and Linux* Operating Systems

Writing a C-based Client/Server

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring HDFS Basics

CASHNet Secure File Transfer Instructions

Outlook Web App (OWA) To create a new message:

Sophos Anti-Virus for Linux configuration guide. Product version: 9

Code Estimation Tools Directions for a Services Engagement

SysPatrol - Server Security Monitor

Linux command line. An introduction to the Linux command line for genomics. Susan Fairley

Extreme computing lab exercises Session one

Module 816. File Management in C. M. Campbell 1993 Deakin University

Linux Driver Devices. Why, When, Which, How?

Linux System Administration on Red Hat

System Administration

OFBiz Addons goals, howto use, howto manage. Nicolas Malin, Nov. 2012

Yocto Project Eclipse plug-in and Developer Tools Hands-on Lab

Networks. Inter-process Communication. Pipes. Inter-process Communication

OS: IPC I. Cooperating Processes. CIT 595 Spring Message Passing vs. Shared Memory. Message Passing: Unix Pipes

Transcription:

Introduction In a multi-user, multi-process operating system, files are continually being created, modified and deleted, often by apparently unrelated processes. This means that any software that needs to keep aware of what is happening in a filesystem needs to employ a file monitoring technique. Monitoring, in this sense, means keeping a watch over a set of files, waiting for any of them to change. Applications that benefit from monitoring techniques include those that need to keep their displayed filesystem information up to date, long running server tools that should automatically reread their configuration files when those files change, applications that watch for and respond to unusual file modifications, system message file monitors, and so on. Most modern operating systems provide file monitoring facilities to give applications realtime information about changes to the filesystem. A variety of notification methods are used to tell the application when a change happens, ranging from an asynchronous signal being sent from the kernel, through to a user space tool printing the name of the changed file on its standard output. We ll take a look at some of the file monitoring facilities available to the Linux developer, starting with the lowest level mechanism and working up to the highest. dnotify All files are ultimately created, updated and deleted by the Linux kernel, so it makes sense that the most direct way for an application to learn that a file has changed is for the kernel to tell it. This is the idea behind the kernel s dnotify feature. dnotify stands for directory notification, and although the feature has been in the kernel for some time, it can only be relied upon in kernels 2.4.19 and later, which was when a tiny but very important bug was fixed. dnotify works by sending a signal to a process that has asked to be informed when the content of a directory is changed. Being a low level feature, dnotify is normally used from C code. The developer needs to open the appropriate directory file for reading, then issue a fcntl(2) system call specifying the F_NOTIFY subcommand. Flags passed to this subcommand can specify which events the process wants to be notified about: file creation, deletion, access, modification, renaming, or access rights being set with chmod. By default, whenever any of the monitored operations happen to any file in the directory, the monitoring process will receive the SIGIO signal from the kernel. The signal used is configurable using the fcntl(2) F_SETSIG subcommand, and in order to ensure no signals are missed it is best to change the signal generated to one of the POSIX4 real-time ones, which can be queued. Note that we are talking about directory notification here, not files. If only a single file needs to be watched its directory should be dnotified and the file examined each time the monitoring process receives the signal. Listing 1 shows an example of some C code that watches a particular file waiting for it to be edited. #define _GNU_SOURCE #include <fcntl.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <signal.h>

int requiredevent = 0; void eventhandler( int sig ) { requiredevent = 1; int main( int argc, char *argv[] ) { struct stat statbuf; struct sigaction action; int fd; char *dir; char *slashptr; char splitfilename[128]; if( argc!= 2 ) { printf( "Usage: %s filename", argv[0] ); if( lstat( argv[1], &statbuf ) < 0 ) { printf( "Cannot lstat %s : %s\n", argv[1], strerror(errno) ); if(! S_ISREG( statbuf.st_mode ) ) { printf( "%s is not a regular file\n", argv[1] ); /* Find directory the file is in, or assume the current directory */ strncpy( splitfilename, argv[1], 127 ); if( (slashptr = rindex( splitfilename, '/' )) == NULL ) { dir = "."; else { *slashptr = 0; dir = splitfilename; /* Set up the signal handler */ action.sa_handler = eventhandler; sigemptyset( &action.sa_mask ); action.sa_flags = SA_RESTART; sigaction( SIGRTMIN, &action, NULL ); /* Open the directory the file is in */ if( (fd = open( dir, O_RDONLY )) < 0 ) { printf( "Cannot open %s for reading : %s\n", dir, strerror(errno) ); /* Choose the signal I want to receive when the directory content changes */ if( fcntl( fd, F_SETSIG, SIGRTMIN) < 0 ) { printf( "Cannot set signal : %s\n", strerror(errno) ); /* Ask for notification when a modification is made in the directory */ if( fcntl( fd, F_NOTIFY, DN_MODIFY DN_MULTISHOT ) < 0 ) { printf( "Cannot fcntl %s : %s\n", dir, strerror(errno) ); /* Infinite loop - a real program would be doing stuff */ while( 1 ) { time_t modifiedtime; /* This demo has nothing to do, so just wait for a signal */ pause(); /* Check the flag which indicates the right signal has been received */ if( requiredevent ) {

/* Something has been modified in the directory - stat our file */ modifiedtime = statbuf.st_mtime; if( lstat( argv[1], &statbuf ) < 0 ) { printf( "Cannot lstat %s : %s\n", argv[1], strerror(errno) ); /* If the modification time has changed, the file has been altered */ if( modifiedtime!= statbuf.st_mtime ) { printf( "File %s has been modified\n", argv[1] ); requiredevent = 0; This program finds the directory the given file is in, then starts monitoring that directory for file modifications. When a notification arrives, the program checks the monitored file with the lstat(2) system call to see if the modification time has been changed. Compile the example code with cc o checkchanged checkchanged.c and try it: > mkdir testdir > touch testdir/datafile >./checkchanged testdir/datafile Now, in another shell do something like echo data >> testdir/datafile. The checkchanged program immediately prints File testdir/datafile has been modified. This example uses the multishot feature of dnotify. Normally, once a notification is issued, dnotify stops monitoring since it is, by default, a single event system. If the DN_MULTISHOT flag is passed to the fcntl(2) F_NOTIFY subcommand, the monitoring stays in place and a signal is sent each and every time a change to the directory is made. FAM The main problem with dnotify is that it is Linux specific. It is also not particularly simple to work with, and if a lot of files need monitoring in lots of different directories, it can get rather complicated. Silicon Graphics Inc. s File Alteration Monitor, or FAM, was designed to simplify file monitoring, and to work on systems without a dnotify type feature. It is now one of SGI s contributions to the free software community. FAM ideally requires the operating system to have SGI s inode monitoring pseudo device driver available. This is called imon and is available for Linux as a kernel patch. There is also a patch available to FAM which allows it to use Linux s dnotify feature instead of imon, and this patch is applied to the FAM package by virtually all Linux distributors. Where neither imon nor dnotify are available, FAM falls back to polling for file changes. Although this might appear to defeat the object somewhat, it does have the advantage that a single process ends up doing all the polling for all monitoring applications. FAM comes in two parts: a daemon and a user level library. The system administrator will configure the daemon to either be started at boot time, or from xinetd as required. It is this daemon process that sits watching for file alterations. Applications, known as FAM clients, link to the user level library which provides routines to connect to the daemon and ask it to monitor a given set of files and/or directories. When a change

happens, the daemon sends the relevant information down a socket to the client application. An important difference between dnotify and FAM is that FAM doesn t work in an asynchronous way. The client program is expected to either block waiting for some information to arrive on its socket, or to occasionally poll the socket to see if anything has happened. If asynchronous behaviour is required by a FAM client, that client should fork off a dedicated process which can block on the socket, and which can send a signal to its parent when something happens. Working with FAM is a lot more straightforward than dnotify. The procedure is basically to open a connection to the daemon, use that connection to tell the daemon what you want to monitor, then either do a blocking read on the connection, or occasionally poll it, waiting for the daemon to tell you your file has changed. When you are finished monitoring, tell the daemon to stop, then close the connection. All of these steps are performed using calls to functions in the FAM library. See the documentation for details. Listing 2 shows a simple FAM client, written in C: #include <fam.h> #include <stdio.h> #include <errno.h> #include <signal.h> void ctrlccatcher( int sig ) { /* No action, just EINTR the system call */ int main( int argc, char *argv[] ) { FAMConnection famconn; FAMRequest famrequest; FAMEvent famevent; struct sigaction action; if( argc!= 2 ) { printf( "Usage: %s filename\n", argv[0] ); action.sa_handler = ctrlccatcher; sigemptyset( &action.sa_mask ); sigaction( SIGINT, &action, NULL ); if( FAMOpen( &famconn ) < 0 ) { printf( "Cannot connect to FAM : %s\n", strerror(errno) ); if( FAMMonitorFile( &famconn, argv[1], &famrequest, NULL ) < 0 ) { printf( "Cannot monitor file %s : %s\n", argv[1], strerror(errno) ); FAMClose( &famconn ); while( 1 ) { if( FAMNextEvent( &famconn, &famevent ) < 0 ) { if( errno == EINTR ) { printf( "Interrupted\n" ); break; printf( "Error retrieving next FAM event : %s\n", strerror(errno) ); FAMClose( &famconn ); if( famevent.code == FAMChanged ) {

printf( "FAM indicates file %s has changed\n", famevent.filename ); if( famevent.code == FAMDeleted ) { printf( "FAM indicates file %s has been deleted\n", famevent.filename ); if( FAMClose( &famconn ) < 0 ) { printf( "Cannot close FAM connection : %s\n", strerror(errno) ); exit( 0 ); This should be complied with a command like cc o famchanged lfam famchanged.c. The file to be monitored should be passed to the program as a command line argument, and must be an absolute pathname, starting with a /. For demonstration purposes this code makes the effort to trap a Ctrl-C and close the connection to the FAM daemon neatly. In normal practise it s safe to just exit the program and have the FAM connection close automatically. FAM can also be used from Perl, using the SGI::FAM module from CPAN. With this module you can write code like Listing 3: #!/usr/bin/perl -w use strict; use SGI::FAM; my $conn = new SGI::FAM; $conn->monitor( "/var/log/messages" ); while (1) { my $event = $conn->next_event; print $event->filename, " ", $event->type, "\n"; There s a Python FAM module too: #!/usr/bin/python import _fam conn = _fam.open() request = conn.monitorfile( "/var/log/messages", None ) while True: event = conn.nextevent() print event.filename, event.code2str() Being a user space tool, FAM can do a lot more than is possible with a kernel based facility like dnotify. For example, if a file to be monitored is in an NFS directory, FAM will attempt to contact the FAM daemon running on the NFS server. The server s FAM daemon will then do the actual monitoring, and when the file changes the information will be relayed via the local daemon to the client. If the server isn t running a FAM daemon then the local daemon will resort to polling the file. See the FAM documentation for details on how to configure this and other more specialised FAM features. FilesChanged If you only have a simple task which requires file monitoring it is often possible to do it from shell script. The fileschanged utility is a FAM client program designed to be used from a script. Although not as flexible as a hand coded FAM client, it is often a quick and simple solution to a problem.

fileschanged has recently been updated to version 0.6.0. Previous versions contained a bug which prevented the tool working with bash under some circumstances. Ensure you have the latest version before experimenting with it. fileschanged takes the names of the files to monitor on its command line and can report when any of the files are created, deleted, changed or executed. When one of these actions happens, the name of the file is printed to standard output. This is simple, but effective. If you re working on a shared source tree, and you want to keep a log of which source files are being updated by your colleagues, you might take advantage of fileschanged s recursive directories feature, and run something like this: fileschanged r /shared/source/tree while read fd; do stat format= %n modified by %U at %y $fc done fileschanged is often used to monitor log files or incoming mailbox files. It s also possible to use it for more complex tasks such as watching and backing up rarely changed configuration files. Conclusion File monitoring is one of those issues of software development that is often classed as the icing on the cake. A user can always press F5 to refresh a file manager window, or send a SIGHUP to a program when they ve changed its configuration file, so automatically monitoring for changes isn t very often essential. It is, however, something which can make a program more intuitive, or easier to use. The system facilities that provide file monitoring are now widespread and mature, so users will always benefit if developers look for ways to utilise them.