Difference between revisions of "ProvaPratica 2012.06.20"
Jump to navigation
Jump to search
(Created page with "[http://www.cs.unibo.it/~renzo/so/pratiche/2012.06.20.pdf Link to Exam] <syntaxhighlight lang="C"> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unis...") |
|||
Line 15: | Line 15: | ||
− | int main (int arc, char | + | int main (int arc, char *argv[]) |
{ | { | ||
if(arc<2) | if(arc<2) |
Revision as of 22:39, 1 May 2014
#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