Example #1
0
static void person_process(int id) {
	init_random();
	char buf[4096];
    struct lift_msg * reply;
	struct lift_msg m;
    m.person_id = id;
    int len;
    //printf("Created person with id %d\n", m.person_id);
	while(1) {
        // TODO:
		//    Generate a to and from floor
		//    Send a LIFT_TRAVEL message to the lift process
        //    Wait for a LIFT_TRAVEL_DONE message
		//    Wait a little while
	  //printf("Morning! This is number %d speaking.\n", id);
        m.from_floor = get_random_value(id, N_FLOORS - 1);
        do {
            m.to_floor = get_random_value(id, N_FLOORS - 1);
        } while(m.from_floor == m.to_floor);
        //printf("Person %d wants to go to floor %d\n", m.person_id,  m.to_floor);
        m.type = LIFT_TRAVEL;
        message_send((char *) &m, sizeof(m), QUEUE_LIFT, 0);

        do { 
            len = message_receive(buf, 4096, QUEUE_FIRSTPERSON + id); // Wait for a message
            if(len < sizeof(struct lift_msg)) {
                fprintf(stderr, "Message too short\n");
                continue;
            }
            reply = ((struct lift_msg*) buf);
         } while(reply->type != LIFT_TRAVEL_DONE);
        //printf("Going to sleep. Number %d\n", id);
        usleep(1000000);
    }
}
Example #2
0
t_error		thread_state_unlock(t_id		arg1,
				    t_state		arg2,
				    t_uint8*		lock)
{
  o_syscall		message;
  i_node		node;
  t_vsize		size;

  node.machine = 0;
  node.task = 0;

  message.id = 0;

  message.u.request.operation = INTERFACE_THREAD_STATE;
  message.u.request.u.thread_state.arg1 = arg1;
  message.u.request.u.thread_state.arg2 = arg2;

  message_send_unlock(node, MESSAGE_TYPE_INTERFACE, (t_vaddr)&message, sizeof (message), lock);

  if (message_receive(MESSAGE_TYPE_INTERFACE, (t_vaddr)&message, &size, &node) != ERROR_NONE)
    return (ERROR_UNKNOWN);

  if (message.u.reply.error != ERROR_NONE)
    return (ERROR_UNKNOWN);

  return (ERROR_NONE);
}
Example #3
0
int tst_alarm(void)
{
  int i;
  //int rc;
  //int alarm;
  struct msg_head selected_msg;

  for(i=0;i<10;i++) {
    display_puts("@");
    syscall_wait(50);
  }
  display_puts("\n");

  for(i=0;i<10;i++) {
    display_puts("@");
    syscall_alarm_set(50,environment_getqueid(),0x00010000);
    selected_msg.size=sizeof(selected_msg);
    message_poll(MESSAGE_MODE_WAIT, 0, 0, &selected_msg);
    message_receive(MESSAGE_MODE_TRY, 0, 0, &selected_msg);
  }
  display_puts("\n");


  return 0;
}
Example #4
0
int cdfs_getinfo_response(unsigned short *seq, int *typecode)
{
  union cdfs_msg msg;
  int rc;

  if(cdfs_queid==0) {
    rc=cdfs_init();
    if(rc<0)
      return rc;
  }

  msg.h.size=sizeof(msg);
  rc=message_receive(MESSAGE_MODE_WAIT,CDFS_SRV_CDFS, CDFS_CMD_GETINFO, &msg);
  if(rc<0) {
    display_puts("getcode getresp=");
    int2dec(-rc,s);
    display_puts(s);
    display_puts("\n");
    return rc;
  }
  *seq = msg.getinfo.res.seq;
  *typecode = msg.getinfo.res.type;

  return 0;
}
Example #5
0
int cdfs_open_response(unsigned short *seq, int *handle)
{
  union cdfs_msg msg;
  int rc;

  if(cdfs_queid==0) {
    rc=cdfs_init();
    if(rc<0)
      return rc;
  }

  msg.h.size=sizeof(msg);
  rc=message_receive(MESSAGE_MODE_WAIT,CDFS_SRV_CDFS, CDFS_CMD_OPEN, &msg);
  if(rc<0) {
    display_puts("cdfs open=");
    int2dec(-rc,s);
    display_puts(s);
    display_puts("\n");
    return rc;
  }
  *seq = msg.open.res.seq;
  *handle = msg.open.res.handle;

  return rc;
}
Example #6
0
int cdfs_read_response(unsigned short *seq, int *readbyte)
{
  union cdfs_msg msg;
  int rc;

  if(cdfs_queid==0) {
    rc=cdfs_init();
    if(rc<0)
      return rc;
  }

  msg.h.size=sizeof(msg);
  rc=message_receive(MESSAGE_MODE_WAIT,CDFS_SRV_CDFS, CDFS_CMD_READ, &msg);
  if(rc<0) {
    display_puts("getcode getresp=");
    int2dec(-rc,s);
    display_puts(s);
    display_puts("\n");
    return rc;
  }
  *seq = msg.read.res.seq;
  *readbyte = msg.read.res.readbyte;

  return rc;
}
Example #7
0
int cdfs_stat_response(unsigned short *seq, struct file_info *info, unsigned long bufsize)
{
  union cdfs_msg msg;
  int rc;

  if(cdfs_queid==0) {
    rc=cdfs_init();
    if(rc<0)
      return rc;
  }

  msg.h.size=sizeof(msg);
  rc=message_receive(MESSAGE_MODE_WAIT,CDFS_SRV_CDFS, CDFS_CMD_STAT, &msg);
  if(rc<0) {
    display_puts("getcode getresp=");
    int2dec(-rc,s);
    display_puts(s);
    display_puts("\n");
    return rc;
  }
  *seq = msg.stat.res.seq;
  unsigned long len = sizeof(struct file_info);
  if(len>bufsize)
    len = bufsize;
  memcpy(info, &msg.stat.res.info, len);
  if((int)(msg.stat.res.info.size) == -1)
    return 0;
  if(bufsize < sizeof(struct file_info))
    return 0;

  return 0;
}
Example #8
0
int main( void ) {
	Status status;
	Pid pid;
	char *message = "This is the test message.";

	status = fork( &pid );
	if ( status == SUCCESS ) {
		if ( pid > 0) { //in parent
			sleep(2); //sleep for two seconds
			status = message_send( pid, message, 26 );
			if ( status == SUCCESS ) {
				writef( "User messages_test(Parent) message_send status SUCCESS\n", status);
			} else {
				writef( "User messages_test(Parent) message_send status FAILED(%d)\n", status);
				exit();
			}
		} else { //in child
			char *receivedMessage;
			Uint32 size;
			Pid fromPid;
			//sleep(2);
			writef( "User messages_test(Child) waiting for message\n");
			status = message_receive( &fromPid, (void**) &receivedMessage, &size );
			if ( status == SUCCESS ) {
				writef( "User messages_test(Child) received from %d of size %d: %s\n", fromPid, size, receivedMessage );
			} else {
				writef( "User messages_test(Child) message_receive status FAILED(%d)\n", status);
				exit();
			}
		}
	} else {
		writef( "User messages_test fork status FAILED(%d)\n", status);
	}
}
Example #9
0
// This process is responsible for drawing the lift. Receives lift_type structures
// as messages.
void uidraw_process(void) {
    char msg[1024];
    si_ui_set_size(670, 700);
    while(1) {
        message_receive(msg, 1024, QUEUE_UI);
        lift_type Lift = (lift_type) &msg[0];
        //      draw_lift(Lift);
    }
}
Example #10
0
void result_process(void)
{
  int processes_done = 0;
  char buf[1024];
  struct lift_msg* msg;
  while(1){
    message_receive(buf, 1024, QUEUE_RESULT);
    msg = (struct lift_msg *)buf;
    if(msg->type == PROCESS_DONE){
      processes_done++;
    }
    if(processes_done == MAX_N_PERSONS){
      //Clear file contents
      printf("Clearing file\n");
      FILE *f = fopen("multi_travels.txt", "w");
      if (f == NULL)
	{
	  printf("Error opening file!\n");
	  exit(1);
	}
      fclose(f);

      int i;
      for(i = 0; i < MAX_N_PERSONS; i++){
	printf("Sending write command to process %d\n",i);
	msg->type = WRITE_TO_FILE;
	message_send((char *)msg, sizeof(struct lift_msg), QUEUE_FIRSTPERSON+i, 0);
	message_receive(buf, 1024, QUEUE_RESULT);
      }
      break;
    }
  }

  //kill(uidraw_pid, SIGINT);
  kill(lift_pid, SIGINT);
  kill(liftmove_pid, SIGINT);
  int i;
  for(i=0; i < MAX_N_PERSONS; i++){
    if(person_pid[i] > 0){
      kill(person_pid[i], SIGINT);
    }
  } 
  
}
Example #11
0
//static void reaper(int signum) { while(waitpid(WAIT_ANY, NULL, WNOHANG) > 0); }
static void reaper(void)
{
  struct msg_head msg;
  int r;

  msg.size=sizeof(msg);
  r = message_receive(MESSAGE_MODE_TRY, MSG_SRV_KERNEL, MSG_CMD_KRN_EXIT, &msg);
  if(r<0)
    return;
  syscall_pgm_delete(msg.arg);
}
Example #12
0
string
tm_link_rep::read_packet (int channel, int timeout, bool& success) {
  success= false;
  string& r= watch (channel);
  time_t start= texmacs_time ();
  while (!message_complete (r)) {
    int n= N(r);
    if (timeout > 0) listen (timeout);
    if (N(r) == n && (texmacs_time () - start >= timeout)) return "";
  }
  if (channel == LINK_OUT && N(r) > 0 && r[0] == '!') {
    secure_server (message_receive (r));
    return "";
  }
  else {
    string back= message_receive (r);
    if (secret != "") back= secret_decode (back, secret);
    success= true;
    return back;
  }
}
Example #13
0
/* Simple guardian process serving as a barrier for the file
 * Short implementation to not interfere too much
 */
void file_guard_process(void) {
    char buf[1024];
    int n_finished = 0;
    int len, i;
    struct lift_msg * received;
    struct lift_msg reply;
    reply.type = FILE_WRITE;

    while(n_finished < MAX_N_PERSONS) {
        len = message_receive(buf, 4096, QUEUE_FILE); // Wait for a message
        if(len < sizeof(struct lift_msg)) {
            fprintf(stderr, "Message too short\n");
            continue;
        }
        received = ((struct lift_msg*) buf);
        //printf("File guard received a message from %d\n", received->person_id);
        if (received->type == FILE_ASK) {
            n_finished++;
        }
    }

    for (i=0; i < MAX_N_PERSONS; i++) {
        message_send((char *) &reply, sizeof(reply), QUEUE_FIRSTPERSON + i, 0);
        do {
            len = message_receive(buf, 4096, QUEUE_FILE); // Wait for a reply from person proc
            if(len < sizeof(struct lift_msg)) {
                fprintf(stderr, "Message too short\n");
                continue;
            }
            received = ((struct lift_msg*) buf);
            //printf("Guard received a message from %d\n", received->person_id);
        } while(received->type != FILE_DONE);
    }

    printf("File guard proc finished\n");
    exit(0);
}
Example #14
0
File: echo.c Project: mycure/kayou
int				echo_serve(void)
{
  t_service_echo_message*	message;
  i_node			sender;
  t_vsize			size;

  printf("server echo OK\n");
  if ((message = malloc(sizeof (*message))) == NULL)
    {
      printf(" -- echo: memory exhausted\n");
      return (-1);
    }

  while (1)
    {
      if (message_receive(MESSAGE_TYPE_SERVICE_ECHO,
			  (t_vaddr)message,
			  &size,
			  &sender) == ERROR_NONE)
	{
	  switch (message->u.request.operation)
	    {
	      case ECHO_SERVICE_ECHO:
		printf(" -- echo: %s\n", message->u.request.u.echo.text);

		memmove(message->u.reply.u.echo.text,
			message->u.request.u.echo.text,
			strlen(message->u.request.u.echo.text) + 1);

		if (message_send(sender,
				 MESSAGE_TYPE_SERVICE_ECHO,
				 (t_vaddr)message,
				 sizeof (*message)) != ERROR_NONE)
		  {
		    printf(" -- echo: error in request\n");
		  }

		break;
	      default:
		printf(" -- echo: error, bad message id\n");
		break;
	    }
	}
    }

  return (0);
}
Example #15
0
int mouse_getcode(int *button, int *dx, int *dy)
{
  union mou_msg msg;
  int r;

  msg.req.h.size=sizeof(msg);
  r=message_receive(mou_quewait,MOU_SRV_MOUSE, MOU_CMD_GETCODE, &msg);
  if(r==ERRNO_OVER)
    return 0;
  if(r<0) {
    display_puts("getcode getresp=");
    int2dec(-r,s);
    display_puts(s);
    display_puts("\n");
    return r;
  }

  mouse_decode_code(&msg, button, dx, dy);
  return 1;
}
Example #16
0
int main(void) {
	// read data (this is outside time measurements, since the data comes from anywhere and is assumed in (virtual) memory)
	Mapipbtest__QueryResult query_result;
	create_result_from_csv(&query_result, DATA_FILE, DATA_COLS, DATA_ROWS,
			DATA_TYPES, 1);

	struct snappy_env se;
	snappy_init_env(&se);

	// react on queries
	void *context = zmq_ctx_new();
	void *socket = zmq_socket(context, ZMQ_REP);
	int rc;
	rc = zmq_bind(socket, SERVER_SOCKET);
	if (rc != 0) {
		fprintf(stderr, "Failed to bind to socket %s\n", SERVER_SOCKET);
		perror("Socket error ");
		return -1;
	}

	long s_time, c_time, req_time;
	struct timeval start, req_start;

	while (1) {
		gettimeofday(&req_start, NULL );
		// receive request
		message query_msg;
		message_receive(socket, &query_msg);
		size_t query_msg_size = message_size(&query_msg);
		void * query_msg_data = message_data(&query_msg);
		if (COMPRESS) {
			query_msg_data = message_uncompress(query_msg_data,
					&query_msg_size);
		}
		Mapipbtest__ExecuteQuery * request = mapipbtest__execute_query__unpack(
				NULL, query_msg_size, query_msg_data);
		message_close(&query_msg);
		if (COMPRESS) {
			free(query_msg_data);
		}
		//printf("%s\n", request->sqlquery);
		//mapipbtest__execute_query__free_unpacked(request, NULL );

		// send response
		gettimeofday(&start, NULL );
		size_t query_response_msg_size =
				mapipbtest__query_result__get_packed_size(&query_result);
		void * query_response_msg_data = malloc(query_response_msg_size);
		mapipbtest__query_result__pack(&query_result, query_response_msg_data);

		s_time = end_timer_ms(&start);
		gettimeofday(&start, NULL );
		char * free_ptr;
		if (COMPRESS) {
			free_ptr = query_response_msg_data;
			query_response_msg_data = message_compress(&se,
					query_response_msg_data, &query_response_msg_size);
		}
		c_time = end_timer_ms(&start);

		message_send(socket, query_response_msg_data, query_response_msg_size);
		//free(query_response_msg_data);
		req_time = end_timer_ms(&req_start);

		//free(query_response_msg_data);
		if (COMPRESS) {
			free(free_ptr);
		}

	}
	zmq_close(socket);
	zmq_ctx_destroy(context);
	return 0;
}
Example #17
0
/*
 * This is the main server bit
 *
 * It receives SQL statements and executes them, breaking at EOF
 */
void mainloop()
{

	int sz;
	string *str = NULL;

	int complete = -1;
	int ans;

	SQLSMALLINT ncol;

	SQLHSTMT stmt;
	char format;

	str = new_string();

	while(isloop)
	{
		
		signal(SIGINT, sighand);
		signal(SIGTERM, sighand);

		complete = -1;
		sz = message_receive(mes, str, &complete, MES_CLIENT_TO_SERVER);
		
		if(sz < 0)
		{
			/*
			 * End of file 
			 */
			isloop = 0;
			break;
		}
		else if(sz <= 1) continue;

		format = *(string_s(str));
		ans = SQLAllocHandle(SQL_HANDLE_STMT, (SQLHANDLE) hdbc, (SQLHANDLE *)stmt);

		if((ans != SQL_SUCCESS) && ( ans != SQL_SUCCESS_WITH_INFO))
		{
			message_status(mes, 127, "ODBC: Cannot allocate statement handle\n", MES_SERVER_TO_CLIENT);
			return;
		}

		/* WTF: +1??? */
		ans = SQLPrepare(stmt, (SQLCHAR*)string_s(str) + 1, SQL_NTS);

		if((ans != SQL_SUCCESS) && ( ans != SQL_SUCCESS_WITH_INFO))
		{
			message_status(mes, 127, "ODBC: Cannot execute statement\n", MES_SERVER_TO_CLIENT);
			SQLFreeHandle(SQL_HANDLE_STMT, stmt);
			return;
		}

		ans = SQLNumResultCols(stmt, &(ncol));
		if(ans != SQL_SUCCESS && ans != SQL_SUCCESS_WITH_INFO)
		{
			message_status(mes, 127, "ODBC: - cannot determine SQL type\n", MES_SERVER_TO_CLIENT);
			SQLFreeHandle(SQL_HANDLE_STMT, stmt);
			return;
		}

		if(ncol) dolines(&stmt, ncol, format);
		SQLFreeHandle(SQL_HANDLE_STMT, stmt);

		string_clear(str);
		message_send(mes, str, -1, MES_SERVER_TO_CLIENT);


	}
	string_delete(str);
}
Example #18
0
/*
 * This is the main server bit
 *
 * It receives SQL statements and executes them, breaking at EOF
 */
void mainloop()
{

	int sz;
	char *errmes;

	string *str = NULL;

	int complete = -1;

	PGresult *pgr;

	char format;

	str = new_string();

	while(isloop)
	{
		
		signal(SIGINT, sighand);
		signal(SIGTERM, sighand);

		complete = -1;
		sz = message_receive(mes, str, &complete, MES_CLIENT_TO_SERVER);
		
		if(sz < 0)
		{
			/*
			 * End of file 
			 */
			isloop = 0;
			break;
		}
		else if(sz <= 1) continue;

		format = *(string_s(str));
		pgr = PQexec(sqldb, string_s(str) + 1);
		if(pgr == NULL)
		{
			message_status(mes, 127, "Postges error - cannot allocate result\n", MES_SERVER_TO_CLIENT);
			string_clear(str);
		}
		else
		{
			errmes = PQresultErrorMessage(pgr);
			if(*errmes)
			{
				char ws[128];
				snprintf(ws, 127, "postgres error: %s\n", errmes);
				message_status(mes, 127, ws, MES_SERVER_TO_CLIENT);
				string_clear(str);
			}
			else
			{

				if(PQresultStatus(pgr) == PGRES_TUPLES_OK)
					dolines(pgr, format);
				string_clear(str);
				message_send(mes, str, -1, MES_SERVER_TO_CLIENT);
			}
			PQclear(pgr);
		}
	}
	string_delete(str);
}
Example #19
0
static void lift_process(void) {
    lift_type Lift;
    Lift = lift_create();
    int change_direction, next_floor, tmp_id, tmp_to_floor;
    struct long_time_msg done_m;
    done_m.type = LIFT_TRAVEL_DONE;
    char msgbuf[4096];
    int found = 0;

    int from_floor_list[MAX_N_PERSONS][MAX_TRIP_LEN]; // Contains the from_floors for trips
    int to_floor_list[MAX_N_PERSONS][MAX_TRIP_LEN];   // Contains the to_floors for trips
    int iterations[MAX_N_PERSONS];                    // Which iteration is the persons on
    int trip_len[MAX_N_PERSONS];                      // Trip length for the persons
    struct timeval starttime[MAX_N_PERSONS][MAX_TRIP_LEN];    // Keeps track of timing of each persons trips
    long long int timediff[MAX_N_PERSONS][MAX_TRIP_LEN];
    struct timeval tmp_time;

    while(1) {
        int i;
        int j;
        int id_array[MAX_N_PERSONS * N_FLOORS];
        //struct lift_msg reply;
        struct lift_msg *m;
        struct long_lift_msg *long_m;
        int count, tmp_id;
        message_send((char *) Lift, sizeof(*Lift), QUEUE_UI, 0); // Draw the lift

        int len = message_receive(msgbuf, 4096, QUEUE_LIFT); // Wait for a message
        if(len < sizeof(struct lift_msg)) {
            fprintf(stderr, "Message too short\n");
            continue;
        }

        if (len == sizeof(struct lift_msg)) {
            m = (struct lift_msg *) msgbuf;
            // We now that this is a LIFT_MOVE msg
            /* Check if someone wants to leave at this floor */
            for (i = 0; i < MAX_N_PASSENGERS; i++) {
                if (Lift->passengers_in_lift[i].id != NO_ID &&
                    Lift->passengers_in_lift[i].to_floor == Lift->floor) {
                    tmp_id = Lift->passengers_in_lift[i].id;
                    leave_lift(Lift,
                               tmp_id,
                               Lift->passengers_in_lift[i].to_floor);

                    // Calculate elapsed time
                    gettimeofday(&tmp_time, NULL);
                    timediff[tmp_id][iterations[tmp_id]] =
                        (tmp_time.tv_sec*1000000ULL + tmp_time.tv_usec) -
                        (starttime[tmp_id][iterations[tmp_id]].tv_sec*1000000ULL +
                         starttime[tmp_id][iterations[tmp_id]].tv_usec);

                    //                    printf("Person %d finished an iteration in %lld \n", tmp_id, timediff[tmp_id][iterations[tmp_id]]);

                    //printf("Person %d leave lift.\n", tmp_id);
                    if (iterations[tmp_id] < trip_len[tmp_id] - 1) {
                        iterations[tmp_id]++;
                        // Start timing for that person
                        gettimeofday(&starttime[tmp_id][iterations[tmp_id]], NULL);
                        enter_floor(Lift,
                                    tmp_id,
                                    from_floor_list[tmp_id][iterations[tmp_id]],
                                    to_floor_list[tmp_id][iterations[tmp_id]]);
                        //  printf("Person %d enter floor %d.\n", tmp_id,
                        //from_floor_list[tmp_id][iterations[tmp_id]]);
                    } else {
                        // Send done message with elapsed time info
                        // printf("Sending done message to person %d.\n", tmp_id);
                        //printf("Sent timediff: ");
                        done_m.person_id = tmp_id;

                        // fill message with info, person knows how many iterations he made

                        for (i=0; i < trip_len[tmp_id]; i++) {
                            done_m.timediff[i] = timediff[tmp_id][i];
                            //  printf("%lld, ", done_m.timediff[i]);
                        }
                        //                        printf("\n");
                        message_send((char *) &done_m,
                                     sizeof(done_m),
                                     QUEUE_FIRSTPERSON + tmp_id,
                                     0);
                        //                        printf("Message sent to person %d\n", tmp_id);
                    }
                }
            }

            /* Check if someone at the floor wants to enter the lift */
            for (i = 0; i < MAX_N_PERSONS; i++) {
                tmp_id = Lift->persons_to_enter[Lift->floor][i].id;
                tmp_to_floor = Lift->persons_to_enter[Lift->floor][i].to_floor;
                if (tmp_id != NO_ID) {
                    if (!enter_lift(Lift,
                                    Lift->persons_to_enter[Lift->floor][i].id,
                                    Lift->floor,
                                    Lift->persons_to_enter[Lift->floor][i].to_floor)) {
                        break;
                    }
                }
            }

            change_direction = !Lift->floor || Lift->floor == N_FLOORS-1;
            next_floor = change_direction ^ Lift->up ? Lift->floor-1 : Lift->floor+1;

            Lift->moving = 0;
            /* check if direction shall be changed */
            if (change_direction) {
                Lift->up = !Lift->up;
            }
            Lift->floor = next_floor;
            Lift->moving = 1;
        } else if (len == sizeof(struct long_lift_msg)) {
            // We know that this is a LIFT_TRAVEL message
            // Update the trip list for the person that sent the message.
            long_m = (struct long_lift_msg *) msgbuf;
            tmp_id = long_m->person_id;
            trip_len[tmp_id] = long_m->trip_len;
            //            printf("Received a long message from %d.\n Floors:", tmp_id);
            for (i=0; i < long_m->trip_len; i++) {
                to_floor_list[tmp_id][i] = long_m->to_floor[i];
                from_floor_list[tmp_id][i] = long_m->from_floor[i];
                //                printf("(%lld, %lld), ", from_floor_list[tmp_id][i], to_floor_list[tmp_id][i]);
            }
            //printf("\n");

            iterations[tmp_id] = 0;
            // Start timing for that person
            gettimeofday(&starttime[tmp_id][iterations[tmp_id]], NULL);

            // Make person enter lift
            enter_floor(Lift, tmp_id, from_floor_list[tmp_id][0], to_floor_list[tmp_id][0]);


        }
    }

    return;
}
Example #20
0
static void person_process(int id) {
    init_random();
    char buf[4096];
    struct long_time_msg * reply;
    struct lift_msg m;
    struct long_lift_msg long_m;
    m.person_id = id;
    long_m.person_id = id;
    int len;
    int i, j;
    FILE * fptr;
    char result_name[25];

    struct timeval starttime;
    struct timeval endtime;
    long long int timediff[MAX_ITERATIONS];
    //printf("Created person with id %d\n", m.person_id);
    for(i=0; i < MAX_ITERATIONS; i+= MAX_TRIP_LEN) {
        // Generate new trip list
        long_m.type = LIFT_TRAVEL;
        long_m.trip_len = MAX_ITERATIONS - i < MAX_TRIP_LEN ? MAX_ITERATIONS - i : MAX_TRIP_LEN;
        //        printf("%d, %d, %d \n", MAX_ITERATIONS, i, MAX_TRIP_LEN);
        //        printf("Generating trip list for person %d of length %d\n", id, long_m.trip_len);
        for (j=0; j < long_m.trip_len; j++) {
            long_m.from_floor[j] = get_random_value(id, N_FLOORS - 1);
            do {
                long_m.to_floor[j] = get_random_value(id, N_FLOORS - 1);
            } while(long_m.from_floor[j] == long_m.to_floor[j]);
            //  printf("(%lld, %lld), ", long_m.from_floor[j], long_m.to_floor[j]);
        }
        // Send trip list to lift proc
        //        printf("\nPerson %d sent a trip list of length: %d\n", id, long_m.trip_len);
        message_send((char *) &long_m, sizeof(long_m), QUEUE_LIFT, 0);

        //printf("Person %d wants to go to floor %d\n", m.person_id,  m.to_floor);
        //gettimeofday(&starttime, NULL);
        do {
            len = message_receive(buf, 4096, QUEUE_FIRSTPERSON + id); // Wait for a message
            if(len < sizeof(struct long_time_msg)) {
                fprintf(stderr, "Message too short\n");
                continue;
            }
            //printf("Person %d, recieved a message \n", id);
            reply = ((struct long_time_msg*) buf);
        } while(reply->type != LIFT_TRAVEL_DONE);

        //        printf("Person %d received a reply from lift\nTimediff %d: (", id, id);
        // save timediff's to own array
        for (j=0; j < long_m.trip_len; j++) {
            timediff[i + j] = reply->timediff[j];
            //            printf("%lld, ", timediff[i+j]);
        }
        //        printf("\n");
        //printf("Person %d finished an iteration in %lld \n", id, timediff[i]);
    }

    //printf("Person %d asking file guard for permission.", id);
    /* Ask file guard for permission to write and wait for my turn */
    m.type = FILE_ASK;
    message_send((char *) &m, sizeof(m), QUEUE_FILE, 0);

    do {
        len = message_receive(buf, 4096, QUEUE_FIRSTPERSON + id); // Wait for a reply from guard
        if(len < sizeof(struct lift_msg)) {
            fprintf(stderr, "Message too short\n");
            continue;
        }
        //printf("Person %d, recieved a message\n", id);
        reply = ((struct lift_msg*) buf);
    } while(reply->type != FILE_WRITE);

    //printf("Person %d is writing to file\n", id);
    sprintf(result_name, "opt_results_m_%d.csv", MAX_N_PERSONS);
    fptr = fopen(result_name, "a");


    for (i=0; i<MAX_ITERATIONS; i++) {
        //printf("I'll write my results now, ID = %d\n", id);
        if (i== MAX_ITERATIONS - 1) {
            fprintf(fptr, "%lld\n", timediff[i]);
        } else {

            fprintf(fptr, "%lld, ", timediff[i]);
        }
    }
    //printf("Person %d is done writing to file\n", id);
    fclose(fptr);

    m.type = FILE_DONE;
    message_send((char *) &m, sizeof(m), QUEUE_FILE, 0);


    //printf("Finished!\n");
    exit(0);
}
Example #21
0
int main(int argc, char *argv[])
{
	int errn;
	string *str;
	int complete = -1;
	int i;

	if(argc < 2)
	{
		fprintf(stderr, "Usage: %s connecstring\n", argv[0]);
		exit(1);
	}

	if((mes = new_message(0)) == NULL)
	{
		fprintf(stderr, "%s: Cannot open message queue\n", argv[0]);
		exit(1);
	}


	/*
	 * I believe a fork duplicates malloced stuff, I am in the poo if it does not :-)
	 */
	errn = fork();

	if(errn == -1)
	{
		fprintf(stderr, "%s: Cannot fork child process\n", argv[0]);
		exit(1);
	}
	else if(errn)
	{
/*
 * This is the parent - which behaves like clien
 */

		/*
		 * Initially just a status message is snt back, zero string length 
		 *
		 * Still needs a string to put it into
		 */


		str = new_string();
		
		if(message_receive(mes, str, &complete, MES_SERVER_TO_CLIENT) < 0)
		{
			fprintf(stderr, "%s: %s\n", argv[0], string_s(str));
			message_destroy(mes);
			message_delete(mes);
			string_delete(str);
			exit(1);
		}
		else
		{
			printf("%d\n",message_id(mes)) ;
			message_delete(mes);
			string_delete(str);
			exit(0);
		}
	}
/*
 * All parents have exited now
 */

/*
 * This is all a child
 */

	/*
	 * I think I need to do this here...
	 * I do not fully understand why, it just works!
	 * otherwise shell parent hangs!
	 */

	setsid();
	if(fork()) exit(0);
	close(0);
	close(1);
	close(2);

	/*
	 * We are in daemon mode now
	 */

	/*
	 * open the database
	 */

	str = new_string();

	for(i=1;i<argc;i++)
	{
		string_cat(str, argv[i]);
		if((!strncasecmp(argv[i], "password", 8))
		 || (!strncasecmp(argv[i], "user", 4))
		 || (!strncasecmp(argv[i], "useriname", 8)))
			wipe(argv[i]);
		if(i < argc - 1) string_cat_c(str, ' ');
	}

	sqldb = PQconnectdb(string_s(str));
	string_delete(str);

	if(sqldb == NULL)
	{
		message_status(mes, 127, "Error allocating connection\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		exit(1);
	}
	if (PQstatus(sqldb) != CONNECTION_OK)
	{
		char ws[64];
		snprintf(ws, 63, "Error opening postgres %s/%s\n", PQhost(sqldb), PQdb(sqldb));
		ws[63] = 0;
		message_status(mes, 127, ws, MES_SERVER_TO_CLIENT);
		PQfinish(sqldb);
		message_delete(mes);
		exit(1);
	}

	/*
	 * Transmit to parent that we are hunky dory
	 */

	message_status(mes, 0, "", MES_SERVER_TO_CLIENT);

	/*
	 * We are open for business - Lets go
 	 */

	mainloop();

	/*
	 * At the end, tidy up
	 */

	PQfinish(sqldb);
	message_destroy(mes);
	message_delete(mes);
	exit(0);
}
Example #22
0
static void lift_process(void) {
    lift_type Lift;
	Lift = lift_create();
	int change_direction, next_floor, tmp_id;
	struct lift_msg done_m;
    done_m.type = LIFT_TRAVEL_DONE;
	char msgbuf[4096];

	while(1) {
		int i;
		struct lift_msg reply;
		struct lift_msg *m;
		message_send((char *) Lift, sizeof(*Lift), QUEUE_UI, 0); // Draw the lift
		int len = message_receive(msgbuf, 4096, QUEUE_LIFT); // Wait for a message
		if(len < sizeof(struct lift_msg)) {
			fprintf(stderr, "Message too short\n");
			continue;
		}
		
		m = (struct lift_msg *) msgbuf;
		switch(m->type){
		case LIFT_MOVE:
			// TODO: 
			//    Check if passengers want to leave elevator
            //        Remove the passenger from the elevator
            //        Send a LIFT_TRAVEL_DONE for each passenger that leaves
            //        the elevator
			//    Check if passengers want to enter elevator
            //        Remove the passenger from the floor and into the elevator
			//    Move the Lift‰
            for (i = 0; i < MAX_N_PASSENGERS; i++) {
                if (Lift->passengers_in_lift[i].id != NO_ID &&
                    Lift->passengers_in_lift[i].to_floor == Lift->floor) {
                    tmp_id = Lift->passengers_in_lift[i].id;
                    leave_lift(Lift,
                               tmp_id,
                               Lift->passengers_in_lift[i].to_floor);

                    message_send((char *) &done_m,
                                 sizeof(done_m),
                                 QUEUE_FIRSTPERSON + tmp_id,
                                 0);
                }
            }

            for (i = 0; i < MAX_N_PERSONS; i++) {
                if (Lift->persons_to_enter[Lift->floor][i].id != NO_ID) {
                    if (!enter_lift(Lift,
                                    Lift->persons_to_enter[Lift->floor][i].id,
                                    Lift->floor,
                                    Lift->persons_to_enter[Lift->floor][i].to_floor)) {
                        break;
                    }
                }
            }

            change_direction = !Lift->floor || Lift->floor == N_FLOORS-1;
            next_floor = change_direction ^ Lift->up ? Lift->floor-1 : Lift->floor+1;
            
            Lift->moving = 0;
            /* check if direction shall be changed */
            if (change_direction) {
                    Lift->up = !Lift->up;
                }            
            Lift->floor = next_floor;
            Lift->moving = 1;
			break;
		case LIFT_TRAVEL:
            // TODO:
            // Update the Lift structure so that the person with the given ID  is now present on the floor
            enter_floor(Lift, m->person_id, m->from_floor, m->to_floor);
			break;
		}
	}
	return;
}
Example #23
0
/*******************************************************************************
Name         : STDVMi_EventTask()

Description  : STDVM Event task notifies STDVM internal events

Parameters   : void     *NULL_p     NOT USED

Return Value :
*******************************************************************************/
static void STDVMi_EventTask(void *NULL_p)
{
    ST_ErrorCode_t      ErrCode;
    STDVMi_Event_t     *Event_p;


    while(STDVMi_EventTaskState == TASK_RUNNING)
    {
        Event_p = message_receive(STDVMi_EventTaskMQ_p);

        if(STDVMi_EventTaskState != TASK_RUNNING)
        {
            message_release(STDVMi_EventTaskMQ_p, Event_p);
            break;
        }

        switch(Event_p->Event)
        {
            case STDVM_EVT_END_OF_FILE:
                ErrCode = STEVT_Notify(STDVMi_EVTHandle, STDVMi_EVTIDs[STDVM_EVT_END_OF_FILE_ID], &Event_p->U.EventData);
                if(ErrCode != ST_NO_ERROR)
                    STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "STEVT_Notify : %08X\n", ErrCode));
                break;

            case STDVM_EVT_END_OF_PLAYBACK:
                ErrCode = STEVT_Notify(STDVMi_EVTHandle, STDVMi_EVTIDs[STDVM_EVT_END_OF_PLAYBACK_ID], &Event_p->U.EventData);
                if(ErrCode != ST_NO_ERROR)
                    STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "STEVT_Notify : %08X\n", ErrCode));
                break;

            case STDVM_EVT_WRITE_CLOSE_TO_READ:
                ErrCode = STEVT_Notify(STDVMi_EVTHandle, STDVMi_EVTIDs[STDVM_EVT_WRITE_CLOSE_TO_READ_ID], &Event_p->U.EventData);
                if(ErrCode != ST_NO_ERROR)
                    STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "STEVT_Notify : %08X\n", ErrCode));
                break;

            case STDVM_EVT_WRITE_TO_READ_MARGIN_OK:
                ErrCode = STEVT_Notify(STDVMi_EVTHandle, STDVMi_EVTIDs[STDVM_EVT_WRITE_TO_READ_MARGIN_OK_ID],&Event_p->U.EventData);
                if(ErrCode != ST_NO_ERROR)
                    STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "STEVT_Notify : %08X\n", ErrCode));
                break;

            case STDVM_EVT_DISK_SPACE_LOW:
                ErrCode = STEVT_Notify(STDVMi_EVTHandle, STDVMi_EVTIDs[STDVM_EVT_DISK_SPACE_LOW_ID], &Event_p->U.EventData);
                if(ErrCode != ST_NO_ERROR)
                    STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "STEVT_Notify : %08X\n", ErrCode));
                break;

            case STDVM_EVT_DISK_FULL:
                ErrCode = STEVT_Notify(STDVMi_EVTHandle, STDVMi_EVTIDs[STDVM_EVT_DISK_FULL_ID], &Event_p->U.EventData);
                if(ErrCode != ST_NO_ERROR)
                    STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "STEVT_Notify : %08X\n", ErrCode));
                break;

            case STDVM_EVT_ERROR:
                ErrCode = STEVT_Notify(STDVMi_EVTHandle, STDVMi_EVTIDs[STDVM_EVT_ERROR_ID], &Event_p->U.EventError);
                if(ErrCode != ST_NO_ERROR)
                    STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "STEVT_Notify : %08X\n", ErrCode));
                break;

            default:
                STTBX_Report((STTBX_REPORT_LEVEL_ERROR, "Unknown event from STDVM %08X\n", Event_p->Event));
                break;
        }

        message_release(STDVMi_EventTaskMQ_p, Event_p);
    }
}
Example #24
0
static void lmtpd_daemonize(bool do_fork, uint16_t port, bool local_only)
{
    pid_t pid = 0;

    if (do_fork)
        pid = fork();
    if (pid < 0)
        die("could not fork daemon process");
    else if (pid > 0)
        exit(EXIT_SUCCESS); /* parent process exits */

    /*
     * perform some general daemon house keeping
     */
    struct sigaction sa;
    sa.sa_handler = lmtpd_wait;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1)
        die("unable to handle child processes");
    if ((signal(SIGTERM, lmtpd_stop) == SIG_ERR) || (signal(SIGINT, lmtpd_stop) == SIG_ERR))
        die("could not set custom signal handler");
    signal(SIGCHLD, SIG_IGN);
    setsid();

    char p[8]; /* just big enough for a pid */
    snprintf(p, sizeof p, "%d\n", getpid());
    write(fd_pidfile, p, strlen(p));

    uint16_t original_socket = socket_create(port);
    if (listen(original_socket, 1) < 0)
        die("could not listen on socket");

    log_message(LOG_DEFAULT, "server up and running");
    while(true)
    {
        struct sockaddr_in client;
        char caddr[INET_ADDRSTRLEN];
        uint32_t z = sizeof client;
        int32_t n = accept(original_socket, (struct sockaddr *)&client, &z);
        if (n < 0)
            die("could not accept on socket");

        inet_ntop(AF_INET, &client.sin_addr, caddr, INET_ADDRSTRLEN);
        if (local_only) /* only allow localhost, else allow everybody */
        {
            if (strcmp(LOCALHOST, caddr))
            {
                close(n);
                continue;
            }
        }
        log_message(LOG_DEFAULT, "connection from %s:%hu", caddr, ntohs(client.sin_port));

        if (do_fork)
            pid = fork();
        if (pid < 0)
            die("could not fork daemon process");
        else if (pid > 0)
            close(n);
        else /* spawn child prcess for connection */
        {
            if (do_fork)
                close(original_socket);
            message_receive(n);
            log_message(LOG_DEFAULT, "closed connection with %s:%hu", caddr, ntohs(client.sin_port));
            close(n);
            if (do_fork)
                _exit(EXIT_SUCCESS);
        }
    }
}
Example #25
0
static void lift_process(void)
{
        lift_type Lift;
	Lift = lift_create();
	int change_direction, next_floor;
	int temp_id;
	int temp_to_floor;
	int to_floors_all[MAX_N_PERSONS][NUMBER_MESSAGES];
	int from_floors_all[MAX_N_PERSONS][NUMBER_MESSAGES];
	int person_message_iterator[MAX_N_PERSONS];
	char msgbuf[4096];
	while(1){
		int i;
		struct lift_msg reply;
		struct lift_msg *m;
		//message_send((char *) Lift, sizeof(*Lift), QUEUE_UI,0); // Draw the lift
		int len = message_receive(msgbuf, 4096, QUEUE_LIFT); // Wait for a message
		if(len < sizeof(struct lift_msg)){
			fprintf(stderr, "Message too short\n");
			continue;
		}
		
		m = (struct lift_msg *) msgbuf;
		switch(m->type){
		case LIFT_MOVE:
		  
		  for (i = 0; i < MAX_N_PASSENGERS; i ++){
		    if (Lift->passengers_in_lift[i].id != NO_ID){
		      if(Lift->passengers_in_lift[i].to_floor == Lift->floor){
			temp_id = Lift->passengers_in_lift[i].id;
			Lift->passengers_in_lift[i].id = NO_ID;
			Lift->passengers_in_lift[i].to_floor = NO_FLOOR;
			
			if(person_message_iterator[temp_id] < NUMBER_MESSAGES){
			  enter_floor(Lift,temp_id,from_floors_all[temp_id][person_message_iterator[temp_id]],to_floors_all[temp_id][person_message_iterator[temp_id]]);
			  //message_send((char *) Lift, sizeof(*Lift), QUEUE_UI,0); // Draw the lift
			  person_message_iterator[temp_id]++;
			}else{
			  
			  reply.type = LIFT_TRAVEL_DONE;
			  
			  //message_send((char *) Lift, sizeof(*Lift), QUEUE_UI,0); // Draw the lift
			message_send(&reply, sizeof(reply), QUEUE_FIRSTPERSON + temp_id, 0);
			}
		      }
		    }
		  }

		  /* Check if passengers want to enter the lift */
		  for (i = 0; i < MAX_N_PERSONS; i ++){
		      temp_id = Lift->persons_to_enter[Lift->floor][i].id;
		      temp_to_floor = Lift->persons_to_enter[Lift->floor][i].to_floor;
		      if ((temp_id != NO_ID) && n_passengers_in_lift(Lift) < MAX_N_PASSENGERS){
			leave_floor(Lift, temp_id, Lift->floor); 
			enter_lift(Lift, temp_id, temp_to_floor);
			//message_send((char *) Lift, sizeof(*Lift), QUEUE_UI,0); // Draw the lift
		      }
		    }
		  
		  lift_next_floor(Lift, &next_floor, &change_direction);
		  lift_move(Lift, next_floor, change_direction);
		  break;
		case LIFT_TRAVEL:
                  
		  for(i = 0; i < NUMBER_MESSAGES; i++){
		    to_floors_all[m->person_id][i] = m->to_floor[i];
		    from_floors_all[m->person_id][i] = m->from_floor[i];
		  }
		  person_message_iterator[m->person_id] = 1;
		  enter_floor(Lift, m->person_id, m->from_floor[0], m->to_floor[0]);
		  //message_send((char *) Lift, sizeof(*Lift), QUEUE_UI,0); // Draw the lift
		  
		  break;
		}
	}
	return;
}
Example #26
0
/*
 * Bucket-sort algorithm.
 */
extern void bucketsort(int *array, int n)
{
	int max;                  /* Maximum number.      */
	int i, j;                 /* Loop indexes.        */
	int range;                /* Bucket range.        */
	struct minibucket *minib; /* Working mini-bucket. */
	struct message *msg;      /* Working message.     */
	struct bucket **todo;     /* Todo buckets.        */
	struct bucket **done;     /* Done buckets.        */
	uint64_t start, end;      /* Timers.              */
	
	/* Setup slaves. */
	open_noc_connectors();
	spawn_slaves();
	sync_slaves();
	
	todo = smalloc(NUM_BUCKETS*sizeof(struct bucket *));
	done = smalloc(NUM_BUCKETS*sizeof(struct bucket *));
	for (i = 0; i < NUM_BUCKETS; i++)
	{
		done[i] = bucket_create();
		todo[i] = bucket_create();
	}

	/* Find max number in the array. */
	start = timer_get();
	max = INT_MIN;
	for (i = 0; i < n; i++)
	{
		/* Found. */
		if (array[i] > max)
			max = array[i];
	}

	/* Distribute numbers. */
	range = max/NUM_BUCKETS;
	for (i = 0; i < n; i++)
	{
		j = array[i]/range;
		if (j >= NUM_BUCKETS)
			j = NUM_BUCKETS - 1;
		
		bucket_insert(&todo[j], array[i]);
	}
	end = timer_get();
	master += timer_diff(start, end);

	/* Sort buckets. */
	j = 0;
	for (i = 0; i < NUM_BUCKETS; i++)
	{	
		while (bucket_size(todo[i]) > 0)
		{
			minib = bucket_pop(todo[i]);
			
			/* Send message. */
			msg = message_create(SORTWORK, i, minib->size);
			message_send(outfd[j], msg);
			message_destroy(msg);
			
			/* Send data. */
			communication += 
				data_send(outfd[j], minib->elements, minib->size*sizeof(int));
			minibucket_destroy(minib);
			
			j++;
			
			/* 
			 * Slave processes are busy.
			 * So let's wait for results.
			 */
			if (j == nclusters)
			{	
				/* Receive results. */
				for (/* NOOP */ ; j > 0; j--)
				{					
					/* Receive message. */
					msg = message_receive(infd[nclusters - j]);
					
					/* Receive mini-bucket. */
					minib = minibucket_create();
					minib->size = msg->u.sortresult.size;
					communication += data_receive(infd[nclusters -j], minib->elements, 
													minib->size*sizeof(int));
					
					bucket_push(done[msg->u.sortresult.id], minib);
					
					message_destroy(msg);
				}
			}
		}
	}

	/* Receive results. */
	for (/* NOOP */ ; j > 0; j--)
	{						
		/* Receive message. */
		msg = message_receive(infd[j - 1]);
					
		/* Receive bucket. */
		minib = minibucket_create();
		minib->size = msg->u.sortresult.size;
		communication += 
			data_receive(infd[j - 1], minib->elements, minib->size*sizeof(int));
					
		bucket_push(done[msg->u.sortresult.id], minib);
					
		message_destroy(msg);
	}

	start = timer_get();
	rebuild_array(done, array);
	end = timer_get();
	master += timer_diff(start, end);
	
	/* House keeping. */
	for (i = 0; i < NUM_BUCKETS; i++)
	{
		bucket_destroy(todo[i]);
		bucket_destroy(done[i]);
	}
	free(done);
	free(todo);
	join_slaves();
	close_noc_connectors();
}
Example #27
0
static void person_process(int id)
{
	init_random();
	
	long long int travel_time_array[ITERATIONS];
	
	struct timeval starttime;
	struct timeval stoptime;
	long long int timediff;
		
	int start_floor;
	int destination_floor;
	 
	char buf[4096];
	struct lift_msg m;
	struct lift_msg* reply;
	int travel_count;
	for(travel_count = 0; travel_count < ITERATIONS; travel_count++){
	  /* Create a LIFT_TRAVEL message and send it */
	  m.type = LIFT_TRAVEL;
	  m.person_id = id;
	  int i;
	  for(i = 0; i < NUMBER_MESSAGES; i++){
	    /* Generate ranom floors */
	    start_floor = get_random_value(id, N_FLOORS-1);
	    destination_floor = start_floor;
	    while(destination_floor == start_floor){
	      destination_floor = get_random_value(id, N_FLOORS-1);
	    }

	    m.from_floor[i] = start_floor;
	    m.to_floor[i] = destination_floor;
	  }

	  gettimeofday(&starttime, NULL);//Start timing
	  message_send((char *)&m, sizeof(struct lift_msg), QUEUE_LIFT, 0);
	  
	  /* Wait for LIFT_TRAVEL_DONE message*/
	  message_receive(buf, 4096, QUEUE_FIRSTPERSON + id);
	  gettimeofday(&stoptime, NULL);//Stop timing
	  
	  timediff = (stoptime.tv_sec*1000000ULL + stoptime.tv_usec) -
	    (starttime.tv_sec*1000000ULL + starttime.tv_usec);
	  travel_time_array[travel_count] = timediff;

	  reply = (struct lift_msg *)buf;

	}
	m.type = PROCESS_DONE;
	message_send((char *)&m, sizeof(struct lift_msg), QUEUE_RESULT,0);
	
	while(1){
	  message_receive(buf, 4096, QUEUE_FIRSTPERSON + id);
	  reply = (struct lift_msg *)buf;
	  if(reply->type == WRITE_TO_FILE){
	    int i;
	    FILE *f = fopen("multi_travels.txt", "a");
	    if (f == NULL)
	      {
		printf("Error opening file!\n");
		exit(1);
	      }
	      for(i = 0; i < ITERATIONS; i++){
		fprintf(f, "%d ", (int)travel_time_array[i]);
	      }
	      fprintf(f, "\n");
	    
	      fclose(f);

	    break;
	  }
	}

	
	m.type = WRITE_DONE;
	message_send((char *)&m, sizeof(struct lift_msg), QUEUE_RESULT,0);
	exit(0);
}
Example #28
0
int main(int argc, char *argv[])
{
	int errn;
	string *str;
	int complete = -1;
	int i;
	long ans;
	long logintimeout = 20;
	char *s;
	char *password;
	char *username;

	if(argc < 4)
	{
		fprintf(stderr, "Usage: %s user password connecstring\n", argv[0]);
		exit(1);
	}

	if((mes = new_message(0)) == NULL)
	{
		fprintf(stderr, "%s: Cannot open message queue\n", argv[0]);
		exit(1);
	}


	/*
	 * I believe a fork duplicates malloced stuff, I am in the poo if it does not :-)
	 */
	errn = fork();

	if(errn == -1)
	{
		fprintf(stderr, "%s: Cannot fork child process\n", argv[0]);
		exit(1);
	}
	else if(errn)
	{
/*
 * This is the parent - which behaves like clien
 */

		/*
		 * Initially just a status message is snt back, zero string length 
		 *
		 * Still needs a string to put it into
		 */


		str = new_string();
		
		if(message_receive(mes, str, &complete, MES_SERVER_TO_CLIENT) < 0)
		{
			fprintf(stderr, "%s: %s\n", argv[0], string_s(str));
			message_destroy(mes);
			message_delete(mes);
			string_delete(str);
			exit(1);
		}
		else
		{
			printf("%d\n",message_id(mes)) ;
			message_delete(mes);
			string_delete(str);
			exit(0);
		}
	}
/*
 * All parents have exited now
 */

/*
 * This is all a child
 */

	/*
	 * I think I need to do this here...
	 * I do not fully understand why, it just works!
	 * otherwise shell parent hangs!
	 */

	setsid();
	if(fork()) exit(0);
	close(0);
	close(1);
	close(2);

	/*
	 * We are in daemon mode now
	 */

	/*
	 * open the database
	 */

	str = new_string();

	for(i=3;i<argc;i++)
	{
		string_cat(str, argv[i]);
		if(i < argc - 1) string_cat_c(str, ' ');
	}

	username = strdup(argv[1]);
	password = strdup(argv[2]);

	wipe(argv[2]);
	wipe(argv[1]);

	ans = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(env));
	if((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		message_status(mes, 127, "ODBC: Cannot allocate environment handle\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		free(username);
		free(password);
		exit(1);
	}

	ans = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); 

	if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		SQLFreeHandle(SQL_HANDLE_ENV, env);
		message_status(mes, 127, "ODBC: Cannot set environment handle attributes\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		exit(1);
	}

	/* 2. allocate connection handle, set timeout */

	ans = SQLAllocHandle(SQL_HANDLE_DBC, env, &(hdbc)); 

	if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		SQLFreeHandle(SQL_HANDLE_ENV, env);
		message_status(mes, 127, "ODBC: Cannot allocate database handle\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		free(username);
		free(password);
		exit(1);
	}

	/*
 	 * TODO - Parameterize ODBC_TIMEOUT as environment variable
	 */

	s = getenv("ODBC_TIMEOUT");
	if(s != NULL)
	{
		if(*s)
		{
			logintimeout = atol(s);
		}
	}

	SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)logintimeout, 0);

	/* 3. Connect to the datasource  */

	ans = SQLConnect(hdbc, (SQLCHAR*) string_s(str), SQL_NTS,
                                     (SQLCHAR*) username, SQL_NTS,
                                     (SQLCHAR*) password, SQL_NTS);

	if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO))
	{
		message_status(mes, 127, "ODBC: Cannot connect to database\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
/*
		SQLGetDiagRec(SQL_HANDLE_DBC, V_OD_hdbc,1, 
		              V_OD_stat, &V_OD_err,V_OD_msg,100,&V_OD_mlen);
		printf("%s (%d)\n",V_OD_msg,V_OD_err);
 */
		SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
		SQLFreeHandle(SQL_HANDLE_ENV, env);
		free(username);
		free(password);
		exit(1);
	}


	/*
	 * Transmit to parent that we are hunky dory
	 */

	message_status(mes, 0, "", MES_SERVER_TO_CLIENT);

	/*
	 * We are open for business - Lets go
 	 */

	mainloop();

	/*
	 * At the end, tidy up
	 */

	SQLDisconnect(hdbc);
	SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
	SQLFreeHandle(SQL_HANDLE_ENV, env);

	message_destroy(mes);
	message_delete(mes);

	free(username);
	free(password);

	exit(0);
}
Example #29
0
static void lift_process(void)
{
  lift_type Lift;
  Lift = lift_create();
  int change_direction, next_floor;	
  char msgbuf[4096];
  struct lift_msg travel_list[MAX_N_PERSONS];

  while(1){
    int i;

    struct lift_msg reply;
    struct lift_msg *m;
    int len = message_receive(msgbuf, 4096, QUEUE_LIFT); // Wait for a message
    if(len < sizeof(struct lift_msg)){
      fprintf(stderr, "Message too short\n");
      continue;
    }
		
    m = (struct lift_msg *) msgbuf;
    
    for(i = 0; i < MAX_N_PASSENGERS; i++){
      if (Lift->passengers_in_lift[i].to_floor == Lift->floor)
	{
	  int id = Lift->passengers_in_lift[i].id;
	  //fprintf(stderr,"ID is: %d\n",id);
	  (travel_list[id].trip)++;
	  //fprintf(stderr,"Trip is: %d\n", travel_list[id].trip);
					//message_send((char *) &reply, sizeof(reply), QUEUE_FIRSTPERSON + Lift->passengers_in_lift[i].id ,0);
					/*for(j = 0; j < MAX_N_PASSENGERS; j++){
						fprintf(stderr, "before removing passengers_in_lift[%d].id = %d\n", j, Lift->passengers_in_lift[j].id);
					}*/
    					Lift->passengers_in_lift[i].id = NO_ID; 
    					Lift->passengers_in_lift[i].to_floor = NO_FLOOR;
					if(travel_list[id].trip == PLANNED_TRIPS){
						message_send((char *) &reply, sizeof(reply), QUEUE_FIRSTPERSON + id ,0);
						//travel_list[id].trip = 0;
						//fprintf(stderr,"inne i skicka meddelande\n");
						/*for(j = 0; j < MAX_N_PASSENGERS; j++){
							fprintf(stderr, "passengers_in_lift[%d].id = %d\n", j, Lift->passengers_in_lift[j].id);
						}*/

					}
					else if(travel_list[id].trip > PLANNED_TRIPS){
						//fprintf(stderr, "IASFHFHKUEFHKSFH\n");
						/*for(j = 0; j < MAX_N_PASSENGERS; j++){
							fprintf(stderr, "passengers_in_lift[%d].id = %d\n", j, Lift->passengers_in_lift[j].id);
						}*/
						exit(1);
					}
					else{
						enter_floor(Lift, id, travel_list[id].from_floor[travel_list[id].trip], travel_list[id].to_floor[travel_list[id].trip]);
						//fprintf(stderr,"next trip here\n");
					}
					
        			}
    			}
			

			//    Check if passengers want to enter elevator
                        //        Remove the passenger from the floor and into the elevator
			for(i = 0; i < MAX_N_PERSONS; i++){
				person_data_type person = Lift->persons_to_enter[Lift->floor][i];
        			if (person.id != NO_ID && (n_passengers_in_lift(Lift) < MAX_N_PASSENGERS))
        			{
					//fprintf(stderr,"Going to enter lift\n");
					leave_floor(Lift, person.id, Lift->floor);
					enter_lift(Lift, person.id, person.to_floor);
        			}
    			}
			//    Move the lift


			lift_next_floor(Lift, &next_floor, &change_direction);
			lift_move(Lift, next_floor, change_direction);

			break;
		case LIFT_TRAVEL:
                        // TODO:
                        //    Update the Lift structure so that the person with the given ID  is now present on the floor
			travel_list[m->person_id]=*m;
			enter_floor(Lift, m->person_id, m->from_floor[0], m->to_floor[0]);

			break;
		default:
			fprintf(stderr, "Error: unkown message type sent!!!!! \n");
		break;
		}
		
	}
Example #30
0
int main(int argc, char *argv[])
{
	int errn;
	string *str;
	int complete = -1;
	int i;

	
	char *sqlname[] = {
		"_dummy",
		"host",
		"user",
		"password",
		"dbname",
		"port",
		"socket",
		"flag"
	};

	sqlarg *sarg;


	/*
	 * Username and password may be in the connection string
	 */

	long flag = 0;
	unsigned int port = 0;

	MYSQL *tdb;

	if(argc < 2)
	{
		fprintf(stderr, "Usage: %s connecstring\n", argv[0]);
		exit(1);
	}

	if((mes = new_message(0)) == NULL)
	{
		fprintf(stderr, "%s: Cannot open message queue\n", argv[0]);
		exit(1);
	}


	/*
	 * I believe a fork duplicates malloced stuff, I am in the poo if it does not :-)
	 */
	errn = fork();

	if(errn == -1)
	{
		fprintf(stderr, "%s: Cannot fork child process\n", argv[0]);
		exit(1);
	}
	else if(errn)
	{
/*
 * This is the parent - which behaves like clien
 */

		/*
		 * Initially just a status message is snt back, zero string length 
		 *
		 * Still needs a string to put it into
		 */


		str = new_string();
		
		if(message_receive(mes, str, &complete, MES_SERVER_TO_CLIENT) < 0)
		{
			fprintf(stderr, "%s: %s\n", argv[0], string_s(str));
			message_destroy(mes);
			message_delete(mes);
			string_delete(str);
			exit(1);
		}
		else
		{
			printf("%d\n",message_id(mes)) ;
			message_delete(mes);
			string_delete(str);
			exit(0);
		}
	}
/*
 * All parents have exited now
 */

/*
 * This is all a child
 */

	/*
	 * I think I need to do this here...
	 * I do not fully understand why, it just works!
	 * otherwise shell parent hangs!
	 */

	setsid();
	if(fork()) exit(0);
	close(0);
	close(1);
	close(2);

	/*
	 * We are in daemon mode now
	 */

	/*
	 * open the database
	 */

	str = new_string();

	for(i=1;i<argc;i++)
	{
		string_cat(str, argv[i]);
		if((!strncasecmp(argv[i], "password", 8))
		 || (!strncasecmp(argv[i], "user", 4))
		 || (!strncasecmp(argv[i], "username", 8)))
			wipe(argv[i]);
		if(i < argc - 1) string_cat_c(str, ' ');
	}

	sarg = new_sqlarg(sqlname, string_s(str), SMYSQL_PARAMETERS);

	string_delete(str);

	if(sarg == NULL)
	{
		message_status(mes, 127, "Error allocating string parameters\n", MES_SERVER_TO_CLIENT);
		message_delete(mes);
		exit(1);
	}

	if(sqlargi(sarg, SMYSQL_PORT) != NULL) port = atoi(sqlargi(sarg, SMYSQL_PORT));
	if(sqlargi(sarg, SMYSQL_FLAG) != NULL) flag = atol(sqlargi(sarg, SMYSQL_FLAG));


	sqldb = mysql_init(NULL);
	if(sqldb == NULL)
	{
		message_status(mes, 127, "Error allocating connection\n", MES_SERVER_TO_CLIENT);
		sqlarg_delete(sarg);
		message_delete(mes);
		exit(1);
	}

	tdb = mysql_real_connect(sqldb, sqlargi(sarg, SMYSQL_HOST), sqlargi(sarg, SMYSQL_USER), sqlargi(sarg, SMYSQL_PASSWORD),
					  sqlargi(sarg, SMYSQL_DBNAME), port, sqlargi(sarg, SMYSQL_SOCKET), flag);

	sqlarg_delete(sarg);

	

	if(tdb == NULL)
	{
		char ws[128];
		snprintf(ws, 127, "Error opening mysql: %s\n", mysql_error(sqldb));
		ws[127] = 0;
		message_status(mes, 127, ws, MES_SERVER_TO_CLIENT);
		mysql_close(sqldb);
		message_delete(mes);
		exit(1);
	}

	/*
	 * Transmit to parent that we are hunky dory
	 */

	message_status(mes, 0, "", MES_SERVER_TO_CLIENT);

	/*
	 * We are open for business - Lets go
 	 */

	mainloop();

	/*
	 * At the end, tidy up
	 */

	mysql_close(sqldb);
	message_destroy(mes);
	message_delete(mes);
	exit(0);
}