Prova pratica 2015.01.21

From Sistemi Operativi
Revision as of 16:14, 26 March 2017 by LeonardoF (talk | contribs)
Jump to navigation Jump to search

Testo: [1]

Esercizio 1

//ESERCIZIO 1
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "execs.h" // from https://github.com/rd235/s2argv-execs
#define BUFFLEN  4096 //probably there is a system constant

int main(int argc,const char* argv[]){
	//take the path name and open the file
	FILE* fd = fopen(argv[1],"r");
	//read the the file and put its content in a array of pointers
	char commands[2][BUFFLEN]; //migliorabile
	char buffer[BUFFLEN];
	int i = 0;
	while (fgets(buffer,sizeof(buffer),fd) != NULL){
		strcpy(commands[i],buffer);
		i ++;
	}
	//printf("%s\n%s\n",commands[0],commands[1] );
	//create a pipe
	int fpipe[2];
	pipe(fpipe); //0 reading,1 writing
	//fork
	int pid;
	pid = fork();
	switch (pid){
	case 0 : //children
		
		close(fpipe[0]);
		//children's stout = pipe output
		dup2(fpipe[1],STDOUT_FILENO);
		close(fpipe[1]);
		//execution of the command
		execsp(commands[0]);
		
		break;

	default : //parent
		
		close(fpipe[1]);
		//father's stdin = pipe input
		dup2(fpipe[0],STDIN_FILENO);
		close(fpipe[0]);
		//receive the comnmand
		execsp(commands[1]);
		
		break;
	}	
}

--LeonardoF (talk) 15:39, 26 March 2017 (CEST)LeonardoF

//ESERCIZIO 2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "execs.h" // from https://github.com/rd235/s2argv-execs
 
#define AOS_LENSTEP 8
 
/*
 * Define a struct for managing and array of pointer to strings.
 */
struct array_of_strings {
    char **strings;
    size_t currentlength; //the length of number of string in memory
    size_t arraylength; //the length of memory allocated
};
 
typedef struct array_of_strings array_of_strings;
 
void array_of_strings_add(array_of_strings *arrayOfStrings, char *string) {
    //if there is not enough space for the string increase it
    if (arrayOfStrings->currentlength >= arrayOfStrings->arraylength) {
        //increase the array length by the size of a string pointer
        size_t newlength = arrayOfStrings->arraylength + AOS_LENSTEP;
        //reallocate the arrayOfString with the new size
        char **new_string = realloc(arrayOfStrings->strings, newlength * sizeof(arrayOfStrings->strings[0]));
        //if the reallocation is successful
        if (new_string != NULL) {
            arrayOfStrings->arraylength = newlength;
            arrayOfStrings->strings = new_string;
        }
    }
    //if there is enough space for the string insert it
    if (arrayOfStrings->currentlength < arrayOfStrings->arraylength)
        //strdup return a pointer to a duplicate of the string
        arrayOfStrings->strings[arrayOfStrings->currentlength++] = strdup(string);
}
 
void array_of_strings_print(array_of_strings *v) {
    size_t i;
    for (i = 0; i < v->currentlength; i++)
        printf("[%3lu]: %s\n", i, v->strings[i]);
}

int main(int argc, char *argv[]) {
	int commandNumber= 0;
    char* line = NULL;
    size_t lineLength = 0;

    ssize_t numberOfCharactersRead;
    static array_of_strings arrayOfStrings;
    FILE* fd = fopen(argv[1],"r");

    while ((numberOfCharactersRead = getline(&line, &lineLength, fd)) >= 0) {
        if (line[numberOfCharactersRead - 1] == '\n')
            line[numberOfCharactersRead - 1] = 0;
        array_of_strings_add(&arrayOfStrings, line);
        commandNumber ++;
    }
 	free(line);
 	//array_of_strings_print(&arrayOfStrings);
 	//printf("%d\n",commandNumber );
 	//open the pipe
 	int fpipe[2];
	pipe(fpipe); //0 reading,1 writing
	int i = 0;

	
 	while(commandNumber > 0 ){
 		if(commandNumber > 1) {
 			int pid = fork();
 			switch(pid){
 				case 0: //children
 						close(fpipe[0]);
						//children's stout = pipe output
						dup2(fpipe[1],STDOUT_FILENO);
						close(fpipe[1]);
						//execution of the command
						//usleep( commandNumber* 1000000);
						execsp(arrayOfStrings.strings[i]);
				
						
 						break;
 				default: //parent 
 						commandNumber --;
 						i ++;
 						break;
 			}
 		}
 		else{ //last command
 				close(fpipe[1]);
				//father's stdin = pipe input
				dup2(fpipe[0],STDIN_FILENO);
				close(fpipe[0]);
				//receive the comnmand
				execsp(arrayOfStrings.strings[i]);
				
 		}
 	}
    
}

--LeonardoF (talk) 15:39, 26 March 2017 (CEST)LeonardoF

Esercizio 3 Script Bash

#!/bin/bash
#ESERCIZIO 3

find $1 -exec md5sum {} \; |sort | uniq  --all-repeated=separate --check-chars=32
shift 

for i in $@ ; do
	find $1 -exec md5sum {} \; |sort | uniq  --all-repeated=separate --check-chars=32
	shift

done

--LeonardoF (talk) 15:39, 26 March 2017 (CEST)LeonardoF

Esercizio 3 Script Python

#!/usr/bin/env python3
#ESERCIZIO 3
import sys
# os.syscall way to use linux syscalls
import os
import hashlib

dictionary = {}

def add(md5val,path):
	"""function that insert the given file path in a dictionary
	using as key the given md5sum"""	
	#in this way i avoid duplicates
	dictionary.setdefault(md5val,set()).add(path)
	

def md5add(path):
	"""function that takes a filepath and calculate is md5sum
	then it calls a function to insert the file in a dictionary"""
	md5val = hashlib.md5()
	with open(path, "rb") as f:
		#Note that sometimes you won't be able to fit the whole file in memory. 
		#In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the Md5 function:
		for chunk in iter(lambda: f.read(4096), b""):
			md5val.update(chunk)
	add(md5val.hexdigest(),path)


def movmd5add(path):
	"""recursive fuction that moves in the file system and call the mdadd function
	it takes a path in input (main checks the path given by the user) """
	for root, dirs, files in os.walk(path):
		for f in files:
			#if file call the function for the md5sum 
			md5add(os.path.join(root,f)) # os.path.join(root,f)



def printdict():
	"""funtion that prints the dictionary"""
	for x in dictionary:
		#doesn't print single lines
		if len(dictionary[x]) > 1 :
			print('\r')
			for y in dictionary[x]:
				print(x," : ",y)


def main(args):
	"""main checks the path and call the functions"""
	if len(args) < 1:
		args = "."
	for path in args:
		movmd5add(path)
	printdict()

if __name__ == "__main__":
		main(sys.argv[1:])

--LeonardoF (talk) 15:39, 26 March 2017 (CEST)LeonardoF

Esercizio 3

#!/usr/bin/python
"""
Esercizio 3: Script bash o Python: (10 punti):
Scrivere un programma python o uno script bash che scandisca il sottoalbero relativo alle directory passate come
parametri (o alla direcotry corrente se non ci sono parametri) e fornisca in output l'elenco dei file che hanno la
stessa somma MD5 (i.e. l'output del comando md5sum).
In output ogni riga deve mostrare un elenco di pathname realtivi a file che hanno la stessa somma MD5 (che quindi
sono molto molto probabilmente uguali).
"""

import sys
import os
import hashlib

def sha1sum(root, filename):
    sha1 = hashlib.sha1()
    with open(os.path.join(root, filename), "rb") as thefile:
        buf = thefile.read()
        sha1.update(buf)
    return sha1.hexdigest()

def initSha1vect(path):
    """ Inizializza il dizionario utilizzando come chiave il sha1
    del file, e come valore il percorso del file. """
    shafiles = {}
    for root, dirs, files in os.walk(path):
        for file in files:
            shaKey = sha1sum(root, file)
            shafiles.setdefault(shaKey, [])
            shafiles[shaKey].append(file)
    return shafiles

def main(args):
    for path in args:
        msg = True
        print "\n", path
        shafiles = initSha1vect(path)
        for k in shafiles:
            if len(shafiles[k]) > 1:
                msg = False
                print k, "\t", shafiles[k]
        if msg:
            print "Nessun file con lo stesso sha1"

if __name__ == "__main__":
	main(sys.argv[1:])

S.G (talk) 14:39, 18 November 2016 (CET)
Ho scritto una possibile soluzione dell'esercizio 3

perché proporre una soluzione in un linguaggio che non ho ancora spiegato?Renzo (talk) 19:36, 21 November 2016 (CET)