static int ascii_init(void) {

	void *ptr_err;
	major = register_chrdev(0, DEVICE_NAME, &fops );

	if(major < 0){
		printk(KERN_INFO "Char device registering failed\n");
		return major;
	}
	printk(KERN_INFO "Device successfully created with major number: %d.\n", major);

	class_ascii = class_create(THIS_MODULE, DEVICE_NAME);

	if(IS_ERR(ptr_err = class_ascii)){
		printk(KERN_INFO "Creating class failed. Unregistering device.\n");
		unregister_chrdev(major, DEVICE_NAME);
		return PTR_ERR(ptr_err);
	}

	dev_ascii = device_create(class_ascii, NULL, MKDEV(major, 0), NULL, DEVICE_NAME);

	if(IS_ERR(ptr_err = dev_ascii)){
		printk(KERN_INFO "Creating Device failed. Unregistering device.\n");
		class_destroy(class_ascii);
		unregister_chrdev(major, DEVICE_NAME);
		return PTR_ERR(ptr_err);
	}

	init_semaphores();
	queue_init();
	initEmptyArray();
	timer_init();

	return 0;
}
Ejemplo n.º 2
0
main(void)
{
    
    set_eflags();
    
    /* Define the kernel segment registers  and a stack to execute the 'main' code */
    // It is necessary to use a global static array for the stack, because the
    // compiler will know its final memory location. Otherwise it will try to use the
    // 'ds' register to access the address... but we are not ready for that yet
    // (we are still in real mode).
    set_seg_regs(__KERNEL_DS, __KERNEL_DS, (DWord) &protected_tasks[5]);
    
    printk("Kernel Loaded!    ");
    
    /* Initialize hardware data */
    setGdt(); /* Definicio de la taula de segments de memoria */
    setIdt(); /* Definicio del vector de interrupcions */
    setTSS(); /* Definicio de la TSS */
    
    /* Initialize Memory */
    init_mm();
    
    /* Initialize an address space to be used for the monoprocess version of ZeOS */
    
    monoprocess_init_addr_space(); /* TO BE DELETED WHEN ADDED THE PROCESS MANAGEMENT CODE TO BECOME MULTIPROCESS */
    
    /* Initialize Scheduling */
    init_sched();
    
    /* Initialize idle task  data */
    init_idle();
    /* Initialize task 1 data */
    init_task1();

    /* Initialize semaphores */
    init_semaphores();
    
    /* Move user code/data now (after the page table initialization) */
    copy_data((void *) KERNEL_START + *p_sys_size, usr_main, *p_usr_size);
    
    
    printk("Entering user mode...");
    
    enable_int();
    /*
     * We return from a 'theorical' call to a 'call gate' to reduce our privileges
     * and going to execute 'magically' at 'usr_main'...
     */
    return_gate(__USER_DS, __USER_DS, USER_ESP, __USER_CS, L_USER_START);
    
    /* The execution never arrives to this point */
    return 0;
}
Ejemplo n.º 3
0
/* Slurmctld and slurmd do not really build shared memory but they use that one built by sim_mgr */
int building_shared_memory(){

    int fd;

    fd = shm_open(SLURM_SIM_SHM, O_RDWR, S_IRUSR | S_IWUSR);
    if(fd < 0){
        printf("Error opening %s\n", SLURM_SIM_SHM);
        return -1;
    }

    ftruncate(fd, 8192);

    timemgr_data = mmap(0, 8192, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    if(!timemgr_data){
        printf("mmaping %s file can not be done\n", SLURM_SIM_SHM);
        return -1;
    }

    /* Initializing pointers to shared memory */
    current_sim = timemgr_data + SIM_SECONDS_OFFSET;
    current_micro = timemgr_data + SIM_MICROSECONDS_OFFSET;
    threads_data = timemgr_data + SIM_SYNC_ARRAY_OFFSET;
    current_threads = timemgr_data + SIM_THREADS_COUNT_OFFSET;
    proto_threads = timemgr_data + SIM_PROTO_THREADS_OFFSET;
    sleep_map_array = timemgr_data + SIM_SLEEP_ARRAY_MAP_OFFSET;
    thread_exit_array = timemgr_data + SIM_THREAD_EXIT_MAP_OFFSET;
    thread_new_array = timemgr_data + SIM_THREAD_NEW_MAP_OFFSET;
    fast_threads_counter = timemgr_data + SIM_FAST_THREADS_OFFSET;
    pthread_create_counter = timemgr_data + SIM_PTHREAD_CREATE_COUNTER;
    pthread_exit_counter = timemgr_data + SIM_PTHREAD_EXIT_COUNTER;
    slurmctl_pid = timemgr_data + SIM_PTHREAD_SLURMCTL_PID;
    slurmd_pid = timemgr_data + SIM_PTHREAD_SLURMD_PID;

    if((slurmctl_pid[0] == 0) || (slurmd_pid[0] == 0)){

        register_program();

        if(init_semaphores() < 0){
            printf("semaphores initialization failed\n");
            return 1;
        }
    }

    return 0;
}
Ejemplo n.º 4
0
/*******************************************************************************
 *	NOME:		main
 *	FUNÇÃO:		Chama as funcoes que iniciam as threads
 *
 *			Tipo					Descrição
 *     		pthread_t*				Thread servidor declarada na main
 *     		pthread_t*				Thread cliente declarada na main
 *
 *	RETORNO:	int	(0 se threads foram criadas com sucesso, 1 se nao foram)
 *******************************************************************************/
int main(int argc,char **argv){
	int erro = 0;
	prog_end = 0;
	client_add = 0;
	client_send = 0;
	numdecontatos = 0;
	char filename[25];

	pthread_t serverthread, clientthread, menuthread;

	printf("Digite o numero da porta da aplicacao: ");
	scanf("%d", &PORTA);

	__fpurge(stdin);
	printf("Digite o seu endereco de IP: ");
	fgets(filename, 16, stdin);
	strtok(filename, "\n");
	__fpurge(stdin);

	strcat(filename, "chat.txt");


	chat_log = fopen(filename, "w+b");

	if(chat_log == NULL){
		printf("Erro na abertura do arquivo");
	}
	else{
		fputc('0', chat_log);
	}

	init_semaphores();
	erro = init_threads(&serverthread, &clientthread, &menuthread);
	if (erro == 1){	//Significa que as threads nao foram criadas. Logo o programa nao pode prosseguir.
		return 1;
	}
	else{
		pthread_join(menuthread, NULL);
	    pthread_join(clientthread, NULL);
		return 0;
	}
}
Ejemplo n.º 5
0
int main(void)
{
  IntMasterDisable();

  /* Set up hardware */
  hardware_setup();
  init_semaphores();
  init_queues();

  /* Module initialization */
  if (spi_init() &&
      uart_init_task() &&
      uart_protocol_init_task() &&
      status_led_task_init() &&
      uart_echo_init() &&
      par_updater_init() &&
      (xTaskCreate(dreh_task,     NAME("Dreh"),    DEFAULT_STACK, NULL, PRIORITY_LOW,   &task_handles[DREH_T])) == pdPASS &&
      (xTaskCreate(lcd_task,      NAME("LCD"),     DEFAULT_STACK, NULL, PRIORITY_LOW,   &task_handles[LCD_T])) == pdPASS &&
      (xTaskCreate(menu_task,     NAME("Menu"),    LARGE_STACK,   NULL, PRIORITY_LOW,   &task_handles[MENU_T])) == pdPASS &&
      (xTaskCreate(numpad_task,   NAME("Numpad"),  DEFAULT_STACK, NULL, PRIORITY_LOW,   &task_handles[NUMPAD_T])) == pdPASS &&
      (xTaskCreate(control_task,  NAME("Control"), DEFAULT_STACK, NULL, PRIORITY_HIGH,  &task_handles[CONTROL_T])) == pdPASS &&
      (xTaskCreate(blink_task,    NAME("Blink"),   DEFAULT_STACK, NULL, PRIORITY_LOW,   &task_handles[BLINK_T])) == pdPASS &&
      uart_to_spi_init() &&
      step_response_init() &&
      itc_init_uartprinter()
      #ifdef DEBUG
      && spi_test_init()
      && runtimestats_init()
      #endif /* DEBUG */
     )
  {
    vTaskStartScheduler();
  }

  while (1)
  {
    /* Will only get here if initialization went wrong. */
  }

  return 1;
}
Ejemplo n.º 6
0
/*******************************************************************************
 *	NOME:		main
 *	FUNÇÃO:		Chama as funcoes que iniciam as threads
 *
 *			Tipo					Descrição
 *     		pthread_t*				Thread servidor declarada na main
 *     		pthread_t*				Thread cliente declarada na main
 *
 *	RETORNO:	int	(0 se threads foram criadas com sucesso, 1 se nao foram)
 *******************************************************************************/
int main(int argc,char **argv){
	int erro = 0;
	prog_end = 0;
	client_add = 0;
	client_send = 0;
	numdecontatos = 0;

	pthread_t serverthread, clientthread, menuthread;

	init_semaphores();
	erro = init_threads(&serverthread, &clientthread, &menuthread);
	if (erro == 1){	//Significa que as threads nao foram criadas. Logo o programa nao pode prosseguir.
		return 1;
	}
	else{
		pthread_join(menuthread, NULL);
	    pthread_join(clientthread, NULL);
	    pthread_join(serverthread, NULL);
		return 0;
	}
}
Ejemplo n.º 7
0
int main(int argc, char **argv) {

    int server_fd, port_number, max_fd, file_descriptors[MAX_NUMBER_USERS], i;
    int temp_fd, select_result, timer_is_active = FALSE, status_code;

    char *validation;

    fd_set file_descriptor_set;

    check_incorrect_usage(argc, argv);
    set_log_method(argv);
    set_lock();

    port_number = extract_port_number(argv);
    server_fd = create_server(port_number, MAX_NUMBER_USERS);
    log_message("Streams server created", LOG_INFO);

    register_signal_handlers();

    for (i = 0; i < MAX_NUMBER_USERS; i++) {
        file_descriptors[i] = 0;
    }

    // -- SHARED MEMORY AND SEMAPHORES --

    shmid = create_shared_memory();
    shared_mem_ptr = attach_memory(shmid);
    init_semaphores();

    log_message("Shared memory and semaphores created", LOG_DEBUG);

    // -- SERVER LOOP --

    while (TRUE) {

        FD_ZERO(&file_descriptor_set);
        FD_SET(server_fd, &file_descriptor_set);
        max_fd = server_fd;

        for (i = 0; i < MAX_NUMBER_USERS; i++) {
            temp_fd = file_descriptors[i];

            if (temp_fd > 0) {
                FD_SET(temp_fd, &file_descriptor_set);
            }

            if (temp_fd > max_fd) {
                max_fd = temp_fd;
            }
        }

        select_result = select(max_fd + 1, &file_descriptor_set, NULL, NULL, NULL);

        if (select_result < 0 && errno != EINTR) {
            log_error("Select call error", LOG_WARNING, errno);
            continue;
        }

        if (FD_ISSET(server_fd, &file_descriptor_set)) {

            if ((temp_fd = accept(server_fd, NULL, 0)) < 0) {
                log_error("Could not accept incoming connection", LOG_ALERT, errno);
                exit(EXIT_FAILURE);
            }

            log_client_connection(temp_fd);

            for (i = 0; i < MAX_NUMBER_USERS; i++) {
                if (file_descriptors[i] != 0)
                    continue;

                file_descriptors[i] = temp_fd;
                break;
            }
        }

        for (i = 0; i < MAX_NUMBER_USERS; i++) {

            temp_fd = file_descriptors[i];

            if (!FD_ISSET(temp_fd, &file_descriptor_set))
                continue;

            char *message = NULL;
            if ((message = (char *) calloc(MESSAGE_LENGTH, sizeof(char))) == NULL) {
                log_error("Memory allocation error", LOG_ALERT, errno);
                exit(EXIT_FAILURE);
            }

            if (recv(temp_fd, message, MESSAGE_LENGTH, 0) <= 0)   // Disconnected
            {
                log_message("Client disconnected", LOG_INFO);

                close(temp_fd);
                file_descriptors[i] = 0;
            }
            else    // Message sent to server
            {
                struct message_t mess=decode(message);

                if( (status_code = mess.type) == ERROR_MESSAGE) {
                    continue;
                }

                if (get_game_phase() == REGISTER_PHASE) {

                    if (status_code != 1) {
                        // TODO Send message back to user?
                        log_message("Currently register phase. User can only register", LOG_DEBUG);
                        continue;
                    }

                    if (!timer_is_active) {
                        log_message("Starting register timer", LOG_DEBUG);
                        alarm(WAIT_TIME);
                        timer_is_active = TRUE;
                    }

                    char *new_user = (char *) malloc(MAX_ARRAY_SIZE * sizeof(char));
                    sprintf(new_user, "User '%s' asks for registration. Adding user in memory.", (char *) mess.payload);
                    log_message(new_user, LOG_INFO);

                    // Add a player to the shared memory
                    semaphore_down(SEMAPHORE_ACCESS);
                    strncpy(shared_mem_ptr->players->name, (char *) mess.payload, strlen(mess.payload));
                    shared_mem_ptr->players[i].fd = temp_fd;
                    shared_mem_ptr->players[i].score = 15; // TODO A supprimer
                    semaphore_up(SEMAPHORE_ACCESS);

                    validation = encode(VALID_REGISTRATION, "1");
                    send(temp_fd, validation, strlen(validation), 0);
                }
                else    // GAME PHASE
                {
                    log_message("Game phase. Not yet implemented.", LOG_INFO);
                }

            }
        }
    }

    return 0;
}
int main(int argc, char **argv)
{
    int n, m, k, shmid, semid, producers;
    key_t ipckey;
    char filepath[PATH_MAX];
    union semun ignored;
    
    printf("Synchronizacja procesow z wykorzystaniem semaforow\n");
    if(argc != 4)
    {
        printf( "Uzycie: %s n m k\n"
                "n - liczba producentow\n"
                "m - rozmiar kolejki\n"
                "k - liczba jednostek towaru, czyli liczb, ktore powinien wstawic kazdy producent do bufora\n", argv[0]);
        return 1;
    }
    
    n = atoi(argv[1]);
    m = atoi(argv[2]);
    k = atoi(argv[3]);
    
    /*
        sprawdamy wszystkie warunki niezbedne do przejscia dalej.
    */
    if(n <= 0) return die("n <= 0");
    if(m <= 0) return die("m <= 0");
    if(k <= 0) return die("k <= 0");
    if((getpagesize()!=4096) || (sizeof(int)!=4)) return die("Ten program nie zadziala na tym komputerze ze wzgledu na egzotyczne rozmiary zmiennych.");
    if(n>1022) return die("Ta wersja obsluguje kolejki do 1022 elementow."); 
    producers = n;
    
    /*
        Do dziela - zdobadzmy klucz       
    */
    //w manie prosza o accessible filepath, takze zdobadzmy je:
    realpath(argv[0], filepath);
    ipckey = ftok(filepath, n);
    if(ipckey == -1) return die("ftok zwrocilo blad");
    
    /*
        alokacja pamieci wspoldzielonej & semaforow.
    */
    shmid = shmget(ipckey, getpagesize(), IPC_CREAT | S_IRUSR | S_IWUSR | IPC_EXCL); //flagi: tworzenie, uprawnienia do czytania&pisania, wylacznosc.
    if(shmid == -1) return die("shmget zwrocilo blad");
    
    semid = semget(ipckey, SEM_NR, IPC_CREAT | S_IRUSR | S_IWUSR | IPC_EXCL);
    if(semid == -1) return die("semget zwrocilo blad");
    
    if(init_semaphores(semid, m)==-1) return die("init_sempahores zwrocilo blad");
    if(init_shared_memory(shmid, m)==-1) return  die("init_shared_memory zwrocilo blad");
    
    //puts("Przerwa techniczna. Wcisnij enter, aby kontynuowac.");
    //getchar();
    while(--producers>=0)   
        if(spawn(producers, n, m, k, shmid, semid)==0) return 0;
    
    //void Client(int shmid, int semid, int m,int elem_to_process)
    Client(shmid, semid, m, n*k);
    
    shmctl(shmid, IPC_RMID, 0);   
    semctl(semid, SEM_NR, IPC_RMID, ignored);
}