Difference between revisions of "Prove pratiche 2019"

From Sistemi Operativi
Jump to navigation Jump to search
(Created page with " = 2019-02-15 = == Esercizio 1 == === Proposta 1 (Da controllare) === ~~~~ <syntaxhighlight lang="C"> #include <stdio.h> #include <sys/types.h> #include <dirent.h> #includ...")
 
 
Line 87: Line 87:
  
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
== Esercizio 2 ==

Latest revision as of 20:16, 26 April 2023

2019-02-15

Esercizio 1

Proposta 1 (Da controllare)

Flecart (talk) 21:15, 26 April 2023 (CEST)

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/inotify.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

// as docs said, return value is event + MAX_NAME of the file.
typedef struct event {
    struct inotify_event ev;
    char name[256 + 1];
} event_t;

char *get_name(char *dir_name, char *file_name) {
    int dir_len = strlen(dir_name);
    int file_len = strlen(file_name);
    char *space = (char *) malloc(dir_len + file_len + 2);

    strcpy(space, dir_name);
    space[dir_len] = '/';
    strcat(space, file_name);
    space[1 + dir_len + file_len] = '\0';

    return space ;
}

int is_dir(char *dirname) {
    int n = 0;
    struct dirent *d;
    DIR *dir = opendir(dirname);
    if (dir == NULL) return 0;
    while ((d = readdir(dir)) != NULL) 
        if (++n > 2)
            break;

    closedir(dir);

    if (n <= 2) return 1;
    else return 0;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("USAGE: doanddelete <directory>\n");
        return 1;
    }

    if (!is_dir(argv[1])) {
        printf("%s is not a directory or not empty, exiting \n", argv[1]);
        return 1;
    }

    int init = inotify_init();

    int ret_val = inotify_add_watch(init, argv[1], IN_CREATE | IN_MOVED_TO);
    if (ret_val == -1) {
        printf("inotify_add_watch failed with errno: %d\n", errno);
        return 1;
    }

    struct event eventt;
    int num_bytes_read;
    while ((num_bytes_read = read(init, &eventt, sizeof(struct event))) > 0) {
        char * name = get_name(argv[1], eventt.name);
        printf("concatenated name is %s\n", name);

        if (fork()) {
            execl(name, name, NULL);
        }
        unlink(name); 
        free(name);
    }
    // 18:59
}

Esercizio 2