void leer(uint8_t idProc, uint8_t pag, int socketSwap, int socketCPU) {

	char* contenido;

	t_contenido_pagina * lecturaMandarCpu;
	lecturaMandarCpu = iniciarContenidoPagina();
	t_marco_y_bit* marcoYBit;
	marcoYBit = iniciarMarcoYBit();

	lecturaMandarCpu->PID = idProc;
	lecturaMandarCpu->numeroPagina = pag;

	marcoYBit = buscarSiEstaEnMemoria(idProc, pag,0);

	if (marcoYBit->bitPresencia == 0) {	// no lo encontro
		uretardo(configuracion->retardoMemoria);
		traerDeSwapUnaPaginaDeUnProceso(idProc, pag, socketSwap); // aca se tiene que pedir a swap la pagina a y del proceso idProc
		char* textoLogger = string_new();
		fallo ++;
		string_append(&textoLogger, string_from_format("Acceso a swap (fallo de página: %i),  PID: %i, pagina: %i\n",fallo, idProc, pag));
		my_log_info(textoLogger);
	} else { // aca significa que trajo el id porque esta en memoria
		contenido = traerContenidoDeMarco(marcoYBit->idMarco);
		char* textoLogger = string_new();
		string_append(&textoLogger, string_from_format("Acceso a memoria realizado, PID: %i, N° de"
				" página: %i y N° de marco: %i\n", idProc, pag, marcoYBit->idMarco));
		my_log_info(textoLogger);
		lecturaMandarCpu->contenido = contenido;
		enviarACPUContenidoPaginaDeUnProcesoPorLeer(lecturaMandarCpu, socketCPU);
	}

}
void escribir(uint8_t idProc, uint8_t nroPag, char* textoAEscribir, int socketSwap, int socketCPU) {

	t_contenido_pagina * escritura;
	escritura = iniciarContenidoPagina();
	t_marco_y_bit* marcoYBit;
	marcoYBit = iniciarMarcoYBit();

	marcoYBit = buscarSiEstaEnMemoria(idProc, nroPag,1);

	escritura->numeroPagina = nroPag;
	escritura->PID = idProc;
	string_append(&escritura->contenido, textoAEscribir);

	if (marcoYBit->bitPresencia == 0) { // traer de swap una pag, cargarla a memoria

		uretardo(configuracion->retardoMemoria );
		traerDeSwapUnaPaginaDeUnProcesoPorEscribir(idProc, nroPag, textoAEscribir, socketSwap);
		char* textoLogger = string_new();
		fallo++;
		string_append(&textoLogger, string_from_format("Acceso a swap (fallo de página:%i),  PID: %i, pagina: %i\n",fallo, idProc, nroPag));
		my_log_info(textoLogger);

	} else {	// entonces tengo el id del marco
		escribirEnMarcoYponerBitDeModificada(marcoYBit->idMarco, textoAEscribir);

		//LOG
		char* textoLogger = string_new();
		string_append(&textoLogger, string_from_format("Acceso a memoria realizado, PID: %i, N° de"
				" página: %i y N° de marco: %i\n", idProc, nroPag, marcoYBit->idMarco));
		my_log_info(textoLogger);

		enviarRtaEscribirACPU(escritura, socketCPU);
	}

}
char * posicionToString(t_posicion * posicion){
	char * pos = string_new();
	string_append(&pos, string_from_format("%d",posicion->posX));
	string_append(&pos, ",");
	string_append(&pos, string_from_format("%d",posicion->posY));

	return pos;
}
void leerArchivoDeConfiguracion(int argc, char *argv[]) {

	char* logMsg = NULL;

	if (argc < 2) {
		logMsg =
				string_from_format(
						"Debe especificar la ruta al archivo de configuracion, al invocar al programa, por ejemplo: ./Memoria /home/utnso/tp-2015-2c-tpso/Memoria/config_memoria.cfg\n");
		puts(logMsg);
		my_log_error(logMsg);
		exit(-1);
	}

	char* nombreArchivoConfig = nombreArchivoConfig = strdup(argv[1]);
	uint8_t result = checkearRutaArchivoConfig(nombreArchivoConfig);
	if (result == -1) {
		logMsg = string_from_format("Archivo de configuracion no encontrado. Parametro especificado: %s\n", nombreArchivoConfig);
		puts(logMsg);
		my_log_error(logMsg);
		exit(-1);
	} else {
		t_config* archivoConfig;
		archivoConfig = config_create(nombreArchivoConfig);
		//warning asignacion diferentes tipos
		configuracion = iniciarArchivoConfig();
		configuracion->puertoEscucha = config_get_int_value(archivoConfig, "PUERTO_ESCUCHA");
		configuracion->puertoSwap = config_get_int_value(archivoConfig, "PUERTO_SWAP");
		configuracion->ipSwap = strdup(config_get_string_value(archivoConfig, "IP_SWAP"));

		char* nombreMemoria = config_get_string_value(archivoConfig, "NOMBRE_MEMORIA");
		configuracion->nombreMemoria = strdup(nombreMemoria != NULL ? nombreMemoria : "NOMBRE_MEMORIA");

		configuracion->maximosMarcosPorProceso = config_get_int_value(archivoConfig, "MAXIMO_MARCOS_POR_PROCESO");
		configuracion->cantidadMarcos = config_get_int_value(archivoConfig, "CANTIDAD_MARCOS");
		configuracion->tamanioMarcos = config_get_int_value(archivoConfig, "TAMANIO_MARCO");
		configuracion->entradasTlb = config_get_int_value(archivoConfig, "ENTRADAS_TLB");
		if (string_equals(config_get_string_value(archivoConfig, "TLB_HABILITADA"),"SI")){
			configuracion->tlbHabilitada=1;
		}
		else if (string_equals(config_get_string_value(archivoConfig, "TLB_HABILITADA"),"NO")){
			configuracion->tlbHabilitada=0;
		}
		configuracion->retardoMemoria = config_get_int_value(archivoConfig, "RETARDO_MEMORIA");
		configuracion->algoritmo_reemplazo = strdup(config_get_string_value(archivoConfig, "ALGORITMO_REEMPLAZO"));
		my_log_info("[INFO]: Archivo de configuracion leido correctamente\n");

		logMsg = string_from_format("Archivo de configuracion leido correctamente\n");
		puts(logMsg);

		//config_destroy(archivoConfig);

	}

}
static void _log_write_in_level(t_log* logger, t_log_level level, const char* message_template, va_list list_arguments) {

	if (_isEnableLevelInLogger(logger, level)) {
		char *message, *time, *buffer;
		unsigned int thread_id;

                message = string_from_vformat(message_template, list_arguments);
		time = temporal_get_string_time();
		thread_id = process_get_thread_id();

		buffer = string_from_format("[%s] %s %s/(%d:%d): %s\n",
                                log_level_as_string(level),
                                time,
                                logger->program_name,
				logger->pid,
                                thread_id,
                                message);

		if (logger->file != NULL) {
			txt_write_in_file(logger->file, buffer);
		}

		if (logger->is_active_console) {
			txt_write_in_stdout(buffer);
		}

		free(time);
		free(message);
		free(buffer);
	}
}
void enviarEscribirAlSwap(t_sobreescribir_swap *estructura, int socketSwap) {
	enviarStruct(socketSwap, ESCRIBIR_SWAP, estructura);
	char* textoLogger = string_new();
	cantEscriturasEnSwap++;
	string_append(&textoLogger, string_from_format("Escritura enviada a swap nro: %i\n", cantEscriturasEnSwap));
	my_log_info(textoLogger);
}
/*
 Write data to an open file

 Write should return exactly the number of bytes requested except on error. An exception to this is when the 'direct_io' mount option is specified (see read operation).
 */
int fs_write(const char *path, const char *buf, size_t size, off_t offset,
		struct fuse_file_info *fi) {
	char* temp = string_from_format(path, "%s"); // no uso string_duplicate para evitar el warning de tipos.
	//logger_info(logger, "Escribo archivo:");
	//logear_path("fs_write", path);
	int ret = 0;

	uint indice = 0;
	int err = buscar_bloque_nodo(temp, &indice);
	free(temp);

	if (err) { // no existe.}
		return 0;
	}
	/*sem_wait(&mutex_nodos);
	 GFile nodo = nodos[indice];
	 sem_post(&mutex_nodos);*/
	ret = guardar_datos(&nodos[indice], buf, size, offset);
	if (!ret) {
		return size;
	} else {
		return 0;
	}

}
t_param_persoje leer_personaje_config() {
	t_config* config;
	t_param_persoje param;
	t_recusos *list_recursos; //declaro el tipo nodo
	char *aux_char;
	char *aux_str;
	char **aux;
	int i;

	log_in_disk_per(LOG_LEVEL_TRACE,
			"comienzo lectura archivo de configuracion del personaje en el %s ",
			PATH_CONFIG_PERSONAJE);

	param.RECURSOS = list_create(); //creo lista de recursos
	config = config_create(PATH_CONFIG_PERSONAJE);

	//param.nom_nivel = nivel; //copio el nombre del nivel que pase por parametro en el main
	param.NOMBRE = config_get_string_value(config, "NOMBRE");

	aux_char = config_get_string_value(config, "SIMBOLO");

	param.SMBOLO = aux_char[0];

	param.PLAN_NIVELES = config_get_array_value(config, "PLANDENIVELES");

	param.VIDAS = config_get_int_value(config, "VIDAS");

	aux_char = config_get_string_value(config, "PLATAFORMA");

	aux = string_split(aux_char, ":");
	param.IP = aux[0];
	param.PUERTO_PLATAFORMA = atoi(aux[1]);

	i = 0;
	while (param.PLAN_NIVELES[i] != '\0') {

		list_recursos = malloc(sizeof(t_recusos));
		//sprintf(aux_str, "OBJ[%s]", param.PLAN_NIVELES[i]);
		aux_str = string_from_format("OBJ[%s]", param.PLAN_NIVELES[i]);

		log_in_disk_per(LOG_LEVEL_TRACE, "Niveles de planificador %s ",
				param.PLAN_NIVELES[i]);

		list_recursos->RECURSOS = config_get_array_value(config, aux_str);
		strcpy(list_recursos->NOMBRE, param.PLAN_NIVELES[i]);
		list_add(param.RECURSOS, list_recursos); //agrego el nuevo nodo

		log_in_disk_per(LOG_LEVEL_TRACE,
				"Niveles de planificador %s con los recursos %s",
				param.PLAN_NIVELES[i],
				config_get_string_value(config, aux_str));
		i++;
	}

	return param;

}
示例#9
0
void* orquestador(void* plat) {
    t_plataforma* plataforma = (t_plataforma*) plat;
    t_orquestador* self = orquestador_create(PUERTO_ORQUESTADOR, plataforma);

    t_socket_client* acceptClosure(t_socket_server* server) {
        t_socket_client* client = sockets_accept(server);

        t_mensaje* mensaje = mensaje_recibir(client);

        if (mensaje == NULL) {
            sockets_destroyClient(client);
            pthread_mutex_lock(&plataforma->logger_mutex);
            log_warning(plataforma->logger,
                        "%s:%d -> Orquestador - Error al recibir datos en el accept",
                        sockets_getIp(client->socket),
                        sockets_getPort(client->socket));
            pthread_mutex_unlock(&plataforma->logger_mutex);
            return NULL;
        }

        int tipo_mensaje = mensaje->type;

        mensaje_destroy(mensaje);

        switch (tipo_mensaje) {
        case M_HANDSHAKE_PERSONAJE:
            responder_handshake(client, plataforma->logger,
                                &plataforma->logger_mutex, "Orquestador");
            orquestador_guardar_personaje(self, client, plataforma);
            break;
        case M_HANDSHAKE_NIVEL:
            responder_handshake(client, plataforma->logger,
                                &plataforma->logger_mutex, "Orquestador");
            if (!procesar_handshake_nivel(self, client, plataforma)) {
                orquestador_send_error_message("Error al procesar el handshake",
                                               client);
                return NULL;
            }
            break;
        default:
            pthread_mutex_lock(&plataforma->logger_mutex);
            char* error_msg = string_from_format(
                                  "Tipo del mensaje recibido no válido tipo: %d",
                                  tipo_mensaje);
            log_warning(plataforma->logger, error_msg);
            mensaje_create_and_send(M_ERROR, string_duplicate(error_msg),
                                    strlen(error_msg) + 1, client);
            free(error_msg);
            pthread_mutex_unlock(&plataforma->logger_mutex);
            orquestador_send_error_message("Request desconocido", client);
            return NULL ;
        }

        return client;
    }
/*
 Remove a directory
 */
int fs_rmdir(const char *path) {
	char* temp = string_from_format(path, "%s"); // no uso string_duplicate para evitar el warning de tipos.
	int err = 0;
	int hijos = 0;
	uint32_t bloque = 0;

	int filler(void *buf, const char *name, const struct stat *stbuf, off_t off) {
		int *i;
		i = buf;
		*i = *name;
		return 0;
	}
示例#11
0
int esperarConexionEntrante(int socketEscucha, int BACKLOG, t_log * logger) {

	listen(socketEscucha, BACKLOG);
	struct sockaddr_in addr;
	socklen_t addrlen = sizeof(addr);
	int socketCliente = accept(socketEscucha, (struct sockaddr *) &addr,
			&addrlen);
	log_info(logger,
			string_from_format("Se asigno el socket %d para el cliente",
					socketCliente));
	return socketCliente;

}
示例#12
0
int setup_listen_con_log(char* IP, char* Port, t_log * logger) {
	struct addrinfo* serverInfo = cargarInfoSocket(IP, Port);
	if (serverInfo == NULL)
		return -1;
	int socketEscucha;
	socketEscucha = socket(serverInfo->ai_family, serverInfo->ai_socktype,
			serverInfo->ai_protocol);
	log_info(logger,
			string_from_format("Escuchando conexiones en el socket %d",
					socketEscucha));
	bind(socketEscucha, serverInfo->ai_addr, serverInfo->ai_addrlen);
	freeaddrinfo(serverInfo);
	return socketEscucha;
}
示例#13
0
int conectarCliente_con_log(char *IP, char* Port, t_log * logger) {
	struct addrinfo* serverInfo = cargarInfoSocket(IP, Port);
	if (serverInfo == NULL) {
		return -1;
	}
	int serverSocket = socket(serverInfo->ai_family, serverInfo->ai_socktype,
			serverInfo->ai_protocol);
	if (serverSocket == -1) {
		log_error(logger,
				string_from_format("Error en la creación del socket"));
		return -1;
	}
	if (connect(serverSocket, serverInfo->ai_addr, serverInfo->ai_addrlen)
			== -1) {
		log_error(logger,
				string_from_format(
						"No se pudo conectar con el socket servidor\n"));
		close(serverSocket);
		return -1;
	}
	freeaddrinfo(serverInfo);
	return serverSocket;
}
示例#14
0
static void test_queCPUsoy() {
	t_cpu* cpuPrimera = crearCPU();
	t_cpu* cpuPrueba = crearCPU();
	char* resultado = string_new();
	resultado = queCPUsoy(cpuPrimera);
	printf("%s",resultado);
	//no se porque falla
//	CU_ASSERT_STRING_EQUAL(resultado, "soy la CPU segunda con numero 1");
	resultado = queCPUsoy(cpuPrueba);
	char* resultado2 = string_new();
	resultado2 = string_from_format("soy %s", resultado);
	string_append(&resultado2,"soy");
//	CU_ASSERT_STRING_EQUAL(resultado, "soy la cpu CPU tercera con numero 2");
	printf("%s \n",resultado2);
}
/*
 Create a directory

 Note that the mode argument may not have the type specification bits set, i.e. S_ISDIR(mode) can be false. To obtain the correct
 directory type bits use mode|S_IFDIR
 */
int fs_mkdir(const char *path, mode_t mode) {
	char* temp; // = string_from_format(path, "%s"); // no uso string_duplicate para evitar el warning de tipos.
	char** subpath;
	char* directorio = NULL;
	int i = 0;
	int err = 0;
	int ret = 0;
	GFile nodo;
	uint32_t bloque_padre = 0;

	//logger_info(logger, "Creo directorio:");
	//logear_path("fs_mkdir", path);
	if (strcmp(path, "/") == 0) {
		return -EPERM;
	}
	nodo.parent_dir_block = 0;
	temp = string_from_format(path, "%s");
	subpath = string_split(temp, "/");
	free(temp);
	while (subpath[i] != NULL ) {
		if (i == 2)
			ret = -EPERM;

		bloque_padre = nodo.parent_dir_block;
		directorio = subpath[i];
		err = buscar_bloque_por_padre(directorio, bloque_padre,
				&nodo.parent_dir_block);
		if (err && subpath[i + 1] != NULL )
			ret = -ENOENT;

		i++;
	};
	strcpy((char *) nodo.fname, directorio);

	liberar_subpath(subpath);
	
	if (ret)
		return ret;
	if (err == 0) { //Si la ultima busqueda no fallo significa que ya existe
		return -EEXIST;
	}
	nodo.c_date = time(NULL );
	nodo.m_date = nodo.c_date;
	nodo.file_size = 0;
	nodo.state = 2; // 0: borrado, 1: archivo, 2: directorio

	return agregar_nodo(&nodo);
}
示例#16
0
int hiloCPU() {

	t_cpu* cpu = crearCPU();

	list_add(procCPU->listaCPU, cpu);
	pthread_mutex_lock(&mutexCPULogs);
	log_info(logger, identificaCPU(queHiloSoy()));
	log_info(logger, "comienza ejecucion de un HILO ");
	log_info(logger,
			string_from_format("Me estoy levantando soy la cpu , %s \n",
					cpu->nombre));
	pthread_mutex_unlock(&mutexCPULogs);
//	printf("Me estoy levantando soy la cpu , %s", cpu->nombre);
//	printf("Creando CPU la id del hilo es %lu \n", cpu->idCPU);
	//conexiones = dictionary_create();

	int socketPlanificador;
	int socketMemoria;
	int resultConexion_mem = 0;
	int resultConexion_planif = 0;

	resultConexion_planif = conectar(configuracion->vg_ipPlanificador,
			string_itoa(configuracion->vg_puertoPlanificador),
			&socketPlanificador);
	if (resultConexion_planif == -1)
		pthread_mutex_lock(&mutexCPULogs);
	log_info(logger, identificaCPU(queHiloSoy()));
	log_error(logger, "[ERROR]no se conecto el CPU al Planificador");
	pthread_mutex_unlock(&mutexCPULogs);
	//dictionary_put(conexiones, "Planificador", string_itoa(socketPlanificador));
	cpu->socketPlanificador = socketPlanificador;
	enviarStruct(socketPlanificador, HANDSHAKE_CPU, getNombre());

	resultConexion_mem = conectar(configuracion->vg_ipMemoria,
			string_itoa(configuracion->vg_puertoMemoria), &socketMemoria);
	if (resultConexion_mem == -1)
		log_info(logger, identificaCPU(queHiloSoy()));
	log_error(logger, "[ERROR]no se conecto el CPU a la memoria");

	//dictionary_put(conexiones, "Memoria", string_itoa(socketMemoria));
	cpu->socketMemoria = socketMemoria;

	escucharConexiones("0", socketPlanificador, socketMemoria, 0,
			procesarMensajes, NULL, logger);

	return 0;
}
示例#17
0
void writeProcessPage(int pid, int nPage, char * content) {

	int absolutePage = getProcessFirstPage(pid) + nPage;

	int byteInicial = absolutePage * getSwapPagesSize();

	int tamanio = strlen(content) * sizeof(int);

	log_info(log_swap,
			string_from_format(
					"[mProc %d] solicitud de escritura en la página %d."
							"byte inicial: %d, tamanio: %d, contenido a escribir: %s",
					pid, nPage, byteInicial, tamanio, content));

	writePage(absolutePage, content);

}
示例#18
0
char * readProcessPage(int pid, int nPage) {

	int absolutePage = getProcessFirstPage(pid) + nPage;

	int byteInicial = absolutePage * getSwapPagesSize();

	int tamanio = strlen(readPage(absolutePage)) * sizeof(int);

	log_info(log_swap,
			string_from_format(
					"[mProc %d] Solicitud de lectura en la página %d. Byte inicial: %d,"
							"tamaño: %d, contenido: %s", pid, nPage,
					byteInicial, tamanio, readPage(absolutePage)));

	return readPage(absolutePage);

}
示例#19
0
	void throw_LastError(const string& message) {
	    // Retrieve the system error message for the last-error code
	    void * pszMessage;
	    auto dw = GetLastError();
	    FormatMessage(
	          FORMAT_MESSAGE_ALLOCATE_BUFFER |
	          FORMAT_MESSAGE_FROM_SYSTEM |
	          FORMAT_MESSAGE_IGNORE_INSERTS,
	          NULL,
	          dw,
	          MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
	          (LPTSTR) &pszMessage,
	          0, NULL );
	    const string msg(string_from_format("%s: %s",message.c_str(), pszMessage));
	    LocalFree(pszMessage);
	    throw runtime_error(msg);
	}
t_msg_id destruirSegmento(uint32_t pid, uint32_t baseSegmento) {

	char *stringPID = string_uitoa(pid);
	t_segmento* tabla = tablaDelProceso(stringPID);
	uint16_t numeroSegmento = segmento(baseSegmento);

	if(tabla && segmentoValido(tabla, numeroSegmento)) {

		char *shellInstruction;
		int pag,cantPagEnMemoria;
		uint16_t cantPaginas = cantidadPaginasTotalDelSegmento(tabla, numeroSegmento);

		for (cantPagEnMemoria = 0, pag = 0; pag < cantPaginas; ++pag)
			if (paginaEnMemoria(tabla, numeroSegmento, pag)) {
				++cantPagEnMemoria;
				++CantPaginasEnMemoriaDisponibles;
				liberarMarco(tabla, numeroSegmento, pag);
				QuitarDeEstructuraDeSeleccion(pid, numeroSegmento, pag);
				pthread_mutex_lock(&LogMutex);
				log_trace(Logger, "Marco %u desasignado al proceso %u.", marcoDePagina(tabla, numeroSegmento, pag), pid);
				pthread_mutex_unlock(&LogMutex);
			}

		/* Borra todas las páginas swappeadas del segmento */
		if (cantPagEnMemoria < cantPaginas) {
			shellInstruction = string_from_format("cd %s\nrm -f %s-%u-*", SWAP_PATH, stringPID, numeroSegmento);
			system(shellInstruction);
			free(shellInstruction);
		}

		CantPaginasDisponibles += cantPaginas;
		CantPaginasEnSwapDisponibles += cantPaginas - cantPagEnMemoria;
		free(tabla[numeroSegmento].tablaPaginas);
		tabla[numeroSegmento].limite = 0;

		//if(baseSegmento == 0)											/* Si es el segmento de código, se elimina el proceso de la tabla */
			//dictionary_remove(TablaSegmentosGlobal,stringPID);

		free(stringPID);
	}
	else
		return INVALID_DIR;

	return OK_DESTROY;

}
示例#21
0
static void test_string_get_string_full_array() {
	char* numbers = "[1, 2, 3, 4, 5]";
	char** numbers_array = string_get_string_as_array(numbers);
	CU_ASSERT_PTR_NOT_NULL(numbers_array);
	CU_ASSERT_PTR_EQUAL(numbers_array[5], NULL);
	
	int i;
	for (i = 1; i <= 5; ++i) {
		char* value = string_from_format("%d", i);
		CU_ASSERT_STRING_EQUAL(numbers_array[i - 1], value);
		free(value);
	}
	
	string_iterate_lines(numbers_array, (void*) free);
	free(numbers_array);

}
示例#22
0
sem_t* sem_crear(int* shmid, key_t* shmkey, int contador_ftok){
	sem_t* sem= NULL;
	//pid_t pid; /*      fork pid                */
	//unsigned int n; /*      fork count              */
	unsigned int value; /*      semaphore value         */

	/* initialize a shared variable in shared memory */

	char* sem_name = string_from_format("pSem_%d", contador_ftok);

	//shmkey = ftok("/dev/null", 5); /* valid directory name and a number */
	*shmkey = ftok("/dev/null", contador_ftok); /* valid directory name and a number */

	//printf("shmkey for p = %d\n", *shmkey);
	*shmid = shmget(*shmkey, sizeof(int), 0644 | IPC_CREAT);
	if (*shmid < 0) { /* shared memory error check */
		perror("shmget\n");
		exit(1);
	}

	///////////////////////////////////////////
	value = 0;
	/* initialize semaphores for shared processes */
	//sem = sem_open("pSem", O_CREAT | O_EXCL, 0644, value);


	//sem = sem_open("pSem", O_CREAT , 0644, value);
	sem = sem_open(sem_name, O_CREAT , 0644, value);
	if(sem==SEM_FAILED){
		perror("sem_open___");
		printf("***************************************************sdfadfasd\n");
		_exit(1);
	}

	/* name of semaphore is "pSem", semaphore is reached using this name */
	//sem_unlink("pSem");
	sem_unlink(sem_name);
	/* unlink prevents the semaphore existing forever */
	/* if a crash occurs during the execution         */
	//printf ("semaphores initialized.\n\n");

	FREE_NULL(sem_name);

	return sem;
}
/*
 Read data from an open file

 Read should return exactly the number of bytes requested except on EOF or error, otherwise the rest of the data will be substituted
 with zeroes. An exception to this is when the 'direct_io' mount option is specified, in which case the return value of the read system
 call will reflect the return value of this operation.
 */
int fs_read(const char *path, char *buf, size_t size, off_t offset,
		struct fuse_file_info *fi) {
	char* temp = string_from_format(path, "%s"); // no uso string_duplicate para evitar el warning de tipos.
	//logear_path("fs_read", path);
	//logger_info(logger, "fs_read: '%s' %zu bytes desde byte %i.", path, size,offset);

	uint indice = 0;
	int retorno = buscar_bloque_nodo(temp, &indice);

	free(temp);

	if (retorno) { // no existe.
		/*logger_info(logger, "fs_read: no encontre '%s' indice: '%i'.", temp,
		 indice);*/
		return -ENOENT;
	}
	return cargar_datos(&nodos[indice], buf, size, offset);
}
示例#24
0
tad_logger* logger_new_instance(const char* header, ...){
	alloc(ret, tad_logger);

	va_list args;
	va_start(args, header);
	char* formatted_header = string_from_vformat(header, args);

	if(strlen(formatted_header) == 0)
		ret->header = formatted_header;
	else{
		char* final_header = string_from_format("%s - ", formatted_header);
		ret->header = final_header;
		free(formatted_header);
	}

	ret->needs_dealloc = 1;

	return ret;
}
/*
 Open directory

 Unless the 'default_permissions' mount option is given, this method should check if opendir is permitted for this directory. Optionally opendir may also return an arbitrary filehandle in the fuse_file_info structure, which will be passed to readdir, closedir and fsyncdir.

 */
int fs_opendir(const char *path, struct fuse_file_info *fi) {
	char* temp = string_from_format(path, "%s"); // no uso string_duplicate para evitar el warning de tipos.
	//logear_path("fs_opendir", path);
	int err = 0;
	uint32_t bloque;
	if (strcmp(path, "/") == 0) {
		free(temp);
		return EXIT_SUCCESS;
	}

	err = buscar_bloque_nodo(temp, &bloque);
	free(temp);
	sem_wait(&mutex_nodos);
	if (!err && nodos[bloque].state == 2) {
		sem_post(&mutex_nodos);
		return EXIT_SUCCESS;
	} else {
		sem_post(&mutex_nodos);
		return -ENOENT;
	}

}
void test_read_full_array() {
	t_config* config = config_create(PATH_CONFIG);

	CU_ASSERT_EQUAL(config_keys_amount(config), KEYS_AMOUNT);

	CU_ASSERT_TRUE(config_has_property(config, "NUMBERS"));
	CU_ASSERT_STRING_EQUAL(config_get_string_value(config, "NUMBERS"), "[1, 2, 3, 4, 5]");

	char** numeros = config_get_array_value(config, "NUMBERS");
	CU_ASSERT_PTR_NOT_NULL(numeros);
	CU_ASSERT_PTR_EQUAL(numeros[5], NULL);

	int i;
	for (i = 1; i <= 5; ++i) {
		char* value = string_from_format("%d", i);
		CU_ASSERT_STRING_EQUAL(numeros[i - 1], value);
		free(value);
	}

	string_iterate_lines(numeros, (void*) free);
	free(numeros);
	config_destroy(config);
}
/*
 Remove a file
 */
int fs_unlink(const char *path) {
	//logger_info(logger, "Elimino archivo:");
	//logear_path("fs_unlink", path);
	char* temp = string_from_format(path, "%s"); // no uso string_duplicate para evitar el warning de tipos.
	int err = 0;
	uint32_t bloque = 0;

	err = buscar_bloque_nodo(temp, &bloque);
	free(temp);
	if (err) {
		return -ENOENT;
	}
	err = borrar_nodo(bloque);
	if (err) {
		return err;
	}
	// marcar los bloques en el mapa de bits como vacios
	err = liberar_espacio(bloque);
	if (err) {
		return err;
	}
	return EXIT_SUCCESS;
}
t_personaje* personaje_crear(char* config_path) {
    //creamos una instancia de personaje
    alloc(self, t_personaje);

    //creamos una instancia del lector de archivos de config
    t_config* config = config_create(config_path);
    t_config* global_config = config_create("global.cfg");

    //datos basicos del personaje
    self->nombre = string_duplicate(config_get_string_value(config, "Nombre"));
    self->simbolo = *config_get_string_value(config, "Simbolo");
    int vidas = config_get_int_value(config, "Vidas");
    self->vidas_iniciales = vidas;
    self->vidas = vidas;

    //misc
    if(config_has_property(global_config, "AutoContinue")) self->auto_continue = config_get_int_value(global_config, "AutoContinue");
    else self->auto_continue = 0;

    //datos del logger
    char* log_file;
    if(config_has_property(config,"LogFile")) log_file = string_duplicate(config_get_string_value(config, "LogFile"));
    else log_file = string_from_format("%s.log", self->nombre);

    char* log_level;
    if(config_has_property(global_config, "LogLevel")) log_level = config_get_string_value(global_config, "LogLevel");
    else if(config_has_property(config, "LogLevel")) log_level = config_get_string_value(config, "LogLevel");
    else log_level = "INFO";

    //inicializamos el logger
    logger_initialize(log_file, "personaje", log_level, 1);
    self->logger = logger_new_instance();
    var(logger, self->logger);

    //datos de plataforma
    char* plataforma;
    if(config_has_property(global_config, "Plataforma"))
        plataforma = string_duplicate(config_get_string_value(global_config, "Plataforma"));
    else
        plataforma = string_duplicate(config_get_string_value(config, "Plataforma"));
    self->ippuerto_orquestador = plataforma;

    //datos de niveles y objetivos
    char** nombres_niveles = config_get_array_value(config, "Niveles");
    t_list* niveles = list_create();
    int i = 0;
    char* nombre_nivel = nombres_niveles[i];

    while(nombre_nivel != null) {
        alloc(nivel, t_nivel);
        nivel->nombre = string_duplicate(nombre_nivel);
        nivel->objetivos = list_create();

        char* key_objetivos = string_from_format("Obj[%s]", nombre_nivel);
        char* objetivos = config_get_string_value(config, key_objetivos);

        logger_info(logger, "Nivel: %s", nivel->nombre);
        logger_info(logger, "Objetivos: %s", objetivos);
        int ii = 0;
        while(objetivos != null && objetivos[ii] != '\0') {
            char* objetivo = string_from_format("%c" , objetivos[ii]);
            list_add(nivel->objetivos, objetivo);
            ii++;
        }

        free(key_objetivos);

        list_add(niveles, nivel);

        i++;
        nombre_nivel = nombres_niveles[i];
    }
    self->niveles = niveles;

    logger_info(logger, "Log File:%s", log_file);
    free(log_file);
    logger_info(logger, "Log Level:%s", log_level);

    //liberamos recursos
    config_destroy(config);
    config_destroy(global_config);
    liberar_niveles(nombres_niveles);

    return self;
}
char* string_itoa(int number) {
    return string_from_format("%d", number);
}
struct h_t_param_nivel leer_nivel_config(int rows, int cols) {
	t_config* config;
	struct h_t_param_nivel param;
	t_recusos *list_recursos; //declaro el tipo nodo
	char *aux_str;
	int i, j;
	char **aux;
	char *aux_char;

	log_in_disk_niv(LOG_LEVEL_TRACE,
			"comienzo lectura archivo de configuracion del nivel en el %s ",
			PATH_CONFIG_NIVEL);

	log_in_disk_niv(LOG_LEVEL_TRACE, "limites de pantalla x = %d ,y = %d", rows,
			cols);
	param.recusos = list_create(); //creo lista de hilos
	config = config_create(PATH_CONFIG_NIVEL);

	//param.nom_nivel = nivel; //copio el nombre del nivel que pase por parametro en el main

	aux_char = config_get_string_value(config, "PLATAFORMA");

	aux = string_split(aux_char, ":");
	param.IP = aux[0];
	param.PUERTO_PLATAFORMA = atoi(aux[1]);

	param.PUERTO = config_get_int_value(config, "PUERTO");
	param.nom_nivel = config_get_string_value(config, "NOMBRE");

	i = 1;

	aux_str = string_from_format("%s%d", "CAJA", i);

	while ((aux = config_get_array_value(config, aux_str)) != NULL ) {

		list_recursos = malloc(sizeof(t_recusos)); //creo el nodo
		j = 0;

		strcpy(list_recursos->NOMBRE, aux[j++]);
		if (!strcmp(list_recursos->NOMBRE, "Fin")) {
			break; //salgo del for cuando encuentro la caja de fin
		}
		list_recursos->SIMBOLO = aux[j++][0];
		list_recursos->cantidad = atoi(aux[j++]);
		list_recursos->posX = atoi(aux[j++]);
		list_recursos->posY = atoi(aux[j]);

		if (val_pos_recurso(rows, cols, list_recursos->posX,
				list_recursos->posY)) {

			log_in_disk_niv(LOG_LEVEL_TRACE,
					"Cargo a la lista la caja %s que contiene el recurso %s con el simbolo %c y la candidad %d en la poscion [x,y] [%d][%d] ",
					aux_str, list_recursos->NOMBRE, list_recursos->SIMBOLO,
					list_recursos->cantidad, list_recursos->posX,
					list_recursos->posY);

			list_add(param.recusos, list_recursos); //agrego el nuevo nodo

		} else {
			log_in_disk_niv(LOG_LEVEL_ERROR,
					"Cargo a la lista la caja %s que contiene el recurso %s con el simbolo %c y la candidad %d en la poscion [x,y] [%d][%d] ES INVELIDA!!",
					aux_str, list_recursos->NOMBRE, list_recursos->SIMBOLO,
					list_recursos->cantidad, list_recursos->posX,
					list_recursos->posY);

		}

		aux_str = string_from_format("%s%d", "CAJA", ++i);
	}

	param.TiempoChequeoDeadlock = config_get_int_value(config,
			"TiempoChequeoDeadlock");
	param.Recovery = config_get_int_value(config, "RECOVERY");

	return param;

}