ProvaPratica 2012.06.20

From Sistemi Operativi
Revision as of 22:39, 1 May 2014 by Gab (talk | contribs)
Jump to navigation Jump to search

Link to Exam


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <linux/inotify.h>


int main (int arc, char *argv[])
{
	if(arc<2)
		return 0;
	char *directoryToWatch;
	directoryToWatch = argv[1]+1;
	int notifierDescriptor = inotify_init();
	if(!notifierDescriptor)
	{
		perror("inotify_init");
		return 0;		
	}
	int watcherDescriptor = inotify_add_watch( notifierDescriptor,directoryToWatch, IN_CREATE);
	char eventBuffer[sizeof(struct inotify_event)+256];
	while(read(notifierDescriptor,eventBuffer,sizeof(struct inotify_event)+256)>0)
	{
		struct inotify_event *event = ( struct inotify_event * ) eventBuffer;
		if ( event->mask & IN_CREATE ) 
		{
     		   	if ( event->mask & IN_ISDIR ) 
        			  printf( "directory %s created.\n", event->name );
		   	else
			{
				struct stat fileStructure;			
				char fileName[strlen(directoryToWatch)+strlen(event->name)+1];
				strcpy(fileName,directoryToWatch);
				strcat(fileName,"/");
				strcat(fileName,event->name);
				int result = stat(fileName,&fileStructure);
				if(result<0)
				{
					return 0;				
				}
				if(S_IEXEC && fileStructure.st_mode)
				{	
					int resultFromFork = fork();
					if(!resultFromFork)
					{
						//child
						int result = execl(fileName,event->name,(char *)0);
						if(result<0)
							 printf("an error: %s\n", strerror(errno));
					}	
					else
					{
						
						if(waitpid(-1,NULL,0))
							unlink(fileName);
						
					}				
				}
			}
        	}
	}
	
	inotify_rm_watch( notifierDescriptor, watcherDescriptor );
	close(notifierDescriptor);
	return 0;
}


Gab