Exemplo n.º 1
0
Direction Runner::step() {
    Direction move;
    bool exit = check_exit(move);
    if (exit == false) {
        move = generate_step();
    }
    return move;

}
Exemplo n.º 2
0
inline std::pair<aid_t, bool> recv_impl(
  gce::nonblocked, Recver& recver, message& msg, pattern& patt, recv_meta meta = recv_meta()
  )
{
  bool has_exit = check_exit(patt.match_list_);
  aid_t sender = recver.recv(msg, patt.match_list_, patt.recver_);
  if (meta.matched_ != 0)
  {
    *meta.matched_ = msg.get_type();
  }
  if (!has_exit && msg.get_type() == exit)
  {
    if (meta.guard_ != 0)
    {
      *meta.guard_ = boost::asio::error::make_error_code(boost::asio::error::shut_down);
      return std::make_pair(sender, false);
    }
    else
    {
      exit_code_t exc;
      std::string errmsg;
      msg >> exc >> errmsg;
      if (exc == exit_normal)
      {
        GCE_VERIFY(false)(exc)(msg)(patt)(sender)
          .msg("gce::normal_exception").except<normal_exception>();
      }
      else if (exc == exit_except)
      {
        GCE_VERIFY(false)(exc)(msg)(patt)(sender)
          .msg("gce::runtime_exception").except<runtime_exception>();
      }
      else if (exc == exit_remote)
      {
        GCE_VERIFY(false)(exc)(msg)(patt)(sender)
          .msg("gce::remote_exception").except<remote_exception>();
      }
      else if (exc == exit_already)
      {
        GCE_VERIFY(false)(exc)(msg)(patt)(sender)
          .msg("gce::already_exit_exception").except<already_exit_exception>();
      }
      else if (exc == exit_neterr)
      {
        GCE_VERIFY(false)(exc)(msg)(patt)(sender)
          .msg("gce::neterr_exception").except<neterr_exception>();
      }
      else
      {
        GCE_ASSERT(false)(exc)(errmsg);
      }
    }
  }
  return std::make_pair(sender, sender != aid_nil);
}
Exemplo n.º 3
0
int 
main(int argc, char **argv)
{
    int     i;

    if (argc != 3) {
	fprintf(stderr, "Must be called in form 'extract <filename> <dbref>'\n");
	exit(1);
    }
    if ((input_file = fopen(argv[1], "r")) == NULL) {
	fprintf(stderr, "Could not open file '%d'\n", argv[1]);
	exit(1);
    }
    me = atoi(argv[2]);

    db_free();
    db_read(input_file);

    fprintf(stderr, "dbtop = %d\n", db_top);

    printf("MUCK 2.2fb extract for dbref #%d\n", me);

    for (i = 0; i < db_top; i++) {
	if (OWNER(i) != me)
	    continue;

	if (!(i % 256))
            fprintf(stderr, "Checking object %d..\n", i);
	check_common(i);
	switch (db[i].flags & TYPE_MASK) {
	    case TYPE_ROOM:
		check_room(i);
		break;
	    case TYPE_THING:
		check_thing(i);
		break;
	    case TYPE_EXIT:
		check_exit(i);
		break;
	    case TYPE_PLAYER:
		check_player(i);
		break;
	    case TYPE_PROGRAM:
		check_program(i);
		break;
	    case TYPE_GARBAGE:
		break;
	    default:
		break;
	}
    }
    fclose(input_file);
    fprintf(stderr, "Completed extract normally.\n");
    return 0;
}
Exemplo n.º 4
0
inline aid_t recv(Recver& recver, message& msg, match& mach)
{
  bool add_exit = check_exit(mach.match_list_);
  if (add_exit)
  {
    mach.match_list_.push_back(exit);
  }

  aid_t sender = recver.recv(msg, mach);
  if (add_exit && msg.get_type() == exit)
  {
    exit_code_t exc;
    std::string errmsg;
    msg >> exc >> errmsg;
    throw std::runtime_error(errmsg);
  }
Exemplo n.º 5
0
void	 minishell2(char **env)
{
  char *bufpath[2];
  char **tab;
  char **cmd;

  while (42)
    {
      bufpath[0] = prompt();
      check_exit(bufpath[0]);
      bufpath[1] = get_path(env);
      tab = my_str_to_wordtab(bufpath[1]);
      cmd = my_str_to_wordtab2(bufpath[0]);
      process(bufpath, tab, cmd, env);
    }
}
Exemplo n.º 6
0
void SkpTcpSocketTest::skp_on_read()
{
    if(check_exit())
        return;

    qint64 size = 0;
    qint64 left = BUFFER_SIZE - m_readSkip;

    if(left > 0) {
        size = read(m_readBuffer + m_readSkip, left);
        if(size <= 0) {
            return;
        }

        m_readSkip += size;

        if(m_readSkip < BUFFER_SIZE) {
            return;
        }

        if(m_readSkip == BUFFER_SIZE) {
            m_readSkip = 0;
        }
    } else {
        qDebug() << "read left = error" << left;
        QApplication::exit();
    }


    if(IS_CHECK_DATA) {
        if(memcmp(m_writeBuffer, m_readBuffer, BUFFER_SIZE) != 0) {
            qDebug() << "m_writeBuffer = " << m_writeBuffer;
            qDebug() << "m_readBuffer = " << m_readBuffer;
            qDebug() << "m_writeBuffer != m_readBuffer";
            QApplication::exit();
        }
    }

    if(IS_CHECK_DATA)
        m_readSize += BUFFER_SIZE;
    else
        m_readSize += size;

    skp_write();
}
Exemplo n.º 7
0
void *proc_echo(void *cache){
	int cnt;
	Parket buf={0};
	int fd=((Cache *)cache)->fd;
	while(1){
		cnt = read(fd,&buf,sizeof(Parket));
		if(cnt == 0){
			printf("client closed!\n");
			break;
		}else if(cnt == -1){
			if(errno==EINTR){
				continue;
			}else{
				break;
		}
		}else{
			switch(buf.data_type){
				case TYPE_REG:
						check_reg(cache,&buf);	
					break;
				case TYPE_LOGIN:
						check_log(cache,&buf);
					break;
				case TYPE_HEART:
						server_heart(cache);
					break;
				case TYPE_CMD:
					execmd(&buf,cache);
				case TYPE_EXIT:
					check_exit(&buf,cache);
					break;
				default :
					break;	
					
			}
		}
	}
	close(fd);
	return NULL;
}
Exemplo n.º 8
0
Arquivo: start.c Projeto: vanner-a/IA
void      start(int argc, char **argv, t_option option)
{
  t_map		map;
  t_stack	*stack;
  char    *p;

  p = argv[argc - 1];
  if (check_map(p) && check_exit(p) && check_player(p)) {
    init_map(&map, argv, argc, option);
    if (map.width != 0) {
      stack = s_solve(&map, NULL, NULL);
      if (stack_empty(stack) && option.c == 1) {
        map.option.c = 0;
        stack = s_solve(&map, NULL, NULL);
      }
      result(map, stack, option);
      destruct(map);
      stack_clean(stack);
    }
  }
  else
    my_putstr("La carte n'est pas valide\n");
}
Exemplo n.º 9
0
/*---------------------------------------------------------------------------*
 *                              run tests                                    *
 *---------------------------------------------------------------------------*/
int
main()
{
    /* hex_int() tests */
    check_int("hex_int(-1)", hex_int(-1), -1);
    check_int("hex_int(0)", hex_int(0), 0);
    check_int("hex_int(1)", hex_int(1), 0xfa);
    check_int("hex_int(2)", hex_int(2), 0x7fffffff);
    check_int("hex_int(3)", hex_int(3), 0x4000);
    check_int("hex_int(4)", hex_int(4), 0xfa - 0xf0);
    check_int("hex_int(5)", hex_int(5), 0x0f0f);
    check_int("hex_int(6)", hex_int(6), -1);

    /* hex_uint() tests */
    check_uint("hex_uint(0)", hex_uint(0), 0xa3u);
    check_uint("hex_uint(1)", hex_uint(1), 0x1ffu);
    check_uint("hex_uint(2)", hex_uint(2), 0x80000000u + 1);
    check_uint("hex_uint(3)", hex_uint(3), 0x80001230u);
    check_uint("hex_uint(4)", hex_uint(4), 0xfafu);
    check_uint("hex_uint(5)", hex_uint(5), 0x0);

    check_exit();
}
Exemplo n.º 10
0
// cmdline 파싱
// exit 체크
// cd 명령 수행
// execute_cmdgrp() 호출
void execute_cmdline(char* cmdline)
{
	int i = 0;
	int count = 0;
	int cd_ok = 0;

	count = makelist(cmdline, ";", cmdgrps, MAX_CMD_GRP);

	for(i = 0; i < count; ++i)
	{
		// exit 명령
		check_exit(cmdgrps[i]);

		// cd 명령
		cd_ok = check_cd(cmdgrps[i]);
		if(cd_ok)
		{
			continue;
		}

		switch(fork())
		{
		case -1:
			fatal("fork error");
			break;

		case 0: // child process
			execute_cmdgrp(cmdgrps[i]);
			exit(0);

		default: // parent process
			wait(NULL);
			fflush(stdout);
		}
	}
}
Exemplo n.º 11
0
collision_data get_collision_with_primitive(movable_object *who, primitive_object *with_what){
    #define WHO_PLAYER ((movable_player*)who->object_data)
    #define WHO_PARTICLE ((movable_particle*)who->object_data)
    #define WITH_POINT ((point*)with_what->object_data)
    #define WITH_SEGMENT ((segment*)(with_what->object_data))
    #define WITH_CIRCLE ((circle*)with_what->object_data)
    #define WITH_EXIT ((fixed_exit*)(((prim_exit*)with_what->object_data)->fixed_data))
    collision_data new_coll;
    long double dr;
    new_coll.time = EMPTY_COLLISION_TIME;
    new_coll.with_movable = false;
    switch(who->type){
        case motPLAYER:
            if(WHO_PLAYER->shield + WHO_PLAYER->shield_push > WHO_PLAYER->r0){
                dr = WHO_PLAYER->shield_push;
            }else{
                dr = 0;
            }
            switch(with_what->type){
                case potPOINT:
                    new_coll.time = check_collision_between_two_balls(WITH_POINT->x - WHO_PLAYER->center.x,
                                                                      WITH_POINT->y - WHO_PLAYER->center.y,
                                                                      who->dx, who->dy, WHO_PLAYER->r, dr);
                    new_coll.time = double_min(new_coll.time, check_collision_between_two_balls(WITH_POINT->x - WHO_PLAYER->center.x,
                                                                      WITH_POINT->y - WHO_PLAYER->center.y,
                                                                      who->dx, who->dy, WHO_PLAYER->r0, 0));
                    break;
                case potSEGMENT:
                    new_coll.time = check_collision_between_ball_and_segment(WHO_PLAYER->center.x, WHO_PLAYER->center.y,
                                                                             who->dx, who->dy, WHO_PLAYER->r, dr, WITH_SEGMENT);
                    new_coll.time = double_min(new_coll.time, check_collision_between_ball_and_segment(WHO_PLAYER->center.x, WHO_PLAYER->center.y,
                                                                             who->dx, who->dy, WHO_PLAYER->r0, 0, WITH_SEGMENT));
                    break;
                case potCIRCLE:
                    new_coll.time = check_collision_between_two_balls(WITH_CIRCLE->center.x - WHO_PLAYER->center.x,
                                                                      WITH_CIRCLE->center.y - WHO_PLAYER->center.y,
                                                                      who->dx, who->dy, WHO_PLAYER->r + WITH_CIRCLE->r, dr);
                    new_coll.time = double_min(new_coll.time, check_collision_between_two_balls(WITH_CIRCLE->center.x - WHO_PLAYER->center.x,
                                                                      WITH_CIRCLE->center.y - WHO_PLAYER->center.y,
                                                                      who->dx, who->dy, WHO_PLAYER->r0 + WITH_CIRCLE->r, 0));
                    break;
                case potEXIT:
                    if(!((prim_exit*)with_what->object_data)->done){
                        new_coll.time = check_exit(WITH_EXIT->center.x - WHO_PLAYER->center.x,
                                                   WITH_EXIT->center.y - WHO_PLAYER->center.y,
                                                   WITH_EXIT);
                    }
                    break;
            }
            break;
        case motPARTICLE:
            switch(with_what->type){
                case potPOINT:
                    new_coll.time = check_collision_between_two_balls(WITH_POINT->x - WHO_PARTICLE->center.x,
                                                                      WITH_POINT->y - WHO_PARTICLE->center.y,
                                                                      who->dx, who->dy, WHO_PARTICLE->r, 0);
                    break;
                case potSEGMENT:
                    new_coll.time = check_collision_between_ball_and_segment(WHO_PARTICLE->center.x, WHO_PARTICLE->center.y,
                                                                             who->dx, who->dy, WHO_PARTICLE->r, 0, WITH_SEGMENT);
                    break;
                case potCIRCLE:
                    new_coll.time = check_collision_between_two_balls(WITH_CIRCLE->center.x - WHO_PARTICLE->center.x,
                                                                      WITH_CIRCLE->center.y - WHO_PARTICLE->center.y,
                                                                      who->dx, who->dy, WHO_PARTICLE->r + WITH_CIRCLE->r, 0);
                    break;
                default:
                    ;
            }
            break;
        default:
            break;
    }
    #undef WHO_PLAYER
    #undef WHO_PARTICLE
    #undef WITH_POINT
    #undef WITH_SEGMENT
    #undef WITH_CIRCLE
    #undef WITH_EXIT
    return new_coll;
}
Exemplo n.º 12
0
int main(int argc, char *argv[]) {
	
	//Checks that only ./whoosh is entered to invoke shell
	if(argc != 1) {
		error_msg();
		exit(1);
	}
	
	int CHAR_LIMIT = 129;
	int BUFFER_LIMIT = 1024;
	char buffer[BUFFER_LIMIT];
	
	int path_num = 1;
	char* s_path[BUFFER_LIMIT];
	s_path[0] = "/bin";
	
	while(1) {
		printf("whoosh> ");
		fflush(stdout);		
		fgets(buffer, sizeof(buffer), stdin);
		
		get_line(buffer);
		
		int line_size = strlen(buffer);
		
		if(line_size > CHAR_LIMIT) {
			error_msg();
			continue;
		}
		
		//Get num of args in command 
		int num_args = count_args(buffer);
		
		if(num_args != 0) {
			
			char* myargv[num_args + 1];
			int r_count = 0;
			int last_r = 0;
			char* r_path = NULL;
			int i;
			char buf[PATH_MAX + 1];
			char *cwd;
			char *r_output;
			
			//Put each argument in myargv array
			get_args(buffer, myargv, num_args);
			
			//Check for redirect
			check_redirect(myargv, num_args, &r_count, &last_r);
		
			//Redirect error handling
			if(r_count > 1) {
				error_msg();
				continue;
			}
			else if (r_count == 1) {
				if(last_r != num_args - 2) {
					error_msg();
					continue;
				}
				if(myargv[num_args - 1][0] == '/') {
					if(chdir(myargv[num_args - 1]) == 0) {
						r_path = strdup(myargv[num_args - 1]);
					}
					else {
						error_msg();
						continue;
					}
				}
				
				r_output = malloc(strlen(myargv[num_args - 1]) + strlen(".out"));
				sprintf(r_output, "%s", myargv[num_args - 1]);	
				//Take off > and path from arguments
				num_args = num_args - 2;
			}
			
			//Set last element in myargv array to NULL
			myargv[num_args] = NULL;
	
			//Check if exit was entered
			check_exit(myargv);
			
			//Check if any built-in commands were called
			if(check_built_in(myargv, num_args, s_path, &path_num) == 0) {
				continue;
			}
			else{
				int file_exist = 0;
				
				cwd = getcwd(buf, PATH_MAX + 1);
				for(i=0; i<path_num; i++) {
					chdir(s_path[i]);
					struct stat path_buff;
					if(stat(myargv[0], &path_buff) == 0) {
						file_exist = 1;
						char *exec_path = malloc(strlen(s_path[i]) + strlen("/") + strlen(myargv[0]) + 1);
						sprintf(exec_path, "%s/%s", s_path[i], myargv[i]);
						myargv[0] = exec_path;
						chdir(cwd);
						break;
					}
				}	
				if(file_exist == 0) {
					error_msg();
					continue;
				}
				else {
					exec_cmd(myargv, r_output, r_path, r_count);
				}
			}
		}	
	}
}
Exemplo n.º 13
0
/*---------------------------------------------------------------------------*
 *                              run tests                                    *
 *---------------------------------------------------------------------------*/
int
main()
{
    /* signed_div_vars() tests */
    check_int("signed_div_vars(20, 5)",
              call_signed_div_vars(20, 5), 20/5);
    check_int("signed_div_vars(-60, 19)",
              call_signed_div_vars(-60, 19), -60 / 19);
    check_int("signed_div_vars(16, -3)",
              call_signed_div_vars(16, -3), 16/-3);
    check_int("signed_div_vars(-1000, -100)",
              call_signed_div_vars(-1000, -100), -1000 / -100);
    check_int("signed_div_vars(0, -1)",
              call_signed_div_vars(0, -1), 0 /-1);

    /* unsigned_div_vars() tests */
    check_uint("unsigned_div_vars(200, 10)",
               call_unsigned_div_vars(200, 10), 200 / 10);
    check_uint("unsigned_div_vars(13, 20)",
               call_unsigned_div_vars(13, 20), 13 / 20);
    check_uint("unsigned_div_vars(1000, 88)",
               call_unsigned_div_vars(1000, 88), 1000 / 88);

    /* signed_div_lconst() tests */
    check_int("signed_div_lconst(3)", call_signed_div_lconst(3), 60/3);
    check_int("signed_div_lconst(7)", call_signed_div_lconst(7), 60/7);
    check_int("signed_div_lconst(-5)", call_signed_div_lconst(-5), 60/-5);

    /* unsigned_div_rconst() tests */
    check_uint("unsigned_div_rconst(297)",
               call_unsigned_div_rconst(297), 297/100);
    check_uint("unsigned_div_rconst(423)",
               call_unsigned_div_rconst(423), 423/100);
    check_uint("unsigned_div_rconst(3141500)",
               call_unsigned_div_rconst(3141500), 3141500/100);

    /* const_mod() test */
    check_int("const_mod()", call_const_mod(), 49 % 10);

    /* signed_mod_vars() tests */
    check_int("signed_mod_vars(20, 5)",
              call_signed_mod_vars(20, 5), 20 % 5);
    check_int("signed_mod_vars(-60, 19)",
              call_signed_mod_vars(-60, 19), -60 % 19);
    check_int("signed_mod_vars(16, -3)",
              call_signed_mod_vars(16, -3), 16 % -3);
    check_int("signed_mod_vars(-1034, -100)",
              call_signed_mod_vars(-1034, -100), -1034 % -100);

    /* unsigned_div_vars() tests */
    check_uint("unsigned_mod_vars(203, 10)",
               call_unsigned_mod_vars(203, 10), 203 % 10);
    check_uint("unsigned_mod_vars(13, 20)",
               call_unsigned_mod_vars(13, 20), 13 % 20);
    check_uint("unsigned_mod_vars(615, 5)",
               call_unsigned_mod_vars(615, 5), 615 % 5);

    /* signed_mod_lconst() tests */
    check_int("signed_mod_lconst(3)", call_signed_mod_lconst(3), 60 % 3);
    check_int("signed_mod_lconst(7)", call_signed_mod_lconst(7), 60 % 7);

    /* unsigned_div_rconst() tests */
    check_uint("unsigned_mod_rconst(297)",
               call_unsigned_mod_rconst(297), 297 % 100);
    check_uint("unsigned_mod_rconst(500)",
               call_unsigned_mod_rconst(500), 500 % 100);

    /* signed_mult_unary() tests */
    check_int("signed_mult_unary(20, 4)", signed_mult_unary(20, 4), 20 * -4);
    check_int("signed_mult_unary(4, -2)", signed_mult_unary(4, -2), 4*-(-2));
    check_int("signed_mult_unary(-1, 0)", signed_mult_unary(-1, 0), -1 * -0);

    check_exit();
}
Exemplo n.º 14
0
/*---------------------------------------------------------------------------*
 *                              run tests                                    *
 *---------------------------------------------------------------------------*/
int
main()
{
    int res;

    /* foreach_slice() test */
    check_int("foreach_slice()", call_foreach_slice(), (1 + 2 + 3) + 2);

    /* foreach_slice_params() tests */
    check_int("foreach_slice_params(1, 2)",
              call_foreach_slice_params(1, 2),
              11 + 0);

    check_int("foreach_slice_params(0, 6)",
              call_foreach_slice_params(0, 6),
              (10 + 11 + 12 + 13 + 14 + 15) +
              (0 + 1 + 2 + 3 + 4 + 5));

    check_int("foreach_slice_params(3, 5)",
              call_foreach_slice_params(3, 5),
              (13 + 14) + (0 + 1));

    /* foreach_shorthand_slice() tests */
    check_int("foreach_shorthand_slice(0, -1)",
              call_foreach_shorthand_slice(0, -1),
              -1 * 4 * 6 * 8 * 10 * 12 * 14 * 16);

    check_int("foreach_shorthand_slice(4, 3)",
              call_foreach_shorthand_slice(4, 3),
              2 * 4 * 6 * 8 * 3 * 12 * 14 * 16);

    /* foreach_value_auto_type() tests */
    check_bool("foreach_value_auto_type(13)",
               call_foreach_value_auto_type(13), true);

    check_bool("foreach_value_auto_type(14)",
               call_foreach_value_auto_type(14), true);

    check_bool("foreach_value_auto_type(15)",
               call_foreach_value_auto_type(15), false);

    check_bool("foreach_value_auto_type(16)",
               call_foreach_value_auto_type(16), false);

    /* 
     * foreach_index_auto_type() and
     * run_foreach_index_auto_type() tests
     */
    check_int("run_foreach_index_auto_type(97)",
              call_run_foreach_index_auto_type(97),
              0);

    check_int("run_foreach_index_auto_type(211)",
              call_run_foreach_index_auto_type(211),
              2);

    check_int("run_foreach_index_auto_type(36)",
              call_run_foreach_index_auto_type(36),
              5);

    check_int("run_foreach_index_auto_type(-15)",
              call_run_foreach_index_auto_type(-15),
              -1);

    check_int("run_foreach_index_auto_type(4)",
              call_run_foreach_index_auto_type(4),
              -1);

    /* foreach_body_loc_vars() tests */
    check_int("foreach_body_loc_vars([0 0 0 0])",
              call_foreach_body_loc_vars(0),
              19341 + 19341 + 19341 + 19341);

    check_int("foreach_body_loc_vars([2 4 5 3])",
              call_foreach_body_loc_vars(1),
              48352 + 49081 + 23112 + 28360);

    check_int("foreach_body_loc_vars([15 14 13 12])",
              call_foreach_body_loc_vars(2),
              41092 + 56732 + 38528 + 37889);

    check_int("foreach_body_loc_vars([0 1 18 3])",
              call_foreach_body_loc_vars(3),
              -1);

    check_int("call_foreach_body_loc_vars(4)",
              call_foreach_body_loc_vars(4),
              -2);

    /* foreach_bool_arry() tests */
    check_int("foreach_bool_arry([false, false, false, false, false, false])",
              call_foreach_bool_arry(0), 0);

    check_int("foreach_bool_arry([true, true, true, true, true, true])",
              call_foreach_bool_arry(1),
              11 + 12 + 13 + 14 + 15 + 16);

    check_int("foreach_bool_arry([false, false, true, false, false, true])",
              call_foreach_bool_arry(2),
              13 + 16);

    check_int("foreach_bool_arry([true, false, false, true, false, true])",
              call_foreach_bool_arry(3),
              11 + 14 + 16);

    check_int("foreach_bool_arry([true, false, true, false, false, false])",
              call_foreach_bool_arry(4),
              11 + 13);

    check_int("call_foreach_bool_arry(5)", call_foreach_bool_arry(5), -1);

    /* foreach_break() tests */
    check_uint("foreach_break(0)", foreach_break(0), 4);
    check_uint("foreach_break(8)", foreach_break(8), 3);
    check_uint("foreach_break(1)", foreach_break(1), 2);
    check_uint("foreach_break(7)", foreach_break(7), 1);
    check_uint("foreach_break(2)", foreach_break(2), 0);
    check_uint("foreach_break(-1)", foreach_break(-1), 4);

    check_exit();
}
Exemplo n.º 15
0
///------------------------------------------------------------------------------
/// recv stackless
///------------------------------------------------------------------------------
inline bool begin_recv(pattern& patt)
{
  return check_exit(patt.match_list_);
}
Exemplo n.º 16
0
int main(int argc, char **argv) {
    tty_t tty = { BADFILE, tty_t_undefined };
    tty_t tty_tcp_uplink = { BADFILE, tty_t_tcp };
    char *tty_name = NULL;
    char *tcp_uplink = NULL;
    int baud = RCX_DEFAULT_BAUD;
    int timeout = RCX_DEFAULT_TIMEOUT;
    int opt;
#ifdef HAVE_GETOPT_LONG
    int option_index;
#endif
    
    fd_set rfds;
//    struct sigaction sigact;
    struct sockaddr addr;
    struct sockaddr_in* addr_in = (struct sockaddr_in*) &addr;
    struct timeval tv;
    long port = BRICK_BROADCAST_PORT;
    int slot_len = 0;
    int val = 1;
    int len = 0;
    char buff[RCX_BUFFERSIZE];
    char buff_echo[RCX_BUFFERSIZE];
    int len_echo = 0;
    int i, j;

    char *usage_string =
    "usage: %s [options]\n\n"
    RCX_COMM_OPTIONS
    "  -p<port>     , --port=<port number>  server broadcast port (default: 50637)\n"
    "  -c<tcp>      , --tcp=<server>:<port> uplink to another TCP IR server\n"
	"\n"
    "Note: There is no functional difference between TCP uplink and TCP downlink\n"
	"\n"
    RCX_COMM_OPTIONS_INFO
	"\n"
	;

    // Process command-line arguments
    while((opt=getopt_long(argc, argv, "p:t:b:o:c:hv",
                        (struct option *)long_options, &option_index) )!=-1) {
        switch(opt) {
          case 'b':
            baud = atoi(optarg);
            break;
          case 'c':
            tcp_uplink = optarg;
            break;
          case 'h':
            fprintf(stderr, usage_string, argv[0]);
            return 1;
            break;
          case 'o':
            timeout = atoi(optarg);
            break;
          case 'p':
            port = atol(optarg);
            break;
          case 't':
            tty_name = optarg;
            break;
          case 'v':
            rcx_set_debug(1);
            break;
        }
    }

    // Set the slot length based on the baud
    if (2400 == baud) {
        slot_len = 11;
    } else {
        slot_len = 10;
    }
    
    // initialize the tty downlink (if specified)
    if (tty_name != NULL) {
        rcx_init(&tty, tty_name, baud, timeout, TRUE);
        if (BADFILE == tty.fd) {
            perror("tty downlink");
            return 1;
        }
    }
    
    // initialize the socket array
    memset(sockets, -1, sizeof(sockets));
    
    // initialize the tcp uplink (if specified) to socket "1"
    if (tcp_uplink != NULL) {
        rcx_init_tcp(&tty_tcp_uplink, tcp_uplink, baud);
        if (BADFILE == tty_tcp_uplink.fd) {
            perror("tcp uplink");
            return 1;
        } else {
            sockets[1] = (int)tty_tcp_uplink.fd;
        }
    }

    // initialize the server
    sockets[0] = socket(PF_INET, SOCK_STREAM, 0);
    setsockopt(sockets[0], SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
    memset(&addr, 0, sizeof(addr));
    addr_in->sin_family = AF_INET;
    addr_in->sin_port = htons(port);
    addr_in->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    if (bind(sockets[0], &addr, sizeof(addr)) < 0) {
      perror("bind");
      return 1;
    }
    listen(sockets[0], 10);
    printf("Server started.\n");
//    if (fork())
//      return 0;

//    sigact.sa_handler = SIG_IGN;
//    sigemptyset(&sigact.sa_mask);
//    sigact.sa_flags = SA_RESTART;
//    sigaction(SIGPIPE, &sigact, NULL);
    // close stdin/out/err
//    close(0);
//    close(1);
//    close(2);
    
    while (1) {
        int max = 0;
        FD_ZERO(&rfds);
        for (i = 0; i < MAX_CLIENTS; i++) {
            if (sockets[i] >= 0) {
                if (sockets[i] >= max)
                    max = sockets[i] + 1;
                FD_SET(sockets[i], &rfds);
            }
        }
        tv.tv_sec = timeout / 1000;
        tv.tv_usec = (timeout % 1000) * 1000;
        select(max, &rfds, NULL, NULL, &tv);
        if (FD_ISSET(sockets[0], &rfds)) {
            socklen_t addr_len = sizeof(addr);
            int client;
            memset(&addr, 0, sizeof(addr));
            client = accept(sockets[0], &addr, &addr_len);
//            if (client == -1)
//                continue;
            if (client != -1) {
                // assign the connection an index in the socket array--indexes 0 and 1 are reserved
                for (i = 2; i < MAX_CLIENTS; i++) {
                    if (sockets[i] == -1) {
                        sockets[i] = client;		    
                        break;
                    }
                }
                if (i == MAX_CLIENTS) {
                    // too many open connections 
                    close(client);
                }
            }
        }
        
        // Process sockets
        // Socket index 0 is reserved for the server--do not read from or write to it
        // Socket index 1 is reserved for the tcp uplink--do not echo to it
        for (i = 1; i < MAX_CLIENTS; i++) {
            if (sockets[i] >= 0 && FD_ISSET(sockets[i], &rfds)) {
                len = read(sockets[i], buff, sizeof(buff));
                if (len <= 0) {
                    close(sockets[i]);
                    sockets[i] = -1;
                    check_exit(&tty);
                } else {
        #if 0
                    usleep(1000000 * slot_len / baud * len);
        #endif
        #if 0
                    {
                        struct timeval current_time;
                        gettimeofday(&current_time, NULL);
                        if (next_time.tv_sec > current_time.tv_sec
                            || (next_time.tv_sec == current_time.tv_sec &&
                                next_time.tv_usec > current_time.tv_usec)) {
                            usleep((next_time.tv_sec - current_time.tv_sec)
                                   * 1000000
                                   + next_time.tv_usec - current_time.tv_usec);
                        }
                        gettimeofday(&current_time, NULL);
                        next_time = current_time;
                        next_time.tv_usec += 1000000 * slot_len * len / baud;
                        if (next_time.tv_usec > 1000000) {
                            next_time.tv_sec++;
                            next_time.tv_usec -= 1000000;
                        }
                    }
        #endif
                    // write to tty downlink
                    if (tty.fd != BADFILE) {
                        rcx_nbwrite(&tty, buff, len, timeout);
                        //lnp_logical_write(buff, len);
                    }
                    // write to other sockets
                    for (j = 1; j < MAX_CLIENTS; j++) {
                        if (i != j && sockets[j] >= 0) {
                            if (write(sockets[j], buff, len) < 0) {
                                close(sockets[j]);
                                sockets[j] = -1;
                                check_exit(&tty);
                            }
                        }
                    }
                    // handle the echo on the uplink socket
                    if (sockets[1] >= 0) {
                        len_echo = rcx_nbread(&tty_tcp_uplink, buff_echo, len, timeout);
                    }
                    
                    // echo back to self if not the uplink socket
                    if ((i != 1) && (write(sockets[i], buff, len) < 0)) {
                        close(sockets[i]);
                        sockets[i] = -1;
                        check_exit(&tty);
                    }
                }
            }
        } // end socket loop
        
        // Process tty downlink
        // NOTE: do NOT echo to the tty downlink
        if (tty.fd != BADFILE) {
            len = rcx_nbread(&tty, buff, sizeof(buff), timeout);
            if (len > 0) {
                // write to sockets
                for (j = 1; j < MAX_CLIENTS; j++) {
                    if (sockets[j] >= 0) {
                        if (write(sockets[j], buff, len) < 0) {
                            close(sockets[j]);
                            sockets[j] = -1;
                            check_exit(&tty);
                        }
                    }
                }
                // handle the echo on the uplink socket
                if (sockets[1] >= 0) {
                    len_echo = rcx_nbread(&tty_tcp_uplink, buff_echo, len, timeout);
                }
            }
        }
    }
}
Exemplo n.º 17
0
////
// main
//
//   The main function to the shell program.
//
int main (int argc, char **argv) {
   (void) argc;
   
   // variables
   set_execname (argv[0]);
   
   // loop until user exits
   while (TRUE) {   // repeat until user exits the shell
      char cmdline[1025]; // will only accept 1024
      bzero (cmdline, 1025);
      char parsebuffer[2024];
      bzero (parsebuffer, 2024);
      char *tokens[512];
      int toknum = 0;
//      bool pipein = FALSE;
//      bool pipeout = FALSE;
      
      print_prompt();    // print the prompt
      // get up to 1024 chars from the user
      if (get_cmdline (cmdline) == FALSE) continue;
      // break the line into tokens
      if (parseline (cmdline, parsebuffer, tokens, &toknum)) {
         // parseline returned an error
         eprintf ("%s: %s\n", "Error",
                  "parsing error caused by incorrect usage");
         continue;
      }

      // Check if the user wishes to exit the shell
      if (check_exit (tokens, toknum)) exit (get_exitstatus());
      

      // set the number of commands to be executed
      int numcmds = set_numofcmds (tokens, toknum);
      // the number of commands should not exceed 20
      if (numcmds > 20) {
         eprintf ("%s: %s\n", "ERROR", "cannot handle more than 20 commands");
         continue;
      }

      // initialize the current start index of the tokens
      int curstart;
      int nextstart = 0;
      
      int fd[2];
//      int fdin[2];
//      int fdout[2];
      // loop fork-exec for each command
      int i;
      for (i = 0; i < numcmds && nextstart < toknum; ++i) {
         // setup current command, update current start, and determine pipe
         curstart = nextstart;
         char *command = set_command (tokens, toknum, &nextstart);
         // a null command will cause an error
         if (command == NULL || command[0] == '\0') {
            eprintf ("%s: %s\n", "FATAL ERROR", "encountered a null command");
            break;
         }
         // make a new argv
         int newargc = get_newargc (tokens, curstart, nextstart);
         char *newargv[newargc + 1];
         newargv[0] = command;
         newargv[newargc] = NULL;
         int j = 1;
         int k;
         for (k = curstart; k < nextstart && j < newargc; ++k) {
            if (tokens[k][0] == '1') {
               newargv[j] = &tokens[k][1];
               ++j;
            }
         }

/*         // set pipe
         pipeout = checktopipe (tokens, curstart, nextstart);
         if (pipein) {
            fdin[0] = fdout[0];
            fdin[1] = fdout[1];
         }
         if (pipeout) {
            pipe (fdout);
         }
*/       
         // set redirection
         char *input_redirect = get_redirectarg (tokens, curstart, nextstart, '<');
         char *output_redirect = get_redirectarg (tokens, curstart, nextstart, '>');
         if (input_redirect != NULL) {
            // open file and set file descriptor
            fd[0] = open (input_redirect, O_RDONLY, 0755);
         }
         if (output_redirect != NULL) {
            // open file and set file descriptor
            fd[1] = open (output_redirect, O_CREAT | O_WRONLY | O_TRUNC, 0644);
         }


         // fork child process
         int status = 0;
         int pid = fork();
         if (pid != 0) {
            /* this is the PARENT PROCESS */
/*            // write to pipe from parent to child
            if (pipein) {
               close (fdin[0]);
               if (dup2 (fdin[1], STDOUT_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and write to pipe from parent to child");
               close (fdin[1]);
               pipein = FALSE;
               
            }
*/
            // wait for any child process to finish
            int waitstatus = waitpid (-1, &status, 0);

/*            // read pipe from child to parent
            if (pipeout) {
               close (fdout[1]);
               if (dup2 (fdout[0], STDIN_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and read pipe from child to parent");
               pipein = TRUE;
            }
*/          // close the file descriptors caused by redirection
            // close stdin
            if (input_redirect != NULL) close (fd[0]);
            // close stdout
            if (output_redirect != NULL) close (fd[1]);
            // determine errors
            if (waitstatus == 0) {
               eprintf ("%s: %s\n", "ERROR", "error waiting on child process");
               break;
            }else if (waitstatus == -1) {
               eprintf ("%s: %s\n", "ERROR", "error executing child process");
               break;
            }
            if (status != 0) {
               eprintf ("%s: %s: %s %d\n", "ERROR", command, "exit status of", status);
               break;
            }
         }else {
            /* this is the CHILD PROCESS */
            // set up pipe in from a previous command
/*            if (pipein) {
               close (fdin[1]);
               if (dup2 (fdin[0], STDIN_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and write to pipe from child to parent");
               close (fdin[0]);
            }
            // set up pipe out to the next command
            if (pipeout) {
               close (fdout[0]);
               if (dup2 (fdout[1], STDOUT_FILENO) == -1)
                  eprintf ("%s: %s\n", "ERROR",
                           "could not open and write to pipe from child to parent");
            }
*/            
            // set up redirection
            if (input_redirect != NULL) {
               // open file and set file descriptor
               // set file to stdin
               if (dup2 (fd[0], STDIN_FILENO) == -1)
                  eprintf ("%s: %s \"%s\" %s\n", "ERROR", "could not open",
                           input_redirect, "for input redirection");
            }
            if (output_redirect != NULL) {
               // open file and set file descriptor
               // set stdout to file
               if (dup2 (fd[1], STDOUT_FILENO) == -1)
                  eprintf ("%s: %s \"%s\" %s\n", "ERROR", "could not open",
                           output_redirect, "for output redirection");
            }

            // execute the command
            set_exitstatus (execvp (command, newargv));
            // if there was an error executing the command
            eprintf ("%s: %s: %s\n", "ERROR", command, "could not execute");
            return (get_exitstatus());
         }
         
      }

   }
   return get_exitstatus();
}
Exemplo n.º 18
0
/*---------------------------------------------------------------------------*
 *                              run tests                                    *
 *---------------------------------------------------------------------------*/
int
main()
{
    unsigned idx;

    /* int_array_lit_assigment() tests */
    check_int("int_array_lit_assigment(0)",
              call_int_array_lit_assigment(0), 3 + 3);
    check_int("int_array_lit_assigment(1)",
              call_int_array_lit_assigment(1), 3 + 1);
    check_int("int_array_lit_assigment(2)",
              call_int_array_lit_assigment(2), 3 + 4);

    /* int_array_lit_init() tests */
    check_int("int_array_lit_init(0)",
              call_int_array_lit_init(0), 2);
    check_int("int_array_lit_init(1)",
              call_int_array_lit_init(1), 7);
    check_int("int_array_lit_init(2)",
              call_int_array_lit_init(2), 1);
    check_int("int_array_lit_init(3)",
              call_int_array_lit_init(3), 8);
    check_int("int_array_lit_init(3)",
              call_int_array_lit_init(4), 2);

    /* intops() tests */
    check_int("intops(0, 20)", call_intops(0, 20), 20 + 2 + 3);
    check_int("intops(1, 0)", call_intops(1, 0), 1 + 0 + 3);
    check_int("intops(2, -20)", call_intops(2, -20), 1 + 2 + (-20));

    /* bool_array_lit_assigment() tests */
    check_bool("bool_array_lit_assigment(0)",
               call_bool_array_lit_assigment(0), true);
    check_bool("bool_array_lit_assigment(1)",
               call_bool_array_lit_assigment(1), false);
    check_bool("bool_array_lit_assigment(2)",
               call_bool_array_lit_assigment(2), true);
    check_bool("bool_array_lit_assigment(3)",
               call_bool_array_lit_assigment(3), false);

    /* bool_array_lit_init() tests */
    check_bool("bool_array_lit_init(true)",
               call_bool_array_lit_init(true), true);
    check_bool("bool_array_lit_init(false)",
               call_bool_array_lit_init(false), false);

    /* boolops() tests */
    check_bool("boolops(0, -1)", call_boolops(0, -1), false);
    check_bool("boolops(1, 10)", call_boolops(1, 10), true);
    check_bool("boolops(2, 0)", call_boolops(2, 0), false);

    /* char_array() tests */
    check_char("char_array('X', 0)", call_char_array('X', 0), 'X');
    check_char("char_array('X', 1)", call_char_array('X', 1), 'b');
    check_char("char_array('X', 2)", call_char_array('X', 2), 'c');
    check_char("char_array('X', 3)", call_char_array('X', 3), 'd');
    check_char("char_array('X', 4)", call_char_array('X', 4), 'e');
    check_char("char_array('X', 5)", call_char_array('X', 5), 'X');

    /* dyn_array_sum() tests */
    check_int("invoke_dyn_array_sum_handle(0)",
              call_invoke_dyn_array_sum_handle(0), 1 + 10 + 15 + 0 + 5);

    check_int("invoke_dyn_array_sum_handle(1)",
              call_invoke_dyn_array_sum_handle(1), 5 -12);

    check_int("invoke_dyn_array_sum_handle(2)",
              call_invoke_dyn_array_sum_handle(2), 0);

    check_int("invoke_dyn_array_sum_handle(3)",
              call_invoke_dyn_array_sum_handle(3), -1);

    check_int("invoke_dyn_array_sum_lit(0)",
              call_invoke_dyn_array_sum_lit(0), 3 + 1 + 4 + 1 + 5);

    check_int("invoke_dyn_array_sum_lit(1)",
              call_invoke_dyn_array_sum_lit(1), 50 + 23);

    check_int("invoke_dyn_array_sum_lit(2)",
              call_invoke_dyn_array_sum_lit(2), 0);

    check_int("invoke_dyn_array_sum_lit(3)",
              call_invoke_dyn_array_sum_lit(3), -1);

    /* dyn_array_slice_assigment() tests */
    for (idx = 0; idx < 5; idx += 1)
    {
      check_int("dyn_array_slice_assigment(false, idx)",
                  call_dyn_array_slice_assigment(false, idx), (int)(idx + 1));
    }
    check_int("dyn_array_slice_assigment(true, 0)",
              call_dyn_array_slice_assigment(true, 0), 1);
    check_int("dyn_array_slice_assigment(true, 1)",
              call_dyn_array_slice_assigment(true, 1), 2);
    check_int("dyn_array_slice_assigment(true, 2)",
              call_dyn_array_slice_assigment(true, 2), 11);
    check_int("dyn_array_slice_assigment(true, 3)",
              call_dyn_array_slice_assigment(true, 3), 22);
    check_int("dyn_array_slice_assigment(true, 4)",
              call_dyn_array_slice_assigment(true, 4), 5);

    /* dyn_array_slice_assigment_length() tests */
    check_uint("dyn_array_slice_assigment_length(0)",
               call_dyn_array_slice_assigment_length(0), 0);
    check_uint("dyn_array_slice_assigment_length(1)",
               call_dyn_array_slice_assigment_length(1), 0);
    check_uint("dyn_array_slice_assigment_length(2)",
               call_dyn_array_slice_assigment_length(2), 0);
    check_uint("dyn_array_slice_assigment_length(3)",
               call_dyn_array_slice_assigment_length(3), 99);
    check_uint("dyn_array_slice_assigment_length(4)",
               call_dyn_array_slice_assigment_length(4), 98);
    check_uint("dyn_array_slice_assigment_length(5)",
               call_dyn_array_slice_assigment_length(5), 97);

    /* dyn_array_slice_shorthand() tests */
    for (idx = 0; idx < 5; idx += 1)
    {
      check_int("dyn_array_slice_shorthand(false, idx)",
                call_dyn_array_slice_shorthand(false, idx), -1);
    }
    check_int("dyn_array_slice_shorthand(true, 0)",
              call_dyn_array_slice_shorthand(true, 0), 11);
    check_int("dyn_array_slice_shorthand(true, 1)",
              call_dyn_array_slice_shorthand(true, 1), 22);
    check_int("dyn_array_slice_shorthand(true, 2)",
              call_dyn_array_slice_shorthand(true, 2), 33);
    check_int("dyn_array_slice_shorthand(true, 3)",
              call_dyn_array_slice_shorthand(true, 3), 44);
    check_int("dyn_array_slice_shorthand(true, 4)",
              call_dyn_array_slice_shorthand(true, 4), 55);

    /* find_int() tests */
    check_bool("invoke_find_int(0)",
               call_invoke_find_int(0), true);
    check_bool("invoke_find_int(1)",
               call_invoke_find_int(1), false);
    check_bool("invoke_find_int(2)",
               call_invoke_find_int(2), false);
    check_bool("invoke_find_int(3)",
               call_invoke_find_int(3), false);
    check_bool("invoke_find_int(4)",
               call_invoke_find_int(4), true);

    /* array_null_assign() tests */
    check_uint("array_null_assign(true)", array_null_assign(true), 0);
    check_uint("array_null_assign(false)", array_null_assign(false), 4);

    /* array_null_arg() tests */
    check_int("array_null_arg(true)", array_null_arg(true), 0);
    check_int("array_null_arg(false)", array_null_arg(false), 10 + 2 + 3);

    check_exit();
}
Exemplo n.º 19
0
void SkpTcpSocketTest::skp_write()
{
    if(check_exit())
        return;

    static int i = 0;
    if(i == 0) {
        i = 1;
        QTime time;
        time= QTime::currentTime();
        qsrand(time.msec()+time.second()*1000);
    }

    int max = 100;
    int min = 65;
    int data=(qrand()%(max - min + 1)) + min;

    memset(m_writeBuffer, data, BUFFER_SIZE);

    qint64 skip = 0;
    qint64 size = 0;
    qint64 left = BUFFER_SIZE;

    while(left > 0) {
        size = write(m_writeBuffer + skip, left);
        //qDebug() << "write size = " << size;
        if(size == 0) {
            //skp_sleep(2);
            QThread::msleep(5);
            m_writeSleep++;
            if(m_writeSleep % 10 == 0) {
                qDebug() << "write error ";
            }
            if(m_writeSleep == 50) {
                qDebug() << "write error len = 0";
                skp_on_error(QAbstractSocket::RemoteHostClosedError);
                return;
            }
        }

        if(size < 0) {
            qDebug() << "write error len < 0";
            skp_on_error(QAbstractSocket::RemoteHostClosedError);
            return;
        }

        if(m_isDelete)
            return;

        left -= size;
        skip += size;
        if(!IS_CHECK_DATA)
            break;
    }

    if(IS_CHECK_DATA)
        m_writeSize += BUFFER_SIZE;
    else
        m_writeSize += size;

    m_count++;


    if(g_ShowPrintNumber > 0 && m_count % g_ShowPrintNumber == 0)
        qDebug() << "m_count" << m_count;
}