Пример #1
0
void *mlx5_uar_mmap(int idx, int cmd, int page_size, int cmd_fd)
{
	off_t offset;

	offset = 0;
	set_command(cmd, &offset);
	set_index(idx, &offset);

	return mmap(NULL, page_size, PROT_WRITE, MAP_SHARED, cmd_fd, page_size * offset);
}
Пример #2
0
int a2dp_stop(a2dpData d)
{
	struct bluetooth_data* data = (struct bluetooth_data*)d;
	DBG("a2dp_stop\n");
	if (!data)
		return 0;

	set_command(data, A2DP_CMD_STOP);
	return 0;
}
Пример #3
0
/* send conn's ip and port which used to connect to user server
 * to mesage server */
void send_conn_info_to_message(struct conn_server *server)
{
	struct list_packet *lp = allocator_malloc(&server->packet_allocator);
	packet_init(lp);
	set_length(lp, 18);
	set_command(lp, CMD_CONN_INFO);
	set_field_uint32_t(get_parameters(lp), 0, server->conn_user_ip);
	set_field_uint16_t(get_parameters(lp), 4, server->conn_user_port);
	list_add_tail(&lp->list, &(server->message_conn.send_packet_list));
	wait_for_write(server->efd, server->message_conn.sfd);
}
Пример #4
0
				BOOST_FOREACH(const std::string &e, data) {
					exec_payload = exec_message.add_payload();
					std::list<std::string> line;
					boost::iter_split(line, e, boost::algorithm::first_finder(separator));
					if (line.size() >= 1) {
						set_command(line.front());
						line.pop_front();
					}
					BOOST_FOREACH(const std::string &a, line) {
						get_exec_payload()->add_arguments(a);
					}
int YARPMEIDeviceDriver::setCommand(void *cmd)
{
	int16 rc = 0;
	SingleAxisParameters *tmp = (SingleAxisParameters *) cmd;
	int axis = tmp->axis;
	double *tmpPos = (double *) tmp->parameters;
	
	rc = set_command(axis, *tmpPos);

	return rc;
}
Пример #6
0
int		main(int argc, char **argv)
{
	t_command 	*command;

	if (!(command = set_command(argc, argv)))
		exit(EXIT_FAILURE);
	if ((read_args(command->paths, command)) == -1)
	{
		delete_command(command);
		exit(EXIT_FAILURE);
	}
} 
Пример #7
0
void
mfc_term_view::recall_next()   // bound to VK_DOWN in term_view
{
  long i = hist_view->bol(1);
  if (i < hist_view->eob(1)) {
    hist_view->GetRichEditCtrl().SetSel(i, i);
    CString txt = hist_view->grab_line();
    set_command(txt);
  } else {
    MessageBeep(MB_OK);
  }
}
Пример #8
0
  IDE::IDE(hw::PCI_Device& pcidev, selector_t sel) :
    _pcidev {pcidev},
    _drive  {(uint8_t)sel},
    _iobase {0U},
    _nb_blk {0U}
{
  INFO("IDE","VENDOR_ID : 0x%x, PRODUCT_ID : 0x%x", _pcidev.vendor_id(), _pcidev.product_id());
  INFO("IDE","Attaching to  PCI addr 0x%x",_pcidev.pci_addr());
  
  /** PCI device checking */
  if (_pcidev.vendor_id() not_eq IDE_VENDOR_ID) {
    panic("This is not an Intel device");
  }
  CHECK(true, "Vendor ID is INTEL");

  if (_pcidev.product_id() not_eq IDE_PRODUCT_ID) {
    panic("This is not an IDE Controller");
  }
  CHECK(true, "Product ID is IDE Controller");

  /** Probe PCI resources and fetch I/O-base for device */
  _pcidev.probe_resources();
  _iobase = _pcidev.iobase();
  CHECK(_iobase, "Unit has valid I/O base (0x%x)", _iobase);

  /** IRQ initialization */
  CHECK(IDE_IRQN, "Unit has IRQ %i", IDE_IRQN);
  enable_irq_handler();
  INFO("IDE", "Enabling IRQ handler");

  /** IDE device initialization */
  set_irq_mode(false);
  set_drive(0xA0 | _drive);
  set_nbsectors(0U);
  set_blocknum(0U);
  set_command(IDE_CMD_IDENTIFY);

  if (not inb(IDE_STATUS)) {
    panic("Device not found");
  }
  CHECK(true, "IDE device found");
  wait_status_flags(IDE_DRDY, false);

  uint16_t buffer[256];
  for (int i {0}; i < 256; ++i) {
    buffer[i] = inw(IDE_DATA);
  }

  _nb_blk = (buffer[61] << 16) | buffer[60];

  INFO("IDE", "Initialization complete");
}
Пример #9
0
		void set_batch(const std::vector<std::string> &data) {
			if (type == type_submit) {
				BOOST_FOREACH(const std::string &e, data) {
					submit_payload = submit_message.add_payload();
					std::vector<std::string> line;
					boost::iter_split(line, e, boost::algorithm::first_finder(separator));
					if (line.size() >= 3)
						set_message(line[2]);
					if (line.size() >= 2)
						set_result(line[1]);
					if (line.size() >= 1)
						set_command(line[0]);
				}
Пример #10
0
/* send offline message to status server */
void send_offline_to_status(struct conn_server *server, uint32_t uin)
{
	struct list_packet *lp = allocator_malloc(&server->packet_allocator);
	packet_init(lp);
	set_length(lp, 24);
	set_command(lp, CMD_STATUS_CHANGE);
	set_uin(lp, uin);
	set_field_uint32_t(get_parameters(lp), 0, uin);
	set_field_uint16_t(get_parameters(lp), 10,
			STATUS_CHANGE_OFFLINE);
	list_add_tail(&lp->list, &(server->status_conn.send_packet_list));
	wait_for_write(server->efd, server->status_conn.sfd);
}
Пример #11
0
/*
1.函数内部需要注意:while(1),while(-1)都会执行循环体,只有while(0)时才跳出循环体
2.目前只能处理读写数据长度为SECTOR_SIZE整数倍的请求,否则会出错
*/
static void hd_rdwt(MESSAGE *message){
    int hd_index=HD_INDEX(message->device);
    int hd_part_index=HD_PART_INDEX(message->device);

    u64 position=message->position;
#ifdef DEBUG_HD
    printl("position=%d\n",position);
#endif
    assert((position>>SECTOR_SIZE_SHIFT)<(1<<31),"");
    assert(position%SECTOR_SIZE==0,"hd readwrite start position must be the multiple of SECTOR_SIZE");//读取的起始位置必须在扇区的起始位置

    HD_COMMAND hd_command;
    u32 base=get_part_info(&hd_info[hd_index],hd_part_index)->base;
    u32 sector_index=base+(u32)(position>>SECTOR_SIZE_SHIFT);
    int sector_length=(message->length+SECTOR_SIZE-1)/SECTOR_SIZE;
    int cmd=(message->type==INFO_FS_READ)?ATA_READ:ATA_WRITE;
    set_command(&hd_command,hd_index,0,0,sector_length,sector_index,cmd);
    hd_command_out(&hd_command);

    int bytes_left=message->length;
#ifdef DEBUG_HD
    printl("sector_index=%d sector_length=%d bytes_left=%d\n",sector_index,sector_length,bytes_left);
#endif
    void *la=(void *)va2la(message->source_pid,message->arg_pointer);
#ifdef DEBUG_HD
    printl("source_pid=%d la[0]=%d\n",message->source_pid,*(int*)la);
#endif
//此处需要注意:while(1),while(-1)都会执行循环体,只有while(0)时才跳出循环体
    while(bytes_left>0){
        int bytes=min(SECTOR_SIZE,bytes_left);
        if(message->type==INFO_FS_READ){
            interrupt_wait();
            port_read(REG_P_DATA,hdbuf,SECTOR_SIZE);
            memcpy(la,(void *)va2la(TASK_HD,hdbuf),bytes);
        }else{
            if(!wait_for(STATUS_DRQ_MASK,STATUS_DRQ,HD_TIME_OUT))
                panic("hd writing error!\n");
            /* printl("bytes=%d",bytes); */
            port_write(REG_P_DATA,la,bytes);
            /* printl("test1"); */
            interrupt_wait();
            /* printl("test2"); */
        }
        bytes_left-=bytes;
        la+=bytes;
        /* printl("(bytes_left>0)=%d\n",bytes_left>0); */
    }
#ifdef DEBUG_HD
    printl("hd_rdwt ok!\n");
#endif
}
Пример #12
0
/**
 * 初始化LCD.
 * 参考:<http://www.repairfaq.org/filipg/LINK/F_Tech_LCD4.html#TECHLCD_001>
 * http://lcd-linux.sourceforge.net/pdfdocs/hd44780.pdf
 */
void init_lcd(void)
{

    //3个控制端口为输出
    CRTL_OUT()
    //4条数据总线:输出
    SET_DB_OUT()
    //多次设置,确保初始化
    //设置功能: [0] [0]  [1] [1]DL-8位  X X X X
    uint8_t fun_8bit_2line = 0b00110000;//低四位无关
    //设置功能: [0] [0]  [1] [0]DL-4位 [1]N-双行 [0]F-5*7字形 X X
    uint8_t fun_4bit_2line = 0b00101000;
    _delay_ms(15);     //2
    set_command(fun_8bit_2line, 0);     //3设为 8 位接口模式,busy=0 不检测忙信号
    _delay_ms(4.1);     //4
    set_command(fun_8bit_2line, 0);	//5
    _delay_us(100);     //6
    set_command(fun_8bit_2line, 0);	//7
    _delay_ms(4.1);     //8
    //DL:数据接口宽度标志:DL=1,8 位数据总线 DB7~DB0;DL=0,4 位数据总线 DB7~DB4,DB3~DB0
    //不用,使用此方式传送数据,需分两次进行;
    //N:显示行数标志;
    //F:显示字符点阵字体标志;
    //功能设置
    set_command(fun_4bit_2line, 0);	//9
    _delay_us(40);     //10
    set_command(fun_4bit_2line, 1);	//11
    _delay_us(40);     //12
    //开关显示
    set_command(0b00001000, 1);     //13.显示关闭(0) 关光标(0) 关光标闪烁(0)
    _delay_us(40);     //14
    //开关显示
    set_command(0b00001111, 1);     //15.显示开启(1) 显示光标(1) 光标闪烁(1)
    _delay_us(40);     //16
    //设置输入方式
    set_command(0b00000110, 1);     //17.写入新数据后光标右移(1) 文字不动(0)
    _delay_us(40);     //18
    //19 初始化完成
    //清屏 可选的
    set_command(0b00000001, 1);     //显示清屏(1)
    _delay_us(40);     //18

}
Пример #13
0
		virtual void read(boost::shared_ptr<nscapi::settings_proxy> proxy, bool oneliner, bool is_sample) {
			parent::read(proxy, oneliner, is_sample);
			set_alias(boost::algorithm::to_lower_copy(get_alias()));
			set_command(get_value());

			nscapi::settings_helper::settings_registry settings(proxy);
			nscapi::settings_helper::path_extension root_path = settings.path(get_path());
			if (is_sample)
				root_path.set_sample();

			if (!oneliner) {
				root_path.add_path()
					("script: " + get_alias(), "The configuration section for the  " + get_alias() + " script.")
					;

				root_path.add_key()
					("command", sh::string_fun_key(boost::bind(&command_object::set_command, this, _1)),
						"COMMAND", "Command to execute")

					("user", nscapi::settings_helper::string_key(&user),
						"USER", "The user to run the command as", true)

					("domain", nscapi::settings_helper::string_key(&domain),
						"DOMAIN", "The user to run the command as", true)

					("password", nscapi::settings_helper::string_key(&password),
						"PASSWORD", "The user to run the command as", true)

					("session", nscapi::settings_helper::string_key(&session),
						"SESSION", "Session you want to invoke the client in either the number of current for the one with a UI", true)

					("display", nscapi::settings_helper::bool_key(&display),
						"DISPLAY", "Set to true if you want to display the resulting window or not", true)

					("encoding", nscapi::settings_helper::string_key(&encoding),
						"ENCODING", "The encoding to parse the command as", true)

					("ignore perfdata", nscapi::settings_helper::bool_key(&ignore_perf),
						"IGNORE PERF DATA", "Do not parse performance data from the output", false)

					("capture output", nscapi::settings_helper::bool_key(&no_fork),
						"CAPTURE OUTPUT", "This should be set to false if you want to run commands which never terminates (i.e. relinquish control from NSClient++). The effect of this is that the command output will not be captured. The main use is to protect from socket reuse issues", true)

					;

				settings.register_all();
				settings.notify();
			}
		}
Пример #14
0
  void IDE::read(block_t blk, on_read_func callback) {
    if (blk >= _nb_blk) {
      // avoid reading past the disk boundaries
      callback(buffer_t());
      return;
    }

    set_irq_mode(true);
    set_drive(0xE0 | _drive | ((blk >> 24) & 0x0F));
    set_nbsectors(1);
    set_blocknum(blk);
    set_command(IDE_CMD_READ);

    _current_callback = callback;
    _nb_irqs = 1;
  }
Пример #15
0
void set_storage(istorage& Storage)
{
	g_option_storage = &Storage;

	// Defines the version of the data stored in the options tree ... incrementing it will force user options to be reset
	const unsigned long current_version = 4;
	if(detail::version_element().text.empty() || (boost::lexical_cast<unsigned long>(detail::version_element().text) < current_version))
	{
		log() << warning << "Resetting options data to version " << current_version << std::endl;

		tree().children.clear();
		detail::version_element().text = k3d::string_cast(current_version);
	}

	// Default external paths
	if(detail::path_element(path::render_farm()).text.empty())
		detail::path_element(path::render_farm()).text = system::get_temp_directory().native_utf8_string().raw();
	if(detail::path_element(path::scripts()).text.empty())
		detail::path_element(path::scripts()).text = (share_path() / filesystem::generic_path("scripts")).native_utf8_string().raw();
	if(detail::path_element(path::documents()).text.empty())
		detail::path_element(path::documents()).text = system::get_home_directory().native_utf8_string().raw();
	if(detail::path_element(path::bitmaps()).text.empty())
		detail::path_element(path::bitmaps()).text = system::get_home_directory().native_utf8_string().raw();
	if(detail::path_element(path::tutorials()).text.empty())
		detail::path_element(path::tutorials()).text = system::get_home_directory().native_utf8_string().raw();
	if(detail::path_element(path::render_frame()).text.empty())
		detail::path_element(path::render_frame()).text = system::get_home_directory().native_utf8_string().raw();
	if(detail::path_element(path::render_animation()).text.empty())
		detail::path_element(path::render_animation()).text = system::get_home_directory().native_utf8_string().raw();
	if(detail::path_element(path::displacement_shaders()).text.empty())
		detail::path_element(path::displacement_shaders()).text = (share_path() / filesystem::generic_path("shaders/displacement")).native_utf8_string().raw();
	if(detail::path_element(path::imager_shaders()).text.empty())
		detail::path_element(path::imager_shaders()).text = (share_path() / filesystem::generic_path("shaders/imager")).native_utf8_string().raw();
	if(detail::path_element(path::light_shaders()).text.empty())
		detail::path_element(path::light_shaders()).text = (share_path() / filesystem::generic_path("shaders/light")).native_utf8_string().raw();
	if(detail::path_element(path::surface_shaders()).text.empty())
		detail::path_element(path::surface_shaders()).text = (share_path() / filesystem::generic_path("shaders/surface")).native_utf8_string().raw();
	if(detail::path_element(path::transformation_shaders()).text.empty())
		detail::path_element(path::transformation_shaders()).text = (share_path() / filesystem::generic_path("shaders/transformation")).native_utf8_string().raw();
	if(detail::path_element(path::volume_shaders()).text.empty())
		detail::path_element(path::volume_shaders()).text = (share_path() / filesystem::generic_path("shaders/volume")).native_utf8_string().raw();

	// Default external commands
	if(get_command(command::bitmap_viewer()).empty())
		set_command(command::bitmap_viewer(), DEFAULT_BITMAP_VIEWER);
}
Пример #16
0
void
mfc_term_view::recall_prev()   // bound to VK_UP in term_view
{
  long i;
  if (!recalling) {
    i = hist_view->eob(1);
    hist_view->GetRichEditCtrl().SetSel(i, i);
  } else {
    i = hist_view->bol();
  }
  long j = hist_view->bol(-1);
  if (j < i) {
    hist_view->GetRichEditCtrl().SetSel(j, j);
    CString txt = hist_view->grab_line();
    set_command(txt);
  } else {
    MessageBeep(MB_OK);
  }
}
Пример #17
0
/*
功能:
    获得一个分区内的完整分区表,即包含四项分区表信息    
参数:
    entry:
返回值:
    (无)
*/
static void get_part_table(int index,int sector_index,struct s_hd_part_entry *entry,int entry_count){
    int hd_index=HD_INDEX(DEVICE(index));
    struct s_hd_command cmd;

    set_command(&cmd,hd_index,0,0,1,sector_index,ATA_READ);

#ifdef DEBUG
    printl("feathures=%d   count=%d   lba_low=%d lba_mid=%d lba_high=%d device=%d command=%d\n",cmd.features,cmd.count,cmd.lba_low,cmd.lba_mid,cmd.lba_high,cmd.device,cmd.command);
#endif

    hd_command_out(&cmd);//命令发出
    interrupt_wait();//等待硬盘中断

    port_read(REG_P_DATA,hdbuf,SECTOR_SIZE);

    memcpy(entry,
           hdbuf+PARTITION_TABLE_OFFSET,
           sizeof(struct s_hd_part_entry)*entry_count);
}
Пример #18
0
static int mlx5_map_internal_clock(struct mlx5_device *mdev,
				   struct ibv_context *ibv_ctx)
{
	struct mlx5_context *context = to_mctx(ibv_ctx);
	void *hca_clock_page;
	off_t offset = 0;

	set_command(MLX5_EXP_MMAP_GET_CORE_CLOCK_CMD, &offset);
	hca_clock_page = mmap(NULL, mdev->page_size,
			      PROT_READ, MAP_SHARED, ibv_ctx->cmd_fd,
			      offset * mdev->page_size);

	if (hca_clock_page == MAP_FAILED) {
		fprintf(stderr, PFX
			"Warning: Timestamp available,\n"
			"but failed to mmap() hca core clock page.\n");
		return -1;
	}

	context->hca_core_clock = hca_clock_page + context->core_clock.offset;

	return 0;
}
Пример #19
0
int make_chasen_process( CHASEN_FD *fd_in, CHASEN_FD *fd_out )
{
	int to_parent[2];

	if( chasen_process != 0 )  return 0;

	pchain[0].command[0] = chasen_bin;
	pchain[0].command[1] = chasen_rc_option;
	pchain[0].command[2] = chasen_rc;
	pchain[0].command[3] = '\0';

	if( chaone_bin[0] == '\0' )  {
		pchain[0].last = 1;		/* set 1 if this process is the last */
	} else {
		pchain[0].last = 0;
		set_command( chaone_bin, pchain[1].command );
		pchain[1].last = 1;	
	}

	/* to_parent は「最後の子 -> 親」で使う。*/
	if( pipe(to_parent) < 0 )  {
		ErrMsg( "pipe error in init_text_analysis\n" );
		return -1;
	}

	/* 親が書き込むfdはこのルーチンの中で決まる。*/
	*fd_out = make_pipe_child( pchain, to_parent );
	if( *fd_out < 0 )  return -1;

	*fd_in = to_parent[0];		/* 親はここから読み出す。*/
	close( to_parent[1] );		/* 親はここへは書かない。*/
	chasen_process = 1;
#ifdef PRINTDATA
	TmpMsg( "* chasen start.\n" );
#endif
	return 0;
}
Пример #20
0
static int command()
{
    FILE *fp;
    int i;
    /* string holding name of save or load file */
    char sv_file[MAX_LINE_LEN + 1];

    for (i = 0; i < MAX_NUM_VAR; i++)
	c_dummy_var[i][0] = NUL;	/* no dummy variables */

    if (is_definition(c_token))
	define();
    else if (almost_equals(c_token, "h$elp") || equals(c_token, "?")) {
	c_token++;
	do_help(1);
    } else if (equals(c_token, "testtime")) {
	/* given a format and a time string, exercise the time code */
	char format[160], string[160];
	struct tm tm;
	double secs;
	if (isstring(++c_token)) {
	    quote_str(format, c_token, 159);
	    if (isstring(++c_token)) {
		quote_str(string, c_token++, 159);
		memset(&tm, 0, sizeof(tm));
		gstrptime(string, format, &tm);
		secs = gtimegm(&tm);
		fprintf(stderr, "internal = %f - %d/%d/%d::%d:%d:%d , wday=%d, yday=%d\n",
			secs, tm.tm_mday, tm.tm_mon + 1, tm.tm_year % 100, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_wday, tm.tm_yday);
		memset(&tm, 0, sizeof(tm));
		ggmtime(&tm, secs);
		gstrftime(string, 159, format, secs);
		fprintf(stderr, "convert back \"%s\" - %d/%d/%d::%d:%d:%d , wday=%d, yday=%d\n",
			string, tm.tm_mday, tm.tm_mon + 1, tm.tm_year % 100, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_wday, tm.tm_yday);
	    }
	}
    } else if (almost_equals(c_token, "test")) {
	c_token++;
	test_term();
    } else if (almost_equals(c_token, "scr$eendump")) {
	c_token++;
#ifdef _Windows
	screen_dump();
#else
	fputs("screendump not implemented\n", stderr);
#endif
    } else if (almost_equals(c_token, "pa$use")) {
	struct value a;
	int sleep_time, text = 0;
	char buf[MAX_LINE_LEN + 1];

	c_token++;
	sleep_time = (int) real(const_express(&a));
	buf[0] = NUL;
	if (!(END_OF_COMMAND)) {
	    if (!isstring(c_token))
		int_error("expecting string", c_token);
	    else {
		quote_str(buf, c_token, MAX_LINE_LEN);
		++c_token;
#ifdef _Windows
		if (sleep_time >= 0)
#else
# ifdef OS2
		if (strcmp(term->name, "pm") != 0 || sleep_time >= 0)
# else
#  ifdef MTOS
	        if (strcmp(term->name, "mtos") != 0 || sleep_time >= 0)
#  endif /* MTOS */
# endif /* OS2 */
#endif /* _Windows */
			fputs(buf, stderr);
		text = 1;
	    }
	}
	if (sleep_time < 0) {
#ifdef _Windows
	    if (!Pause(buf))
		bail_to_command_line();
#else
# ifdef OS2
	    if (strcmp(term->name, "pm") == 0 && sleep_time < 0) {
		int rc;
		if ((rc = PM_pause(buf)) == 0)
		    bail_to_command_line();
		else if (rc == 2) {
		    fputs(buf, stderr);
		    text = 1;
		    (void) fgets(buf, MAX_LINE_LEN, stdin);
		}
	    }
# else				/* !OS2 */
#  ifdef _Macintosh
	    if (strcmp(term->name, "macintosh") == 0 && sleep_time < 0)
		Pause(sleep_time);
#  else				/* !_Macintosh */
#   ifdef MTOS
	    if (strcmp(term->name, "mtos") == 0) {
		int MTOS_pause(char *buf);
		int rc;
		if ((rc = MTOS_pause(buf)) == 0)
		    bail_to_command_line();
		else if (rc == 2) {
		    fputs(buf, stderr);
		    text = 1;
		    (void) fgets(buf, MAX_LINE_LEN, stdin);
		}
	    } else if (strcmp(term->name, "atari") == 0) {
		char *readline(char *);
		char *line = readline("");
		if (line)
		    free(line);
	    } else
		(void) fgets(buf, MAX_LINE_LEN, stdin);
#   else			/* !MTOS */
#    ifdef ATARI
	    if (strcmp(term->name, "atari") == 0) {
		char *readline(char *);
		char *line = readline("");
		if (line)
		    free(line);
	    } else
		(void) fgets(buf, MAX_LINE_LEN, stdin);
#    else			/* !ATARI */
	    (void) fgets(buf, MAX_LINE_LEN, stdin);
	    /* Hold until CR hit. */
#    endif			/* !ATARI */
#   endif			/* !MTOS */
#  endif			/* !_Macintosh */
# endif				/* !OS2 */
#endif
	}
	if (sleep_time > 0)
	    GP_SLEEP(sleep_time);

	if (text != 0 && sleep_time >= 0)
	    fputc('\n', stderr);
	screen_ok = FALSE;
    } else if (almost_equals(c_token, "pr$int")) {
	int need_space = 0;	/* space printed between two expressions only */
	screen_ok = FALSE;
	do {
	    ++c_token;
	    if (isstring(c_token)) {
		char s[MAX_LINE_LEN];
		quote_str(s, c_token, MAX_LINE_LEN);
		fputs(s, stderr);
		need_space = 0;
		++c_token;
	    } else {
		struct value a;
		(void) const_express(&a);
		if (need_space)
		    putc(' ', stderr);
		need_space = 1;
		disp_value(stderr, &a);
	    }
	} while (!END_OF_COMMAND && equals(c_token, ","));

	(void) putc('\n', stderr);
    } else if (almost_equals(c_token, "fit")) {
	++c_token;
	do_fit();
    } else if (almost_equals(c_token, "up$date")) {
	char tmps[80];
	char tmps2[80];
	/* Have to initialise tmps2, otherwise
	 * update() cannot decide whether a valid
	 * filename was given. lh
	 */
	tmps2[0] = NUL;
	if (!isstring(++c_token))
	    int_error("Parameter filename expected", c_token);
	quote_str(tmps, c_token++, 80);
	if (!(END_OF_COMMAND)) {
	    if (!isstring(c_token))
		int_error("New parameter filename expected", c_token);
	    else
		quote_str(tmps2, c_token++, 80);
	}
	update(tmps, tmps2);
    } else if (almost_equals(c_token, "p$lot")) {
	plot_token = c_token++;
	SET_CURSOR_WAIT;
	plotrequest();
	SET_CURSOR_ARROW;
    } else if (almost_equals(c_token, "sp$lot")) {
	plot_token = c_token++;
	SET_CURSOR_WAIT;
	plot3drequest();
	SET_CURSOR_ARROW;
    } else if (almost_equals(c_token, "rep$lot")) {
	if (replot_line[0] == NUL)
	    int_error("no previous plot", c_token);
	c_token++;
	SET_CURSOR_WAIT;
	replotrequest();
	SET_CURSOR_ARROW;
    } else if (almost_equals(c_token, "se$t"))
	set_command();
    else if (almost_equals(c_token, "res$et"))
	reset_command();
    else if (almost_equals(c_token, "sh$ow"))
	show_command();
    else if (almost_equals(c_token, "cl$ear")) {
	term_start_plot();

	if (multiplot && term->fillbox) {
	    unsigned int x1 = (unsigned int) (xoffset * term->xmax);
	    unsigned int y1 = (unsigned int) (yoffset * term->ymax);
	    unsigned int width = (unsigned int) (xsize * term->xmax);
	    unsigned int height = (unsigned int) (ysize * term->ymax);
	    (*term->fillbox) (0, x1, y1, width, height);
	}
	term_end_plot();

	screen_ok = FALSE;
	c_token++;
    } else if (almost_equals(c_token, "she$ll")) {
	do_shell();
	screen_ok = FALSE;
	c_token++;
    } else if (almost_equals(c_token, "sa$ve")) {
	if (almost_equals(++c_token, "f$unctions")) {
	    if (!isstring(++c_token))
		int_error("expecting filename", c_token);
	    else {
		quote_str(sv_file, c_token, MAX_LINE_LEN);
		save_functions(fopen(sv_file, "w"));
	    }
	} else if (almost_equals(c_token, "v$ariables")) {
	    if (!isstring(++c_token))
		int_error("expecting filename", c_token);
	    else {
		quote_str(sv_file, c_token, MAX_LINE_LEN);
		save_variables(fopen(sv_file, "w"));
	    }
	} else if (almost_equals(c_token, "s$et")) {
	    if (!isstring(++c_token))
		int_error("expecting filename", c_token);
	    else {
		quote_str(sv_file, c_token, MAX_LINE_LEN);
		save_set(fopen(sv_file, "w"));
	    }
	} else if (isstring(c_token)) {
	    quote_str(sv_file, c_token, MAX_LINE_LEN);
	    save_all(fopen(sv_file, "w"));
	} else {
	    int_error("filename or keyword 'functions', 'variables', or 'set' expected", c_token);
	}
	c_token++;
    } else if (almost_equals(c_token, "l$oad")) {
	if (!isstring(++c_token))
	    int_error("expecting filename", c_token);
	else {
	    quote_str(sv_file, c_token, MAX_LINE_LEN);
	    /* load_file(fp=fopen(sv_file, "r"), sv_file, FALSE); OLD
	     * DBT 10/6/98 handle stdin as special case
	     * passes it on to load_file() so that it gets
	     * pushed on the stack and recusion will work, etc
	     */
	    fp = strcmp(sv_file, "-") ? fopen(sv_file, "r") : stdin; 
	    load_file(fp, sv_file, FALSE);
	    /* input_line[] and token[] now destroyed! */
	    c_token = num_tokens = 0;
	}
    } else if (almost_equals(c_token, "ca$ll")) {
	if (!isstring(++c_token))
	    int_error("expecting filename", c_token);
	else {
	    quote_str(sv_file, c_token, MAX_LINE_LEN);
	    load_file(fopen(sv_file, "r"), sv_file, TRUE);	/* Argument list follows filename */
	    /* input_line[] and token[] now destroyed! */
	    c_token = num_tokens = 0;
	}
    } else if (almost_equals(c_token, "if")) {
	double exprval;
	struct value t;
	if (!equals(++c_token, "("))	/* no expression */
	    int_error("expecting (expression)", c_token);
	exprval = real(const_express(&t));
	if (exprval != 0.0) {
	    /* fake the condition of a ';' between commands */
	    int eolpos = token[num_tokens - 1].start_index + token[num_tokens - 1].length;
	    --c_token;
	    token[c_token].length = 1;
	    token[c_token].start_index = eolpos + 2;
	    input_line[eolpos + 2] = ';';
	    input_line[eolpos + 3] = NUL;
	} else
	    c_token = num_tokens = 0;
    } else if (almost_equals(c_token, "rer$ead")) {
	fp = lf_top();
	if (fp != (FILE *) NULL)
	    rewind(fp);
	c_token++;
    } else if (almost_equals(c_token, "cd")) {
	if (!isstring(++c_token))
	    int_error("expecting directory name", c_token);
	else {
	    quote_str(sv_file, c_token, MAX_LINE_LEN);
	    if (changedir(sv_file)) {
		int_error("Can't change to this directory", c_token);
	    }
	    c_token++;
	}
    } else if (almost_equals(c_token, "pwd")) {
	GP_GETCWD(sv_file, sizeof(sv_file));
	fprintf(stderr, "%s\n", sv_file);
	c_token++;
    } else if (almost_equals(c_token, "ex$it") ||
	       almost_equals(c_token, "q$uit")) {
	/* graphics will be tidied up in main */
	return (1);
    } else if (!equals(c_token, ";")) {		/* null statement */
#ifdef OS2
	if (_osmode == OS2_MODE) {
	    if (token[c_token].is_token) {
		int rc;
		rc = ExecuteMacro(input_line + token[c_token].start_index,
				  token[c_token].length);
		if (rc == 0) {
		    c_token = num_tokens = 0;
		    return (0);
		}
	    }
	}
#endif
	int_error("invalid command", c_token);
    }
    return (0);
}
/**
 * \brief Main method
 */
int main(int argc, char *argv[]) {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "mount utility");
	int	c;
	int	longindex;
	putenv((char *)"POSIXLY_CORRECT=1");	// cast to silence compiler
	while (EOF != (c = getopt_long(argc, argv, "c:dh", longopts,
		&longindex))) {
		switch (c) {
		case 'c':
			Configuration::set_default(std::string(optarg));
			break;
		case 'd':
			debuglevel = LOG_DEBUG;
			break;
		case 'h':
			usage(argv[0]);
			return EXIT_SUCCESS;
		case 'n':
			dryrun = true;
			break;
		case 'f':
			decimal = true;
			break;
		case 'w':
			await_completion = true;
			break;
		case 1:
			switch (longindex) {
			}
			break;
		}
	}

	// next argument must be the command
	if (argc <= optind) {
		throw std::runtime_error("missing command argument");
	}
	std::string	command(argv[optind++]);

	// call the command specific functions
	if (command == "help") {
		return help_command();
	}

	// the other commands need a repository
	astro::module::Repository	repository;
	astro::module::Devices	devices(repository);

	// list command
	if (command == "list") {
		return list_command(devices);
	}

	// other commands need a mount url 
	if (argc <= optind) {
		throw std::runtime_error("missing mount URL");
	}
	DeviceName	mountname(argv[optind++]);
	if (!mountname.hasType(DeviceName::Mount)) {
		throw std::runtime_error("not a mount device name");
	}
	debug(LOG_DEBUG, DEBUG_LOG, 0, "mount device name: %s",
		mountname.toString().c_str());

	// use the Devices class to get the mount associated with this name
	MountPtr	mount = devices.getMount(mountname);
	if (command == "get") {
		return get_command(mount);
	}
	if (command == "cancel") {
		return cancel_command(mount);
	}
	if (command == "wait") {
		return wait_command(mount, true);
	}
	if (command == "set") {
		if (argc < optind + 2) {
			throw std::runtime_error("two angle arguments missing");
		}
		RaDec	radec;
		radec.ra() = Angle::hms_to_angle(argv[optind++]);
		radec.dec() = Angle::dms_to_angle(argv[optind++]);
		return set_command(mount, radec);
	}

	throw std::runtime_error("unknown command");
}
Пример #22
0
static int mlx5_alloc_context(struct verbs_device *vdev,
			      struct ibv_context *ctx, int cmd_fd)
{
	struct mlx5_context	       *context;
	struct mlx5_alloc_ucontext	req;
	struct mlx5_exp_alloc_ucontext_resp resp;
	struct ibv_device		*ibdev = &vdev->device;
	struct verbs_context *verbs_ctx = verbs_get_ctx(ctx);
	struct ibv_exp_device_attr attr;
	int	i;
	int	page_size = to_mdev(ibdev)->page_size;
	int	tot_uuars;
	int	low_lat_uuars;
	int	gross_uuars;
	int	j;
	int	uar_mapped;
	off_t	offset;
	int	err;

	context = to_mctx(ctx);
	if (pthread_mutex_init(&context->env_mtx, NULL))
		return -1;

	context->ibv_ctx.cmd_fd = cmd_fd;

	memset(&resp, 0, sizeof(resp));
	if (gethostname(context->hostname, sizeof(context->hostname)))
		strcpy(context->hostname, "host_unknown");

	tot_uuars = get_total_uuars();
	gross_uuars = tot_uuars / MLX5_NUM_UUARS_PER_PAGE * 4;
	context->bfs = calloc(gross_uuars, sizeof *context->bfs);
	if (!context->bfs) {
		errno = ENOMEM;
		goto err_free;
	}

	low_lat_uuars = get_num_low_lat_uuars();
	if (low_lat_uuars > tot_uuars - 1) {
		errno = ENOMEM;
		goto err_free_bf;
	}

	memset(&req, 0, sizeof(req));
	req.total_num_uuars = tot_uuars;
	req.num_low_latency_uuars = low_lat_uuars;
	if (ibv_cmd_get_context(&context->ibv_ctx, &req.ibv_req, sizeof req,
				&resp.ibv_resp, sizeof resp))
		goto err_free_bf;

	context->max_num_qps		= resp.qp_tab_size;
	context->bf_reg_size		= resp.bf_reg_size;
	context->tot_uuars		= resp.tot_uuars;
	context->low_lat_uuars		= low_lat_uuars;
	context->cache_line_size	= resp.cache_line_size;
	context->max_sq_desc_sz = resp.max_sq_desc_sz;
	context->max_rq_desc_sz = resp.max_rq_desc_sz;
	context->max_send_wqebb	= resp.max_send_wqebb;
	context->num_ports	= resp.num_ports;
	context->max_recv_wr	= resp.max_recv_wr;
	context->max_srq_recv_wr = resp.max_srq_recv_wr;
	context->max_desc_sz_sq_dc = resp.max_desc_sz_sq_dc;
	context->atomic_sizes_dc = resp.atomic_sizes_dc;
	context->compact_av = resp.flags & MLX5_CAP_COMPACT_AV;

	if (resp.exp_data.comp_mask & MLX5_EXP_ALLOC_CTX_RESP_MASK_CQE_COMP_MAX_NUM)
		context->cqe_comp_max_num = resp.exp_data.cqe_comp_max_num;

	if (resp.exp_data.comp_mask & MLX5_EXP_ALLOC_CTX_RESP_MASK_CQE_VERSION)
		context->cqe_version = resp.exp_data.cqe_version;

	if (resp.exp_data.comp_mask & MLX5_EXP_ALLOC_CTX_RESP_MASK_RROCE_UDP_SPORT_MIN)
		context->rroce_udp_sport_min = resp.exp_data.rroce_udp_sport_min;

	if (resp.exp_data.comp_mask & MLX5_EXP_ALLOC_CTX_RESP_MASK_RROCE_UDP_SPORT_MAX)
		context->rroce_udp_sport_max = resp.exp_data.rroce_udp_sport_max;

	ctx->ops = mlx5_ctx_ops;
	if (context->cqe_version) {
		if (context->cqe_version == 1) {
			ctx->ops.poll_cq = mlx5_poll_cq_1;
		} else {
			printf("Unsupported cqe_vesion = %d, stay on  cqe version 0\n",
			       context->cqe_version);
			context->cqe_version = 0;
		}
	}

	attr.comp_mask = IBV_EXP_DEVICE_ATTR_RESERVED - 1;
	err = mlx5_query_device_ex(ctx, &attr);
	if (!err) {
		if (attr.comp_mask & IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS)
			context->exp_device_cap_flags = attr.exp_device_cap_flags;

		if (attr.comp_mask & IBV_EXP_DEVICE_ATTR_MAX_CTX_RES_DOMAIN) {
			context->max_ctx_res_domain = attr.max_ctx_res_domain;
			mlx5_spinlock_init(&context->send_db_lock, !mlx5_single_threaded);
			INIT_LIST_HEAD(&context->send_wc_db_list);
			INIT_LIST_HEAD(&context->wc_uar_list);
		}
		if (resp.exp_data.comp_mask & MLX5_EXP_ALLOC_CTX_RESP_MASK_HCA_CORE_CLOCK_OFFSET) {
			context->core_clock.offset =
				resp.exp_data.hca_core_clock_offset &
				(to_mdev(ibdev)->page_size - 1);
			mlx5_map_internal_clock(to_mdev(ibdev), ctx);
			if (attr.hca_core_clock)
				context->core_clock.mult = ((1ull * 1000) << 21) /
					attr.hca_core_clock;
			else
				context->core_clock.mult = 0;

			/* ConnectX-4 supports 64bit timestamp. We choose these numbers
			 * in order to make sure that after arithmetic operations,
			 * we don't overflow a 64bit variable.
			 */
			context->core_clock.shift = 21;
			context->core_clock.mask = (1ULL << 49) - 1;
		}
	}

	pthread_mutex_init(&context->rsc_table_mutex, NULL);
	pthread_mutex_init(&context->srq_table_mutex, NULL);
	for (i = 0; i < MLX5_QP_TABLE_SIZE; ++i)
		context->rsc_table[i].refcnt = 0;

	for (i = 0; i < MLX5_QP_TABLE_SIZE; ++i)
		context->uidx_table[i].refcnt = 0;

	context->db_list = NULL;

	pthread_mutex_init(&context->db_list_mutex, NULL);

	context->prefer_bf = get_always_bf(&context->ibv_ctx);
	context->shut_up_bf = get_shut_up_bf(&context->ibv_ctx);
	context->enable_cqe_comp = get_cqe_comp(&context->ibv_ctx);
	mlx5_use_mutex = get_use_mutex(&context->ibv_ctx);

	offset = 0;
	set_command(MLX5_MMAP_MAP_DC_INFO_PAGE, &offset);
	context->cc.buf = mmap(NULL, 4096 * context->num_ports, PROT_READ,
			       MAP_PRIVATE, cmd_fd, page_size * offset);
	if (context->cc.buf == MAP_FAILED)
		context->cc.buf = NULL;

	mlx5_single_threaded = single_threaded_app(&context->ibv_ctx);
	for (i = 0; i < resp.tot_uuars / MLX5_NUM_UUARS_PER_PAGE; ++i) {
		uar_mapped = 0;

		/* Don't map UAR to WC if BF is not used */
		if (!context->shut_up_bf) {
			context->uar[i].regs = mlx5_uar_mmap(i, MLX5_MMAP_GET_WC_PAGES_CMD, page_size, cmd_fd);
			if (context->uar[i].regs != MAP_FAILED) {
				context->uar[i].map_type = MLX5_UAR_MAP_WC;
				uar_mapped = 1;
			}
		}

		if (!uar_mapped) {
			context->uar[i].regs = mlx5_uar_mmap(i, MLX5_MMAP_GET_NC_PAGES_CMD, page_size, cmd_fd);
			if (context->uar[i].regs != MAP_FAILED) {
				context->uar[i].map_type = MLX5_UAR_MAP_NC;
				uar_mapped = 1;
			}
		}

		if (!uar_mapped) {
			/* for backward compatibility with old kernel driver */
			context->uar[i].regs = mlx5_uar_mmap(i, MLX5_MMAP_GET_REGULAR_PAGES_CMD, page_size, cmd_fd);
			if (context->uar[i].regs != MAP_FAILED) {
				context->uar[i].map_type = MLX5_UAR_MAP_WC;
				uar_mapped = 1;
			}
		}

		if (!uar_mapped) {
			context->uar[i].regs = NULL;
			goto err_free_cc;
		}
	}

	for (j = 0; j < gross_uuars; ++j) {
		context->bfs[j].reg = context->uar[j / 4].regs +
			MLX5_BF_OFFSET + (j % 4) * context->bf_reg_size;
		context->bfs[j].need_lock = need_uuar_lock(context, j) &&
					    context->uar[j / 4].map_type == MLX5_UAR_MAP_WC;
		mlx5_lock_init(&context->bfs[j].lock,
			       !mlx5_single_threaded,
			       mlx5_get_locktype());
		context->bfs[j].offset = 0;
		if (context->uar[j / 4].map_type == MLX5_UAR_MAP_WC) {
			context->bfs[j].buf_size = context->bf_reg_size / 2;
			context->bfs[j].db_method = (context->bfs[j].need_lock &&  !mlx5_single_threaded) ?
						    MLX5_DB_METHOD_BF :
						    (mlx5_single_threaded && wc_auto_evict_size() == 64 ?
						     MLX5_DB_METHOD_DEDIC_BF_1_THREAD :
						     MLX5_DB_METHOD_DEDIC_BF);

		} else {
			context->bfs[j].db_method = MLX5_DB_METHOD_DB;
		}

		context->bfs[j].uuarn = j;
	}

	mlx5_lock_init(&context->lock32,
		       !mlx5_single_threaded,
		       mlx5_get_locktype());

	mlx5_spinlock_init(&context->hugetlb_lock, !mlx5_single_threaded);
	INIT_LIST_HEAD(&context->hugetlb_list);

	pthread_mutex_init(&context->task_mutex, NULL);

	set_extended(verbs_ctx);
	set_experimental(ctx);

	for (i = 0; i < MLX5_MAX_PORTS_NUM; ++i)
		context->port_query_cache[i].valid = 0;

	return 0;

err_free_cc:
	if (context->cc.buf)
		munmap(context->cc.buf, 4096 * context->num_ports);

	if (context->hca_core_clock)
		munmap(context->hca_core_clock - context->core_clock.offset,
		       to_mdev(ibdev)->page_size);

err_free_bf:
	free(context->bfs);

err_free:
	for (i = 0; i < MLX5_MAX_UAR_PAGES; ++i) {
		if (context->uar[i].regs)
			munmap(context->uar[i].regs, page_size);
	}
	close_debug_file(context);

	return errno;
}
Пример #23
0
int main(int argc, char *argv[]){
  jlist = create_job_list();

  char *tok;
  TOKENIZER *tokenizer;
  int ispipe, redirect_out_flag, redirect_in_flag, not_exec_cmd, is_bg_flag;

  //read-in buffer
  char data[BUFFER_MAX]; 
  char extra[1]; 

  //linked list to add argument arrays to execvp: 1 for process 1, 2 for piped process
  list_elt *argv2_elt = NULL; 
  list_elt *argv1_elt = NULL;
  message_q = NULL;
  int argv1size = 0;
  int argv2size = 0;
  int status;

  //set shell pgid
  sh_pgid = getpgid(0);

  //register sigaction for SIGCHLD, SIGINT, SIGTSTP
  struct sigaction handler_action;
  sigaction(SIGCHLD, NULL, &handler_action);  //save previous action for SIGCHLD to handler_action

  //change what handler_action does
  handler_action.sa_flags |= SA_SIGINFO;
  handler_action.sa_flags |= SA_RESTART;

  handler_action.sa_sigaction = child_signal_handler;
  sigfillset(&handler_action.sa_mask);

  // sigaction setup
  sigaction(SIGCHLD, &handler_action, NULL);
  sigaction(SIGTSTP, &handler_action, NULL);
  sigaction(SIGINT, &handler_action, NULL);

  // igmore the sigint and sigtstp sigmals
  signal(SIGINT, SIG_IGN);
  //signal(SIGTSTP, SIG_IGN);

  while(1){
    signal(SIGTTOU, SIG_IGN); //igmore sigttou for tcsetpgrp

    if (-1 == tcsetpgrp(STDIN_FILENO, sh_pgid)){
      perror("tcsetpgrp read error");
    }

    if(-1 == tcsetpgrp(STDOUT_FILENO, sh_pgid)){
      perror("tcsetpgrp read error 2");
    }

    signal(SIGTTOU, SIG_DFL); // un-ignmore sigttou

    print_list(message_q); // print the message_q

    while(message_q){
      message_q =  delete(message_q, message_q); //empty the message_q
    }
    write(STDOUT_FILENO, "kinda-sh# ", 10); //prompt

    //initialize all the flags before tokenizing
    argv1size = 0;
    argv2size = 0;
    is_bg_flag = 0;
    ispipe = 0;
    redirect_out_flag = 0;
    redirect_in_flag = 0;  
    int new_std_in=0; // <
    int new_std_out = 0; // >
    char* fname_in;
    char* fname_out;
    int error_flag=0;
    not_exec_cmd = 0;
    fg_pid=0;

    int read_val;
    data[0] = '\0'; // null terminate data array

    read_val = read(0, data, BUFFER_MAX); // read into the data 


    if(data[0] != '\n'){
      //check if there is buffer overflow
      if((read_val == BUFFER_MAX) && (data[BUFFER_MAX - 1] != '\n')){ 

        while(1){
          argv2_elt = NULL;
          argv1_elt = NULL;
          read(0, extra, 1); // read 1 char at a time from the input stream until its empty (new line)
          if(extra[0] == '\n'){ //read in until the "return(\n) key is hit (similar to flush the std_in)
            break;
          }
        }
      }
      //error handling for inappropriate read size
      if(read_val < 0){ 
        perror("Read"); //check for read error
      } 
      if(read_val == 0){
        kill(0, SIGKILL);
      }

      data[read_val-1] = '\0'; //null terminate dat
      tokenizer = init_tokenizer(data); //create tokenizer on data

      // start tokenizer loop
      while((tok = get_next_token(tokenizer)) != NULL){

        if(is_bg_flag){
          printf("& should be at the end of the command \n");
          error_flag=1;
          break;
        }

        if( (*tok != '|') && (*tok != '&') && (*tok != '<') &&(*tok !=  '>') && (*tok != '\0')){ //check for token

          if(!ispipe){

            if(redirect_out_flag || redirect_in_flag){
              printf("invalid argument between redirection and pipe\n"); //cat < infile something | wc
              error_flag=1;
              break;
            }
            argv1_elt = add(argv1_elt, tok); // add tok to  arv1
            argv1size++;
          }
          else{ // after pipe - second process
            argv2size++;
            argv2_elt = add(argv2_elt, tok);
          }
          //if jobs command called
          if(str_equals(tok, "jobs")){
            print_job_list(jlist);
            not_exec_cmd = 1;
          }

          // if fg command called
          if(str_equals(tok, "fg")){
            job* new_bg_jb;
            char* num;
            num = get_next_token(tokenizer);
            int num_int = -1;
            not_exec_cmd = 1;
            int list_len;
            //if number argument is not specified, take the most recent background job
            if(num == NULL){
              new_bg_jb = get_ith_job(jlist, 1);
              if(new_bg_jb == NULL){
                printf("fg error: no job in job queue\n");
                break;
              }
            }
            //take the num'th background job
            else{
              num_int= my_atoi(num); // run atoi on input number (ie: fg 2)
              //reverse the number into the correct job order
              list_len = listlength(jlist);
              num_int = num_int - list_len -1;

              if(num_int < 0){
                num_int = num_int * (-1);
              }
              new_bg_jb = get_ith_job(jlist, num_int); //get num_int job from the job list

              if(new_bg_jb == NULL){
                printf("fg error: no [%s] job\n", num);
                free(num);
                break;
              } 
            }
            //take the foreground job pid as the chosen bg pid
            fg_pid= new_bg_jb->pgid;
            message_q = add(message_q, "\n"); // add restarting prompt to message_q
            message_q = add(message_q, new_bg_jb->command);
            message_q = add(message_q, "Restarting: ");

            print_list(message_q);
            while(message_q){
              message_q =  delete(message_q, message_q); //empty the message_q
            }

            if(tcsetpgrp(STDIN_FILENO, fg_pid) == -1){
              perror("tcsetpgrp error");
            }

            //relay SIGCONT to the job, and mask it from all signals but SIGCHLD
            killpg(fg_pid, SIGCONT);

            sigset_t cont_mask;
            sigfillset(&cont_mask);
            sigdelset(&cont_mask, SIGCHLD);

            //now the shell should wait for the new foregrounded job to be finished
            while(fg_pid){
              sigsuspend(&cont_mask);
            }
          }
          //take the specific background job to restart. If already running, do nothing.
          if(str_equals(tok, "bg")){
            job* new_bg_jb;
            not_exec_cmd = 1;
            char* num;
            int num_int=-1;
            num = get_next_token(tokenizer);

            // if num is not specified, get the most recent background job (to restart it)
            if(num == NULL){
              new_bg_jb = get_ith_job(jlist, 1);
              if(new_bg_jb == NULL){
                printf("bg error: no job in job queue\n");
                break;
              }
            }
            else{
              num_int= my_atoi(num); // run atoi for bg 
              //set up num_int to pass
              int list_len;
              list_len = listlength(jlist);
              num_int = num_int - list_len -1;
              if(num_int < 0){
                num_int = num_int * (-1);
              }
              new_bg_jb = get_ith_job(jlist, num_int); // get ith job from job_list

              if(new_bg_jb == NULL){
                printf("bg error: no [%s] job\n", num);
                free(num);
                break;
              }
            }

            if(!job_stopped(new_bg_jb)){
              //   tcsetpgrp(STDIN_FILENO, 0);
              printf("bg error: job is already running in the background\n");
              break;
            }

            killpg(new_bg_jb->pgid, SIGCONT);
            tcsetpgrp(STDIN_FILENO, 0);
          }
        }
        else if(*tok=='>'){ // if redirect out token

          if(redirect_out_flag){
            error_flag=1;
            printf("multiple stdout redirection is invalid\n"); //printf?
            break;
          }
          else{
            fname_out = get_next_token(tokenizer); // get hte next token
            new_std_out = open(fname_out, O_WRONLY| O_TRUNC | O_CREAT, 0644); // open file
            if(new_std_out == -1){
              perror("stdout Redir Error");
            }
            redirect_out_flag=1;
          }
        }
        else if(*tok=='<'){ //if redirect in token

          if(ispipe){
            printf("invalid stdin redirection after pipe\n");
            error_flag=1;
            break;
          }
          else if(redirect_in_flag){
            printf("multiple stdin redirection is invalid\n");
            error_flag=1;
            break;
          }            
          else{
            fname_in = get_next_token(tokenizer); // get next token
            new_std_in = open(fname_in, O_RDONLY); // open the file 
            if(new_std_in == -1){
              perror("stdin Redir Error");
            }
          }
        }
        else if(*tok=='|'){ //if pipe token

          if(ispipe){ // cant have more than 1 pipe (didnt do the extra credit)
            printf("invalid multiple pipes\n");
            error_flag=1;
            break;
          }
          else if(redirect_out_flag){
            printf("invalid pipe after stdout redirection\n");
            error_flag=1;
            break;
          }
          ispipe=1; //set a pipe flag
        }
        else if(*tok == '&'){ // if background command
          is_bg_flag = 1;
        }
      }

      if(is_bg_flag){
        data[read_val-2]= '\0'; // delete the '&' from the data array
      }

      argv1size++;
      argv2size++;

      char *argv1[argv1size];
      char *argv2[argv2size];

      if(error_flag || not_exec_cmd){ //if not elecutable command (jobs, fg, bg...) or error flag (bad command)
        while( argv1_elt ){
          argv1_elt = delete(argv1_elt, argv1_elt); //empty the linked list argv1_elt
        }
        while( argv2_elt ){
          argv2_elt = delete(argv2_elt, argv2_elt); //empty the linked list argv2_elt
        }
        continue;
      }

      //set up argv1 array
      list_elt *cursor = argv1_elt;
      list_elt *last;
      int tempIndex=0;
      //last pointer to the last element of argv1_elt linked list
      while(cursor != NULL){
        last = cursor;
        cursor = cursor->next;
      }
      //move all values from argv1_elt into argv1 array.
      while(last != NULL){ 
        argv1[tempIndex]=last->item;
        last = last->prev;
        tempIndex++;
      }
      argv1[argv1size-1] = NULL;

      //set up argv2 array if there's a pipe
      if(ispipe){
        cursor = argv2_elt;
        tempIndex=0;

        //last pointer to the last element of argv2_elt linked list
        while(cursor != NULL){
          last = cursor;
          cursor = cursor->next;
        }
        //move all values from argv2_elt into argv2 array.
        while(last != NULL){ 
          argv2[tempIndex]=last->item; //put input after the pipe into an array argv2
          last = last->prev;
          tempIndex++;
        }
        argv2[argv2size-1] = NULL;
      }
      free_tokenizer( tokenizer ); 

      // tokenizer update done.

      if((pid=fork()) < 0){
        perror("fork1");
      }

      //process & job stuff
      job* jb;
      jb = create_job(); // create corresponding job
      subjob* sj;
      sj = create_subjob(); // create corresponding subjob
      set_command(data, jb);

      if(pid==0){

        if(setpgid(0,0)==-1){
          perror("setpgid error");
        }
        sj->pid = getpid(); // get subjobs pid
        jb->pgid = getpgid(pid);//pid=0
      }
      else{

        if(setpgid(pid, pid)==-1){
          perror("setpgid error");
        }
        // set correct job and subjob pid vals
        sj->pid = pid;
        jb->pgid = pid;
      }

      set_first_subjob(sj, jb); // link subjob to job
      add_new_job(jb, jlist); // add the job to the job_list jlist

      if(pid==0){
        signal(SIGINT, SIG_DFL);
        signal(SIGTSTP, SIG_DFL);

        if(setpgid(0,0)==-1){
          perror("setpgid error");
        }

        if(new_std_out != 0){
          // if redirect out command, dup accordingly
          if(dup2(new_std_out, STDOUT_FILENO) == -1){ //dup2 for > (out)
            perror("stdout dup2");
            _exit(0);
          }
          free(fname_out);
        }

        if(new_std_in != 0){
          // if redirect in command, dup accordingly
          if(dup2(new_std_in, STDIN_FILENO) == -1){ //dup2 for < (in)
            perror("stdin dup2");
            _exit(0);
          }
          free(fname_in);
        }

        if(ispipe){ // if pipe command called
          int filedes[2];

          if(pipe(filedes)){//pipe
            perror("pipe error");
          }
          scnd_pid = fork();

          if(scnd_pid < 0){ //print error if the fork failed
            perror("Fork");
            exit(-1);
          }
          //create a subjob, set its pid for both child and parent
          subjob* sj2;
          sj2 = create_subjob();

          if(scnd_pid==0){
            sj2->pid = getpid(); 
          }
          else{
            sj2->pid = scnd_pid;
          }

          jb->pgid = getpgid(scnd_pid);

          //add to the job group as the first (most recent) process.
          set_first_subjob(sj2, jb);
          set_next_subjob(sj2, sj);
          pipe_pid=sj2->pid;

          if(scnd_pid==0){ // process that writes to pipe (program 1) grand child

            if(close(filedes[0]) == -1){ // close STDIN part of pipe
              perror("close");
            }

            if(dup2(filedes[1], STDOUT_FILENO) == -1){ // dip for STDOUT
              perror("pipe dup2 #1");
            }
            status =  execvp(argv1[0], argv1); // execute

            if(status == -1){  
              perror("execvp program1");
              exit(-1);
            }
            killpg(0, SIGKILL);
            _exit(0); // exit the child
          }
          else{ //program 2; (first fork) process that reads from pipe
            sigset_t sigmask;
            sigfillset(&sigmask);
            sigdelset(&sigmask, SIGCHLD);

            while(pipe_pid){
              sigsuspend(&sigmask);
            }

            if(close(filedes[1]) == -1){ // close STDOUT part of pipe
              perror("close");
            }

            if(dup2(filedes[0], STDIN_FILENO) == -1){ // dup for the STDIN
              perror("dup2 (pipe #2)");
            }

            status = execvp(argv2[0], argv2); // execute the second part of pipe

            if(status == -1){  
              perror("execvp program2");
            }
            killpg(0, SIGKILL);
            _exit(0);
          }
        }
        else{ // if not pipe, pid.
          status = execvp(argv1[0], argv1); 

          if(status == -1){  
            perror("execvp");
          }
          _exit(0);
        }
      } 
      else{ //kinda-sh
        if(setpgid(pid, pid) ==-1){
          perror("setpgid pid");
        }

        if(is_bg_flag){ //if background command, prompt with running
          printf("Running: %s\n", data);
        }

        if(!is_bg_flag){
          fg_pid= pid; // if not bacground command, set the fg_pid to be the first fork pid val
          tcsetpgrp(STDIN_FILENO, pid);
        }

        sigset_t sigmask0;
        sigfillset(&sigmask0);
        sigdelset(&sigmask0, SIGCHLD);

        //suspend only if it's not bg process  
        while(fg_pid!=0){
          sigsuspend(&sigmask0);
        }
        if(new_std_in != 0){
          close(new_std_in); //close stdin if used
        }
        if(new_std_out != 0){
          close(new_std_out); //close stdout if used
        }

      }
      while(argv1_elt){
        argv1_elt = delete(argv1_elt, argv1_elt); //empty the linked list argv1_elt
      }
      while(argv2_elt){
        argv2_elt = delete(argv2_elt, argv2_elt); //empty the linked list argv2_elt
      }
    } //if data[0]!=\n
  }//while end

  return 0;
}
Пример #24
0
/**
 * 设置字符显示的位置 Set position
 * @param offset 输入位置 第7位为1,其他为地址
 * 1行: 0x00 0x01 ... 0x0f
 * 2行: 0x40 0x41 ... 0x4f
 */
void set_pos(uint8_t offset)
{
    set_command(offset|0b10000000, 1);
}
Пример #25
0
		virtual void read(boost::shared_ptr<nscapi::settings_proxy> proxy, bool oneliner, bool is_sample) {
			parent::read(proxy, oneliner, is_sample);

			set_command(get_value());
			bool is_def = is_default();

			nscapi::settings_helper::settings_registry settings(proxy);
			nscapi::settings_helper::path_extension root_path = settings.path(get_path());
			if (is_sample)
				root_path.set_sample();
			if (oneliner)
				return;

			root_path.add_path()
				("SCHEDULE DEFENITION", "Schedule definition for: " + get_alias())
				;

			root_path.add_key()

				("command", sh::string_fun_key(boost::bind(&schedule_object::set_command, this, _1)),
					"SCHEDULE COMMAND", "Command to execute", is_def)

				("target", sh::string_key(&target_id),
					"TARGET", "The target to send the message to (will be resolved by the consumer)", true)
				("source", sh::string_key(&source_id),
					"SOURCE", "The name of the source system, will automatically use the remote system if a remote system is called. Almost most sending systems will replace this with current systems hostname if not present. So use this only if you need specific source systems for specific schedules and not calling remote systems.", true)

				;
			if (is_def) {
				root_path.add_key()

					("channel", sh::string_key(&channel, "NSCA"),
						"SCHEDULE CHANNEL", "Channel to send results on")

					("interval", sh::string_fun_key(boost::bind(&schedule_object::set_duration, this, _1)),
					"SCHEDULE INTERAVAL", "Time in seconds between each check")

					("randomness", sh::string_fun_key(boost::bind(&schedule_object::set_randomness, this, _1)),
						"RANDOMNESS", "% of the interval which should be random to prevent overloading server resources")

					("schedule", sh::string_fun_key(boost::bind(&schedule_object::set_schedule, this, _1)),
						"SCHEDULE", "Cron-like statement for when a task is run. Currently limited to only one number i.e. 1 * * * * or * * 1 * * but not 1 1 * * *")

					("report", sh::string_fun_key(boost::bind(&schedule_object::set_report, this, _1), "all"),
						"REPORT MODE", "What to report to the server (any of the following: all, critical, warning, unknown, ok)")

					;
			} else {
				root_path.add_key()
					("channel", sh::string_key(&channel),
						"SCHEDULE CHANNEL", "Channel to send results on")

					("interval", sh::string_fun_key(boost::bind(&schedule_object::set_duration, this, _1)),
						"SCHEDULE INTERAVAL", "Time in seconds between each check", true)

					("randomness", sh::string_fun_key(boost::bind(&schedule_object::set_randomness, this, _1)),
						"RANDOMNESS", "% of the interval which should be random to prevent overloading server resources")

					("schedule", sh::string_fun_key(boost::bind(&schedule_object::set_schedule, this, _1)),
						"SCHEDULE", "Cron-like statement for when a task is run. Currently limited to only one number i.e. 1 * * * * or * * 1 * * but not 1 1 * * *")

					("report", sh::string_fun_key(boost::bind(&schedule_object::set_report, this, _1)),
						"REPORT MODE", "What to report to the server (any of the following: all, critical, warning, unknown, ok)", true)

					;
			}

			settings.register_all();
			settings.notify();
		}
Пример #26
0
/**
 * 光标复位到1行1列处.
 */
void return_home(void)
{
    set_command(0b00000010, 1);     //显示开启(1) 显示光标(1) 光标闪烁(1)
}
Пример #27
0
static void change_command( GtkEntry *entry, CPUGraph * base )
{
	set_command( base, gtk_entry_get_text( entry ) );
}
Пример #28
0
/**
 *  set CGRAM address 设置CGRAM地址.
 *  用于自定义字符,低6位为地址位,
 *  7 6 5 4 3 2 1 0 bit
 * +-+-+-+-+-+-+-+-+
 * |0|1| CGRAM addr|
 * +-+-+-----------+
 * 其中0-6为有分为:
 * * 0-2位:表示5*8阵列的第几行(共8行),
 * * 3-6位:表示第几个字符,最多定义8个自定义字符.
 * @param data
 */
void set_cgram_addr(uint8_t addr)
{
    set_command(0b01000000|(addr&0b00111111), 1);
}
Пример #29
0
void a2dp_cleanup(a2dpData d)
{
	struct bluetooth_data* data = (struct bluetooth_data*)d;
	DBG("a2dp_cleanup\n");
	set_command(data, A2DP_CMD_QUIT);
}
Пример #30
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();
}