Пример #1
0
int main(int argc, char *argv[])
{
	FILE *fh = NULL;
	if (argc != 2) {
		fprintf(stderr, "Please specify file to write to.\n");
		return EXIT_FAILURE;
	}
	if (argc == 2) {
		fh = fopen(argv[1], "w");
		if (NULL == fh) {
			fprintf(stderr, "Failure to open file.\n");
			return EXIT_FAILURE;
		}
	}

	int sock = client_init("225.1.1.1", 5555);

	struct sample samples[SAMPLES_PER_FILE];
	memset(samples, 0, sizeof(samples));

	struct sample *cap = samples;
	while (true) {
		size_t len = client_recv(sock, (uint8_t *)cap,
				SAMPLES_PER_CAPTURE * sizeof(*cap));
		assert(SAMPLES_PER_CAPTURE * sizeof(*cap) == len);
		cap += SAMPLES_PER_CAPTURE;

		if (cap >= &samples[SAMPLES_PER_FILE]) {
			// Write out the file with all the known samples.
			fh = fopen(argv[1], "w");
			for (int i = 0; i < ARRAY_LEN(samples); i++) {
				fprintf(fh, "%f %03.4f\n", samples[i].t.tv_sec +
						samples[i].t.tv_nsec / NSEC_PER_SEC,
						((105.84 / 4096) * samples[i].d) / 0.1);
			}
			fclose(fh);

			// Shift room for the new samples.
			memset(samples, 0, sizeof(samples));
			cap = samples;
		}
	}
	return EXIT_SUCCESS;
}
Пример #2
0
void
win_server_main_loop (WinServer *server)
{
	while (!server->stop) {
		fd_set readfds;
		int ret;
		Client *client;
		struct timeval tv;
		struct sockaddr_in addr;
		int addr_len;
		SOCKET sock;

		/* Check whether there are incoming connections. */
		tv.tv_sec = 0;
		tv.tv_usec = 50000;
		FD_ZERO (&readfds);
		FD_SET (server->sock, &readfds);
		ret = select (0, &readfds, NULL, NULL, &tv);
		
		if (ret == SOCKET_ERROR) {
			/* Error. */
			return;

		} else if (ret == 0)
			/* No incoming connections. */
			continue;


		/* Accept incoming connection. */
		addr_len = sizeof (addr);
		sock = accept (server->sock, (struct sockaddr *) &addr, &addr_len);
		if (sock == INVALID_SOCKET) {
			/* Failed. */
			return;
		}

		/* Create a Client structure and pass it to the callback. */
		client = malloc (sizeof (Client));
		client->fd = sock;
		client_init (client);
		server->callback (client);
	}
}
Пример #3
0
/* ----------------------------------------------------------------------------*/
int main(int argc,char* argv[]) {
    int i;
    char directory[1024];

    strcpy(soundCardName,"HPSDR");
    strcpy(server_address,"127.0.0.1"); // localhost

    processCommands(argc,argv);

    fprintf(stderr,"gHPSDR rx %d (Version %s)\n",receiver,VERSION);

    setSoundcard(getSoundcardId(soundCardName));

    // initialize DttSP
    if(getcwd(directory, sizeof(directory))==NULL) {
        fprintf(stderr,"current working directory path is > 1024 bytes!");
        exit(1);
    }
    Setup_SDR(directory);
    Release_Update();
    SetTRX(0,0); // thread 0 is for receive
    SetTRX(1,1);  // thread 1 is for transmit
    SetRingBufferOffset(0,offset);
    SetThreadProcessingMode(0,2);
    SetThreadProcessingMode(1,2);
    SetSubRXSt(0,0,1);
    SetRXOutputGain(0,0,0.20);

    reset_for_buflen(0,1024);
    reset_for_buflen(1,1024);

    client_init(receiver);
    audio_stream_init(receiver);

    // initialize ozy
    ozy_init();

    while(1) {
        sleep(10000);
    }

    return 0;
}
Пример #4
0
int		main(int ac, char **av)
{
  t_client	*clt;

  if ((clt = malloc(sizeof(t_client))) == NULL)
    return (err_msg(": malloc fail"));
  if (ac != 3)
    {
      printf("Usage: ./client <ip server> <port nb>\n");
      return (-1);
    }
  if (client_init(clt, av) == -1)
    return (-1);
  if (client_loop(clt) == -1)
    return (-1);
  close(clt->fd);
  free(clt->line);
  free(clt->srv_ret);
  return (1);
}
Пример #5
0
int main () {

	
	request_t request;
	response_t response;
	
	request.client_id = 1;
  request.priority = 1;
  request.client_seq_id = 1;


  int sd = client_init ("localhost", 5050);

  
  send_request_t(sd, &request);
	read_response_t(sd,&response);
	printf("The worker id is %d\n",response.worker_id);
  
  return 0;
}
Пример #6
0
void	init_client(int s, t_env *e, t_client client)
{
	int		father;
	t_play	player;

	father = fork();
	if (father > 0)
		return ;
	if (father == 0)
	{
		if ((s = client_init(client.port, client.host)) < 0)
		{
			ft_putendl_fd("Client init error\n", 2);
			exit(0);
		}
		printf("SON\n");
		player = init_play(s, client);
		ft_loop(s, e, player);
	}
}
Пример #7
0
int
main(int argc, char* argv[])
{
	CORBA_char filename[] = "/tmp/test-atspi.ior";
        Accessibility_Role data;
	int i;
        struct timeval start, end;
        long d_secs;
        long d_usec;
        
	Accessibility_Accessible service = CORBA_OBJECT_NIL;

        CORBA_Environment ev[1];
        CORBA_exception_init(ev);

	client_init (&argc, argv, &global_orb, ev);
	etk_abort_if_exception(ev, "init failed");

	g_print ("Reading service reference from file \"%s\"\n", filename);

	service = (Accessibility_Accessible) etk_import_object_from_file (global_orb,
							   filename,
							   ev);
        etk_abort_if_exception(ev, "import service failed");


        gettimeofday(&start, NULL);
	for (i=0; i<NUM_CALLS; i++)
	  {
            data = Accessibility_Accessible_getRole(service, ev);
	  }
        gettimeofday(&end, NULL);
        d_secs = end.tv_sec - start.tv_sec;
        d_usec = end.tv_usec - start.tv_usec;
        printf("\nGetRole : %f\n", (float) d_secs + ((float) d_usec / 1000000.0));
 
	client_cleanup (global_orb, service, ev);
        etk_abort_if_exception(ev, "cleanup failed");
 
        exit (0);
}
Пример #8
0
static void
testing_init()
{
#ifdef STATIC_ALLOC_LINKEDLIST_NODES
    printf("Only static memory to be used for linkedlist nodes.\n");
    linkedlist_init();
    printf("\n");
#else
    printf("Linkedlist nodes will be created with heap memory.\n");
#endif

#ifdef STATIC_ALLOC_CLIENTS
    printf("Only static memory to be used for client structures.\n");
    client_init();
    printf("\n");
#else
    printf("Client structures will be created with heap memory.\n");
#endif

    world_init();
}
Пример #9
0
void server_event_accept(struct evconnlistener *listener,
                            evutil_socket_t c_socket,
                            struct sockaddr *c_addr,
                            int socklen, void *arg)
{
    log_info("Connected client socket:%d, from:%s:%d", c_socket,
                                                        inet_ntoa(((struct sockaddr_in*)c_addr)->sin_addr),
                                                        ntohs(((struct sockaddr_in*)c_addr)->sin_port));
    server_t *s= (server_t*) arg;

    if(setting_get_max_connections(s->setting) <= server_get_current_connections(s->worker_list, s->worker_count))
    {
        log_warn("Reached to max connection(%" PRIu64 ")", s->conn_cur_count);
        resp_error_max_connection(s->msg_buf, c_socket);
        close(c_socket);
        return;
    }

    // debug용
    if(s->conn_cur_count > s->conn_max)
    {
        s->conn_max = s->conn_cur_count;
    }

    worker_t *w = server_get_least_connection_worker(s->worker_list, s->worker_count);

    client_t *c = client_init(w, c_socket, (struct sockaddr_in*)c_addr);
    c->worker = w;
    c->bufevent = worker_add_new_connection(w, c_socket);
    c->evbuf = evbuffer_new();

    bufferevent_setcb(c->bufevent, client_event_read, client_event_write, client_event_error, c);
    bufferevent_enable(c->bufevent, EV_READ);

    log_info("Accepted client connection. socket #%d from %s:%d", c_socket, inet_ntoa(c->addr.sin_addr), ntohs(c->addr.sin_port));
    log_info("Connected clients : %"PRIu64"", server_get_current_connections(s->worker_list, s->worker_count));

    return;
}
Пример #10
0
int main(int argc,char *argv[])
{
	int choice = 0;
	
	do {
		printf("1.Server\n2.Client\nEnter Choice or press 0(ZERO) to exit:");
		scanf("%d",&choice);
		switch(choice)
		{
			case 1:
				if ( 0 != server_init())
					printf("Failed to init Server\n");
				
				break;
			case 2:
				client_init();
				break;
			default:
				printf("Byeeee \n");
				exit(0);
		}
	}while(1);
}
Пример #11
0
void client_new(int fd, const struct sockaddr *sa, size_t sa_length, int uid)
{
    struct client *client;
    char *remote;

    if (num_clients >= client_max_connections) {
        g_warning("Max Connections Reached!");
        close(fd);
        return;
    }

    client = g_new0(struct client, 1);
    clients = g_list_prepend(clients, client);
    ++num_clients;

    client_init(client, fd);
    client->uid = uid;

    remote = sockaddr_to_string(sa, sa_length, NULL);
    g_log(G_LOG_DOMAIN, LOG_LEVEL_SECURE,
          "[%u] opened from %s", client->num, remote);
    g_free(remote);
}
Пример #12
0
int EPLIB_init()
{
    process_env_vars();

    init_sig_handlers();

    PMPI_Comm_rank(MPI_COMM_WORLD, &taskid);
    PMPI_Comm_size(MPI_COMM_WORLD, &num_tasks);

    set_local_uuid(taskid);

    allocator_init();

    if (max_ep == 0) return MPI_SUCCESS;

    /* Initialize client */
    client_init(taskid, num_tasks);

    /* Register MPI type and MPI Op before any other cqueue commands */
    cqueue_mpi_type_register();
    cqueue_mpi_op_register();

    /* Initialize communicator handles table */
    handle_init();

    /* Initialize window object table */
    window_init();

    /* Create server world and peer comm for MPI_COMM_WORLD */
    EPLIB_split_comm(MPI_COMM_WORLD, 0, taskid, MPI_COMM_WORLD);

    if (std_mpi_mode == STD_MPI_MODE_IMPLICIT)
        block_coll_request = malloc(max_ep*sizeof(MPI_Request));

    return MPI_SUCCESS;
}
Пример #13
0
int
main (int argc, char **argv)
{
	int retval;
	char * remotehost = DEFAULT_REMOTEHOST, * port = DEFAULT_PORT;
	
	while ((retval = getopt(argc, argv, "dn:hH:P:")) != -1) {
		switch (retval) {
			case 'H':
				remotehost = optarg;
				break;
			case 'P':
				port = optarg;
				break;
			case 'd':
				debug = 1;
				break;
			case 'h':
				usage(argv[0], EXIT_SUCCESS);
				break;
			default:
				break;
		}
	}
	
	if (argc > optind) /* || !hostname || !port)*/
		usage(argv[0], EXIT_FAILURE);
	
	signal(SIGPIPE, SIG_IGN);
	if(client_init(remotehost, port))
		printf_die(stderr, "could not connect to : %s:%s\n", EXIT_FAILURE, remotehost, port);

	srandom(time(NULL) + getpid());
	srand(time(NULL) + getpid());
	rmain ();
}
Пример #14
0
int init(void){
	device = alcOpenDevice(NULL);
	if(device) {
		context = alcCreateContext(device, NULL);
	}
	alcMakeContextCurrent(context);

	if (enet_initialize () != 0)
    {
        fprintf (stderr, "An error occurred while initializing ENet.\n");
        return EXIT_FAILURE;
    }
	atexit (enet_deinitialize);
	atexit (alCleanUp);

	atexit (clean_up);
	enet_client = enet_host_create (NULL /* create a client host */,
							   1 /* only allow 1 outgoing connection */,
							   0 /* allow up 4 channels to be used, 0 and 1 */,
							   0 /* 56K modem with 56 Kbps downstream bandwidth */,
							   0 /* 56K modem with 14 Kbps upstream bandwidth */);
   
	if (enet_client == NULL)
	{
		fprintf (stderr, 
                "An error occurred while trying to create an ENet client host.\n");
		exit (EXIT_FAILURE);
	}
	tclient = client_init(enet_client);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_POINT_SMOOTH);
	glEnable(GL_LINE_SMOOTH);
	
	
}
Пример #15
0
int main(int argc, const char** argv)
{
	struct client cli;

	// Set default hostname.
	strcpy(cli.host, DEFAULT_HOST);

	// Set def. port & time.
	cli.port = DEFAULT_PORT;
	cli.time = DEFAULT_TIME;

	// Process user arguments.
	process_args(&cli, argv, argc);

	printf("Connecting to %s:%d\n", cli.host, cli.port);
	if (client_init(&cli, cli.host, cli.port) == -1) {
		return EXIT_FAILURE;	
	}

	client_start(&cli);

	client_stop(&cli);
	return EXIT_SUCCESS;
}
Пример #16
0
int
main(int argc, char *argv[])
{
    serverstate_set_event_loop(uv_default_loop());

    config_init();
    listener_init();
    client_init();
    module_init();
    server_init();
    command_init();
    connection_init();

    process_commandline(argv, argc);

    config_load();
    listener_start_listeners();
    module_load_all_modules();
    connection_init_tls();

    uv_run(serverstate_get_event_loop(), UV_RUN_DEFAULT);

    return 0;
}
Пример #17
0
Файл: main.c Проект: dzruyk/ntx
int
main (int argc, char *argv[])
{
  ChannelCallbacks callbacks;

  g_type_init ();

  gui_init (&argc, &argv);

  client_init ();

  callbacks.input = input_cb;
  callbacks.disconnect = disconnect_cb;
  callbacks.error = error_cb;
  callbacks.user_data = NULL;

  chn_set_callbacks (&callbacks);

  if (g_strcmp0 (getenv ("ntx_channel"), "echo") == 0)
    chn_echo_init ();
  else if (g_strcmp0 (getenv ("ntx_channel"), "pty") == 0)
    chn_pty_init (argc > 1 ? argv[1] : "/bin/sh");
  else
    chn_telnet_init (argc > 1 ? argv[1] : "localhost", argc > 2 ? atoi (argv[2]) : 23);

  chn_connect ();

  gtk_main ();

  chn_disconnect ();
  chn_finalize ();

  client_deinit ();

  return 0;
}
Пример #18
0
int main(int argc, const char *argv[])
{
    #define OPEN 1
    #define CLOSE 0
    pthread_t show_data,wait_controller;
    int err,ret,alive;

    FD_ZERO(&wset);
    FD_ZERO(&rset);
    FD_SET(fd,&wset);
    FD_SET(fd,&rset);

    ss = fx_serial_start();
    fd = client_init(7000,argv[1]);
    select(fd+1,&rset,&wset,NULL,NULL);

    restart:
    /*set keepalive on fd*/
    alive = 1;
    if(setsockopt(fd,SOL_SOCKET,SO_KEEPALIVE,&alive,sizeof(alive)) != 0)
    {
        fprintf(stderr,"set socket option error\n");
        goto restart;
    }	

    socket_set_keepalive(fd);
    ret = connect_retry(fd,(struct sockaddr *)&clientaddr,sizeof(clientaddr));

    if(ret == -1)
    {
        printf("cannot connect to server\n");
        exit(1);
    }

    signal(SIGINT,free_space);

    err = pthread_create(&wait_controller,NULL,Control_controller,NULL);
    if(err != 0)
    {
        fprintf(stderr,"cannot create the thread\n");
        exit(1);
    }

    while(1)
    {
        header__init(&MS.mh);
        sensor_info__init(&MS.si);
        sensor_t__init(&MS.st);
        Get_data();
	//test();
        sleep(293); //sleep 5 mins
    } 
    //err = pthread_create(&show_data,NULL,Sensor_data,NULL);
//if(err != 0)
//	{
//	fprintf(stderr,"cannot create the thread\n");
//	exit(1);
//}


    //pthread_join(show_data, NULL);
    pthread_join(wait_controller, NULL);


    //while(1) getchar();
    return 0;
}
Пример #19
0
int main(int argc, char *argv[])
{
	/*初始化*/
	int sock_fd, n;
	struct sockaddr_in r_addr, srv_addr;
	socklen_t addr_len = sizeof(r_addr);

	CHK_RET_EXIT(sock_fd, client_init(argc, argv));

	char buf[MAX_PACK_SIZE] = {0};
	
	bzero(&srv_addr, sizeof(srv_addr));
	srv_addr.sin_family = AF_INET;
	inet_pton(AF_INET, DEFAULT_SERVER_IP, &srv_addr.sin_addr);


	/*拉去频道列表,选择频道号*/
	bzero(&r_addr, addr_len);

	while (1) {
		/*收包*/
		n = recvfrom(sock_fd, buf, sizeof(buf) - 1, 0, 
			(struct sockaddr *)&r_addr, &addr_len);
		if (n < 0) {
			if (errno == EINTR || errno == EAGAIN) {
				continue;
			}
			perror("recvfrom");
			break;
		}
		//DEBUG("buf:%s\n", buf);	
#if 1
		struct  chnlist_info_st *plist = (struct  chnlist_info_st *)buf;

		if (plist->chn_id == LIST_CHN_ID) {
			/*展示频道信息*/
			DEBUG("recv:chnlist_info package,(%d)\n", n);
			show_chn_list(plist, n);	
			break;
		}
#endif
	}
	
	/*选择频道号*/
	int chose_id = 2;
	#if 1
	printf("chose_id:");
	fflush(stdout);
	n = scanf("%d", &chose_id);
	if (n != 1) {
		perror("scanf");
		exit(1);
	}
	#endif
	printf("your chose chanel:%d\n", chose_id);
	
	int pipe_fd[2];

	pipe(pipe_fd);

	pid_t pid = fork();

	if (pid == 0) {
		close(pipe_fd[1]);
		dup2(pipe_fd[0], STDIN_FILENO);
		close(pipe_fd[0]);

		execlp("mpg123", "mpg123", "-q", "-", NULL);
		exit(0);
	}

	/*收到指定频道数据*/
	while (1) {
		/*收包*/
		n = recvfrom(sock_fd, buf, sizeof(buf) - 1, 0, 
			(struct sockaddr *)&r_addr, &addr_len);
		if (n < 0) {
			if (errno == EINTR || errno == EAGAIN) {
				continue;
			}
			perror("recvfrom");
			break;
		}
		
		struct mesg_info_st *pmesg = (struct mesg_info_st *)buf;
		/*判断是否为指定ID的消息*/
		if (pmesg->chn_id != chose_id) {
			continue;
		}
//		DEBUG("chn_id:%d\n", pmesg->chn_id);
		#if 0
		/*判断是否从服务器中发出的消息*/
		if (r_addr.sin_addr.s_addr != srv_addr.sin_addr.s_addr) {
			fprintf(stderr,"收到非发主机的组播信息,from '%s:%hu'\n", inet_ntoa(r_addr.sin_addr), ntohs(r_addr.sin_port));
			continue;
		}
		#endif
//		DEBUG("(%d)%s\n", n, (char *)(pmesg->data));
#if 1
		close(pipe_fd[0]);
		dup2(pipe_fd[1], STDOUT_FILENO);
		write(STDOUT_FILENO, pmesg->data, n - 1);		
		/*关闭*/
#endif
	}
	wait(NULL);

	return 0;
}
Пример #20
0
main(int argc, char *argv[ ])
{
       //*Lab 5 CODE
  char *tok;
  char cmdArgs[2][MAX] = {'\0'};
  char cwd[128];
  int cmdCount = 0;
       //LAB 5 CODE*
  char temp[MAX];

  int n;
  char line[MAX], ans[MAX];

       //*Lab 5 CODE
  getcwd(cwd, 128);   // get CWD pathname
       // Lab 5 CODE*
  printf("cwd: %s\n", cwd);

  if (argc < 3){
     printf("Usage : client ServerName ServerPort\n");
     exit(1);
  }

  client_init(argv);
  // sock <---> server
  printf("********  processing loop  *********\n");
  while (1){
    //printf("input two numbers to add : ");
    //bzero(line, MAX);                // zero out line[ ]

          // *LAB 5 CODE
    cmdCount = 0;
    strcpy(cmdArgs[0],"");
    strcpy(cmdArgs[1],"");
    
    printf("Input a command: ");    
          // LAB 5 CODE*

    fgets(line, MAX, stdin);         // get a line (end with \n) from stdin
    //printf("line: %s\n", line);
    line[strlen(line)-1] = 0;        // kill \n at end
    //printf("line[0]: %c\n", line[0]);
    //if(line[0]==0)                  // exit if NULL line
       //{exit(0);}

         // *Lab 5 CODE
    strcpy(temp, line);
    //printf("temp: %s\n", temp);
    
    tok = strtok(line, " ");
    cmdCount++;
    //printf("temp: %s\n", temp);
    //printf("cmdArgs[0] = %s\n", cmdArgs[0]);
    //printf("cmdCount: %d\n", cmdCount);
    while(tok != NULL)
    {
      strcpy(cmdArgs[cmdCount-1], tok);
      tok = strtok(NULL, " ");
      cmdCount++;
      //printf("cmdCount: %d\n", cmdCount);
    }
    //printf("cmdCount: %d\n", cmdCount);
    //printf("line: %s\n", line);
    //printf("cmdArgs[0] = %s\n", cmdArgs[0]);
    if(strcmp(cmdArgs[0], "lcat") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mycat(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "lpwd") == 0) 
    {
      mypwd(cwd);
    }
    else if (strcmp(cmdArgs[0], "lls") == 0) 
    {
      printf("args: %s\n", cmdArgs[1]);
      if(strcmp(cmdArgs[1],"") != 0) {myls(cmdArgs[1]);}
      else 
      {
        printf("cwd: %s\n", cwd);
        myls(cwd);
      }
    }
    else if (strcmp(cmdArgs[0], "lcd") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mycd(cmdArgs[1]);}
      else {mycd(cwd);}
    }
    else if (strcmp(cmdArgs[0], "lmkdir") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mymkdir(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "lrmdir") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {myrmdir(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "lrm") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {myrm(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "get") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mycp(cmdArgs[1], cwd);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "quit") == 0) 
    {
      printf("Goodbye!\n");
      return 0;
    }
    else // Not a local command, work with the sever
    {
      // Send command to server
      n = write(server_sock, temp, MAX);
      printf("client: wrote n=%d bytes; line=(%s)\n", n, temp);
      // Send command pathname
      //n = write(server_sock, cmdArgs[0], MAX);
      //printf("client: wrote n=%d bytes; line=(%s)\n", n, line);

      // Now read the Reply and Results in from the Server...

      //REPLY
      //n = read(server_sock, ans, MAX);
      //printf("client: read  n=%d bytes; echo=(%s)\n",n, ans);

      //RESULTS
      //n = read(server_sock, ans, MAX);
      //printf("client: read  n=%d bytes; echo=(%s)\n",n, ans);

      readData(ans);
    }
         // Lab 5 CODE*

    //
    // Send ENTIRE line to server
    //n = write(server_sock, line, MAX);
    //printf("client: wrote n=%d bytes; line=(%s)\n", n, line);

    // Read a line from sock and show it
    //n = read(server_sock, ans, MAX);
    //printf("client: read  n=%d bytes; echo=(%s)\n",n, ans);
  }
}
Пример #21
0
int		main()
{
  if (client_init(NULL, 0, function_read) == -1)
    return (-1);
  client_loop();
}
Пример #22
0
/*--------------------------------------------------------------------
 * ServiceStart
 *
 * each time starting the service, this is the entry point of the service.
 * Start the service, certainly it is on server-mode
 * 
 *-------------------------------------------------------------------- */
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv) {
    
    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;

    thread_Settings* ext_gSettings = new thread_Settings;

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
    // read settings from command-line parameters
    Settings_ParseCommandLine( dwArgc, lpszArgv, ext_gSettings );

    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;

    // if needed, redirect the output into a specified file
    if ( !isSTDOUT( ext_gSettings ) ) {
        redirect( ext_gSettings->mOutputFileName );
    }

    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_START_PENDING, // service state
                             NO_ERROR,              // exit code
                             3000) )                 // wait hint
        goto clean;
    
    // initialize client(s)
    if ( ext_gSettings->mThreadMode == kMode_Client ) {
        client_init( ext_gSettings );
    }

    // start up the reporter and client(s) or listener
    {
        thread_Settings *into = NULL;
#ifdef HAVE_THREAD
        Settings_Copy( ext_gSettings, &into );
        into->mThreadMode = kMode_Reporter;
        into->runNow = ext_gSettings;
#else
        into = ext_gSettings;
#endif
        thread_start( into );
    }
    
    // report the status to the service control manager.
    //
    if ( !ReportStatusToSCMgr(
                             SERVICE_RUNNING,       // service state
                             NO_ERROR,              // exit code
                             0) )                    // wait hint
        goto clean;

    clean:
    // wait for other (client, server) threads to complete
    thread_joinall();
}
Пример #23
0
/* -------------------------------------------------------------------
 * main()
 *      Entry point into Iperf
 *
 * sets up signal handlers
 * initialize global locks and conditions
 * parses settings from environment and command line
 * starts up server or client thread
 * waits for all threads to complete
 * ------------------------------------------------------------------- */
int main( int argc, char **argv ) {
#ifdef WIN32
    // Start winsock
    WSADATA wsaData;
    int rc;
#endif

    // Set SIGTERM and SIGINT to call our user interrupt function
    my_signal( SIGTERM, Sig_Interupt );
    my_signal( SIGINT,  Sig_Interupt );
#ifndef WIN32 // SIGALRM=14, _NSIG=3...
    my_signal( SIGALRM,  Sig_Interupt );
#endif

#ifndef WIN32
	// Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#endif

#ifdef WIN32 
    // Start winsock
    rc = WSAStartup( 0x202, &wsaData );
    WARN_errno( rc == SOCKET_ERROR, "WSAStartup" );
    if (rc == SOCKET_ERROR)
        return 0;

    // Tell windows we want to handle our own signals
    SetConsoleCtrlHandler( sig_dispatcher, true );
#endif

    // Initialize global mutexes and conditions
    Condition_Initialize ( &ReportCond );
    Condition_Initialize ( &ReportDoneCond );
    Mutex_Initialize( &groupCond );
    Mutex_Initialize( &clients_mutex );

    // Initialize the thread subsystem
    thread_init( );

    // Initialize the interrupt handling thread to 0
    sThread = thread_zeroid();

    // perform any cleanup when quitting Iperf
    atexit( cleanup );

    // Allocate the "global" settings
    thread_Settings* ext_gSettings = new thread_Settings;

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
    // read settings from command-line parameters
    Settings_ParseCommandLine( argc, argv, ext_gSettings );

    // Check for either having specified client or server
    if ( ext_gSettings->mThreadMode == kMode_Client
         || ext_gSettings->mThreadMode == kMode_Listener ) {
#ifdef WIN32
        // Start the server as a daemon
        // Daemon mode for non-windows in handled
        // in the listener_spawn function
        if ( isDaemon( ext_gSettings ) ) {
            CmdInstallService(argc, argv);
            return 0;
        }

        // Remove the Windows service if requested
        if ( isRemoveService( ext_gSettings ) ) {
            // remove the service
            if ( CmdRemoveService() ) {
                fprintf(stderr, "IPerf Service is removed.\n");

                return 0;
            }
        }
#endif
        // initialize client(s)
        if ( ext_gSettings->mThreadMode == kMode_Client ) {
            client_init( ext_gSettings );
        }

#ifdef HAVE_THREAD
        // start up the reporter and client(s) or listener
        {
            thread_Settings *into = NULL;
            // Create the settings structure for the reporter thread
            Settings_Copy( ext_gSettings, &into );
            into->mThreadMode = kMode_Reporter;

            // Have the reporter launch the client or listener
            into->runNow = ext_gSettings;

            // Start all the threads that are ready to go
            thread_start( into );
        }
#else
        // No need to make a reporter thread because we don't have threads
        thread_start( ext_gSettings );
#endif
    } else {
        // neither server nor client mode was specified
        // print usage and exit

#ifdef WIN32
        // In Win32 we also attempt to start a previously defined service
        // Starting in 2.0 to restart a previously defined service
        // you must call iperf with "iperf -D" or using the environment variable
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
            { NULL, NULL}
        };

        // Only attempt to start the service if "-D" was specified
        if ( !isDaemon(ext_gSettings) ||
             // starting the service by SCM, there is no arguments will be passed in.
             // the arguments will pass into Service_Main entry.
             !StartServiceCtrlDispatcher(dispatchTable) )
            // If the service failed to start then print usage
#endif
        fprintf( stderr, usage_short, argv[0], argv[0] );

        return 0;
    }

    // wait for other (client, server) threads to complete
    thread_joinall();

    // all done!
    return 0;
} // end main
Пример #24
0
int main(void)
{
    log_init();

    leds_init();
    timer_init();
    counter_init();
    buttons_init();

    ble_stack_init();

    gap_params_init();
    conn_params_init();
    gatt_init();
    advertising_data_set();

    server_init();
    client_init();

    // Default ATT MTU size and connection interval are set at compile time.
    gatt_mtu_set(m_test_params.att_mtu);
    // Data Length Extension (DLE) is on by default.
    // Enable the Connection Event Length Extension.
    conn_evt_len_ext_set(m_test_params.conn_evt_len_ext_enabled);

    NRF_LOG_INFO("ATT MTU example started.\r\n");
    NRF_LOG_INFO("Press button 3 on the board connected to the PC.\r\n");
    NRF_LOG_INFO("Press button 4 on other board.\r\n");
    NRF_LOG_FLUSH();

    board_role_select();

    if (m_board_role == BOARD_TESTER)
    {
        m_print_menu = true;
    }
    if (m_board_role == BOARD_DUMMY)
    {
        advertising_start();
        scan_start();
    }

    // Enter main loop.
    NRF_LOG_DEBUG("Entering main loop.\r\n");
    for (;;)
    {
        if (m_print_menu)
        {
            menu_print();
        }

        if (is_test_ready())
        {
            m_run_test = true;
            test_run();
        }

        if (!NRF_LOG_PROCESS())
        {
            wait_for_event();
        }

    }
}
Пример #25
0
static struct ropa_client *
client_query (uint32_t host, uint16_t port)
{
    struct ropa_client *c, *c_new;
    int ret;

    c = client_query_notalkback(host, port);
    if (c == NULL) {
	interfaceAddr remote;
	struct rx_connection *conn = NULL;

	c = obtain_client();
	assert (c->state == ROPAC_FREE && c->li == NULL);
	c->state = ROPAC_LOOKUP_U;
	c->flags |= ROPAF_LOOKUP;
	client_init (c, host, port, NULL, NULL);
	
	conn = rx_NewConnection (host, port, CM_SERVICE_ID,
				 rxnull_NewClientSecurityObject(),
				 0);
	if (conn == NULL) {
	    free(c);
	    return NULL;
	}
    retry:
	switch (c->state) {
	case ROPAC_DEAD:
	    c->li = listaddtail (lru_clients, c);
	    ret = ENETDOWN;
	    break;
	case ROPAC_LOOKUP_U:
	    ret = RXAFSCB_WhoAreYou (conn, &remote);
	    if (ret == RXGEN_OPCODE) {
		c->state = ROPAC_LOOKUP;
		goto retry;
	    } else if (ret == RX_CALL_DEAD) {
		c->state = ROPAC_DEAD;
		goto retry;
	    } else {
		struct ropa_client ckey;
		
		ckey.uuid = remote.uuid;
		c_new = hashtabsearch (ht_clients_uuid, &ckey);
		if (c_new == NULL) {
		    client_init (c, host, port, &remote.uuid, NULL);
		    ret = RXAFSCB_InitCallBackState3(conn, &server_uuid);
		} else {
		    client_update_interfaces (c_new, host, port, &remote);
		    disconnect_client (c);
		    c = c_new;
		    listdel(lru_clients, c->li);
		    c->li = NULL;
		}
	    }
	    break;
	case ROPAC_LOOKUP: {
	    afsUUID uuid;
	    ret = RXAFSCB_InitCallBackState(conn);
	    if (ret == RX_CALL_DEAD) {
		c->state = ROPAC_DEAD;
		goto retry;
	    }
	    uuid_init_simple (&uuid, host);
	    client_init (c, host, port, &uuid, NULL);
	    break;
	}
	default:
	     exit(-1);
	}
	
	rx_DestroyConnection (conn);
	
	if ((c->flags & ROPAF_WAITING) != 0)
	    LWP_NoYieldSignal (c);
	c->flags &= ~(ROPAF_LOOKUP|ROPAF_WAITING);

	if (ret) {
	    assert (c->li != NULL);
	    return NULL;
	}

	assert (c->li == NULL);
	c->li = listaddhead (lru_clients, c);

    } else { /* c != NULL */
	if ((c->flags & ROPAF_LOOKUP) != 0) {
	    c->flags |= ROPAF_WAITING;
	    LWP_WaitProcess (c);
	}
	assert (c->li != NULL);
    }

    return c;
}
Пример #26
0
int client_main(int argc, char **argv) {
	if (argc < 4) {
		fprintf(stderr, "Usage: wetalk -c <ip> <uid> <password>\n"
						"Or   : wetalk -r <ip> <username> <password>\n");
		return wetalk_usage("wetalk");
	}

	int uid = 0;
	char *ipaddr = argv[1];
	char *password = argv[3];

	if (strlen(password) >= PASSWORD_MAX) {
		fprintf(stderr, "错误的密码长度\n");
		return 1;
	}

	if (!client_init(argv[1], on_msg_recv)) {
		wetalk_error("初始化客户端失败\n");
	}

	if (!strcmp(argv[0], "-r")) {
		uid = client_register(argv[2], password);
		if (uid > 0) {
			fprintf(stderr, "注册成功,您的 uid 为: %d\n这是以后登陆时必要的信息,请牢记\n回车键以继续", uid);
			getchar();
		} else {
			fprintf(stderr, "注册失败\n");
			return 1;
		}
	} else {
		uid = atoi(argv[2]);
		if (uid <= 0) {
			fprintf(stderr, "错误的uid\n");
			return 1;
		}
	}

	if (!client_login(uid, password)) {
		wetalk_error("登陆失败\n");
	}

	client_main_run = true;
	int r;

	setlocale(LC_ALL, "");
	initscr();
	getmaxyx(stdscr, window_y, window_x);

	char input[BUFFER_SIZE] = {0};
	while(client_main_run) {
		draw_editarea();

		getnstr(input, BUFFER_SIZE - 1);
		r = strlen(input);
		input[r] = '\0';

		if (r > 0) {
			client_send(input);
		}
	}

	endwin();
	return 0;
}
Пример #27
0
int main(int argc, char *argv[])
{
	int listenfd;
	int res = 0;
	int lfd;
	struct flock lock;
	char pids[10];

	parse_opts(argc, argv);

	argc -= optind;
	argv += optind;

	if (!foreground) {
		verbose += LL_WARNING;
		log_enable_syslog();
	} else {
		verbose += LL_NOTICE;
	}

	/* set log level to specified verbosity */
	log_level = verbose;

	usbmuxd_log(LL_NOTICE, "usbmuxd v%s starting up", PACKAGE_VERSION);
	should_exit = 0;
	should_discover = 0;

	set_signal_handlers();
	signal(SIGPIPE, SIG_IGN);

	res = lfd = open(lockfile, O_WRONLY|O_CREAT, 0644);
	if(res == -1) {
		usbmuxd_log(LL_FATAL, "Could not open lockfile");
		goto terminate;
	}
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_pid = 0;
	fcntl(lfd, F_GETLK, &lock);
	close(lfd);
	if (lock.l_type != F_UNLCK) {
		if (opt_exit) {
			if (lock.l_pid && !kill(lock.l_pid, 0)) {
				usbmuxd_log(LL_NOTICE, "Sending signal %d to instance with pid %d", exit_signal, lock.l_pid);
				res = 0;
				if (kill(lock.l_pid, exit_signal) < 0) {
					usbmuxd_log(LL_FATAL, "Could not deliver signal %d to pid %d", exit_signal, lock.l_pid);
					res = -1;
				}
				goto terminate;
			} else {
				usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
				res = -1;
				goto terminate;
			}
		} else {
			if (!opt_disable_hotplug) {
				usbmuxd_log(LL_ERROR, "Another instance is already running (pid %d). exiting.", lock.l_pid);
				res = -1;
			} else {
				usbmuxd_log(LL_NOTICE, "Another instance is already running (pid %d). Telling it to check for devices.", lock.l_pid);
				if (lock.l_pid && !kill(lock.l_pid, 0)) {
					usbmuxd_log(LL_NOTICE, "Sending signal SIGUSR2 to instance with pid %d", lock.l_pid);
					res = 0;
					if (kill(lock.l_pid, SIGUSR2) < 0) {
						usbmuxd_log(LL_FATAL, "Could not deliver SIGUSR2 to pid %d", lock.l_pid);
						res = -1;
					}
				} else {
					usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
					res = -1;
				}
			}
			goto terminate;
		}
	}
	unlink(lockfile);

	if (opt_exit) {
		usbmuxd_log(LL_NOTICE, "No running instance found, none killed. Exiting.");
		goto terminate;
	}

	if (!foreground) {
		if ((res = daemonize()) < 0) {
			fprintf(stderr, "usbmuxd: FATAL: Could not daemonize!\n");
			usbmuxd_log(LL_FATAL, "Could not daemonize!");
			goto terminate;
		}
	}

	// now open the lockfile and place the lock
	res = lfd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644);
	if(res < 0) {
		usbmuxd_log(LL_FATAL, "Could not open lockfile");
		goto terminate;
	}
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	if ((res = fcntl(lfd, F_SETLK, &lock)) < 0) {
		usbmuxd_log(LL_FATAL, "Lockfile locking failed!");
		goto terminate;
	}
	sprintf(pids, "%d", getpid());
	if ((size_t)(res = write(lfd, pids, strlen(pids))) != strlen(pids)) {
		usbmuxd_log(LL_FATAL, "Could not write pidfile!");
		if(res >= 0)
			res = -2;
		goto terminate;
	}

	// set number of file descriptors to higher value
	struct rlimit rlim;
	getrlimit(RLIMIT_NOFILE, &rlim);
	rlim.rlim_max = 65536;
	setrlimit(RLIMIT_NOFILE, (const struct rlimit*)&rlim);

	usbmuxd_log(LL_INFO, "Creating socket");
	res = listenfd = create_socket();
	if(listenfd < 0)
		goto terminate;

#ifdef HAVE_LIBIMOBILEDEVICE
	const char* userprefdir = config_get_config_dir();
	struct stat fst;
	memset(&fst, '\0', sizeof(struct stat));
	if (stat(userprefdir, &fst) < 0) {
		if (mkdir(userprefdir, 0775) < 0) {
			usbmuxd_log(LL_FATAL, "Failed to create required directory '%s': %s", userprefdir, strerror(errno));
			res = -1;
			goto terminate;
		}
		if (stat(userprefdir, &fst) < 0) {
			usbmuxd_log(LL_FATAL, "stat() failed after creating directory '%s': %s", userprefdir, strerror(errno));
			res = -1;
			goto terminate;
		}
	}

	// make sure permission bits are set correctly
	if (fst.st_mode != 02775) {
		if (chmod(userprefdir, 02775) < 0) {
			usbmuxd_log(LL_WARNING, "chmod(%s, 02775) failed: %s", userprefdir, strerror(errno));
		}
	}
#endif

	// drop elevated privileges
	if (drop_privileges && (getuid() == 0 || geteuid() == 0)) {
		struct passwd *pw;
		if (!drop_user) {
			usbmuxd_log(LL_FATAL, "No user to drop privileges to?");
			res = -1;
			goto terminate;
		}
		pw = getpwnam(drop_user);
		if (!pw) {
			usbmuxd_log(LL_FATAL, "Dropping privileges failed, check if user '%s' exists!", drop_user);
			res = -1;
			goto terminate;
		}
		if (pw->pw_uid == 0) {
			usbmuxd_log(LL_INFO, "Not dropping privileges to root");
		} else {
#ifdef HAVE_LIBIMOBILEDEVICE
			/* make sure the non-privileged user has proper access to the config directory */
			if ((fst.st_uid != pw->pw_uid) || (fst.st_gid != pw->pw_gid)) {
				if (chown(userprefdir, pw->pw_uid, pw->pw_gid) < 0) {
					usbmuxd_log(LL_WARNING, "chown(%s, %d, %d) failed: %s", userprefdir, pw->pw_uid, pw->pw_gid, strerror(errno));
				}
			}
#endif

			if ((res = initgroups(drop_user, pw->pw_gid)) < 0) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set supplementary groups)");
				goto terminate;
			}
			if ((res = setgid(pw->pw_gid)) < 0) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set group ID to %d)", pw->pw_gid);
				goto terminate;
			}
			if ((res = setuid(pw->pw_uid)) < 0) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set user ID to %d)", pw->pw_uid);
				goto terminate;
			}

			// security check
			if (setuid(0) != -1) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
				res = -1;
				goto terminate;
			}
			if (getuid() != pw->pw_uid || getgid() != pw->pw_gid) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
				res = -1;
				goto terminate;
			}
			usbmuxd_log(LL_NOTICE, "Successfully dropped privileges to '%s'", drop_user);
		}
	}

	client_init();
	device_init();
	usbmuxd_log(LL_INFO, "Initializing USB");
	if((res = usb_init()) < 0)
		goto terminate;

	usbmuxd_log(LL_INFO, "%d device%s detected", res, (res==1)?"":"s");

	usbmuxd_log(LL_NOTICE, "Initialization complete");

	if (report_to_parent)
		if((res = notify_parent(0)) < 0)
			goto terminate;

	if(opt_disable_hotplug) {
		usbmuxd_log(LL_NOTICE, "Automatic device discovery on hotplug disabled.");
		usb_autodiscover(0); // discovery to be triggered by new instance
	}
	if (opt_enable_exit) {
		usbmuxd_log(LL_NOTICE, "Enabled exit on SIGUSR1 if no devices are attached. Start a new instance with \"--exit\" to trigger.");
	}

	res = main_loop(listenfd);
	if(res < 0)
		usbmuxd_log(LL_FATAL, "main_loop failed");

	usbmuxd_log(LL_NOTICE, "usbmuxd shutting down");
	device_kill_connections();
	usb_shutdown();
	device_shutdown();
	client_shutdown();
	usbmuxd_log(LL_NOTICE, "Shutdown complete");

terminate:
	log_disable_syslog();

	if (res < 0)
		res = -res;
	else
		res = 0;
	if (report_to_parent)
		notify_parent(res);

	return res;
}
Пример #28
0
int
main(int argc, char **argv)
{
	struct client_ctx	 cctx;
	struct msg_command_data	 cmddata;
	struct buffer		*b;
	struct cmd_list		*cmdlist;
 	struct cmd		*cmd;
	struct pollfd	 	 pfd;
	struct hdr	 	 hdr;
	const char		*shell;
	struct passwd		*pw;
	char			*path, *label, *cause, *home, *pass = NULL;
	char			 cwd[MAXPATHLEN];
	int	 		 retcode, opt, flags, unlock, start_server;

	unlock = flags = 0;
	label = path = NULL;
        while ((opt = getopt(argc, argv, "28df:L:qS:uUVv")) != -1) {
                switch (opt) {
		case '2':
			flags |= IDENTIFY_256COLOURS;
			flags &= ~IDENTIFY_88COLOURS;
			break;
		case '8':
			flags |= IDENTIFY_88COLOURS;
			flags &= ~IDENTIFY_256COLOURS;
			break;
		case 'f':
			cfg_file = xstrdup(optarg);
			break;
		case 'L':
			if (path != NULL) {
				log_warnx("-L and -S cannot be used together");
				exit(1);
			}
			if (label != NULL)
				xfree(label);
			label = xstrdup(optarg);
			break;
		case 'S':
			if (label != NULL) {
				log_warnx("-L and -S cannot be used together");
				exit(1);
			}
			if (path != NULL)
				xfree(path);
			path = xstrdup(optarg);
			break;
		case 'q':
			be_quiet = 1;
			break;
		case 'u':
			flags |= IDENTIFY_UTF8;
			break;
		case 'U':
			unlock = 1;
			break;
		case 'd':
			flags |= IDENTIFY_HASDEFAULTS;
			break;
		case 'v':
			debug_level++;
			break;
		case 'V':
			printf("%s " BUILD "\n", __progname);
			exit(0);
                default:
			usage();
                }
        }
	argc -= optind;
	argv += optind;

	log_open_tty(debug_level);
	siginit();

	options_init(&global_options, NULL);
	options_set_number(&global_options, "bell-action", BELL_ANY);
	options_set_number(&global_options, "buffer-limit", 9);
	options_set_number(&global_options, "display-time", 750);
	options_set_number(&global_options, "history-limit", 2000);
	options_set_number(&global_options, "message-bg", 3);
	options_set_number(&global_options, "message-fg", 0);
	options_set_number(&global_options, "message-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_options, "prefix", META);
	options_set_number(&global_options, "repeat-time", 500);
	options_set_number(&global_options, "set-titles", 1);
	options_set_number(&global_options, "lock-after-time", 0);
	options_set_number(&global_options, "set-remain-on-exit", 0);
	options_set_number(&global_options, "status", 1);
	options_set_number(&global_options, "status-bg", 2);
	options_set_number(&global_options, "status-fg", 0);
	options_set_number(&global_options, "status-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_options, "status-interval", 15);
	options_set_number(&global_options, "status-left-length", 10);
	options_set_number(&global_options, "status-right-length", 40);
	options_set_string(&global_options, "status-left", "[#S]");
	options_set_string(
	    &global_options, "status-right", "\"#24T\" %%H:%%M %%d-%%b-%%y");
	options_set_number(&global_options, "status-keys", MODEKEY_EMACS);
	options_init(&global_window_options, NULL);
	options_set_number(&global_window_options, "aggressive-resize", 0);
	options_set_number(&global_window_options, "clock-mode-colour", 4);
	options_set_number(&global_window_options, "clock-mode-style", 1);
	options_set_number(&global_window_options, "force-height", 0);
	options_set_number(&global_window_options, "force-width", 0);
	options_set_number(&global_window_options, "automatic-rename", 1);
	options_set_number(&global_window_options, "mode-bg", 3);
	options_set_number(&global_window_options, "mode-fg", 0);
	options_set_number(
	    &global_window_options, "mode-attr", GRID_ATTR_REVERSE);
	options_set_number(&global_window_options, "mode-keys", MODEKEY_EMACS);
	options_set_number(&global_window_options, "monitor-activity", 0);
	options_set_number(&global_window_options, "utf8", 0);
	options_set_number(&global_window_options, "xterm-keys", 0);
 	options_set_number(&global_window_options, "remain-on-exit", 0);
	options_set_number(&global_window_options, "window-status-bg", 8);
	options_set_number(&global_window_options, "window-status-fg", 8);
	options_set_number(&global_window_options, "window-status-attr", 0);

	if (cfg_file == NULL) {
		home = getenv("HOME");
		if (home == NULL || *home == '\0') {
			pw = getpwuid(getuid());
			if (pw != NULL)
				home = pw->pw_dir;
			endpwent();
		}
		xasprintf(&cfg_file, "%s/%s", home, DEFAULT_CFG);
		if (access(cfg_file, R_OK) != 0) {
			xfree(cfg_file);
			cfg_file = NULL;
		}
	} else {
		if (access(cfg_file, R_OK) != 0) {
			log_warn("%s", cfg_file);
			exit(1);
		}
	}

	if (label == NULL)
		label = xstrdup("default");
	if (path == NULL && (path = makesockpath(label)) == NULL) {
		log_warn("can't create socket");
		exit(1);
	}
	xfree(label);

	shell = getenv("SHELL");
	if (shell == NULL || *shell == '\0') {
		pw = getpwuid(getuid());
		if (pw != NULL)
			shell = pw->pw_shell;
		endpwent();
		if (shell == NULL || *shell == '\0')
			shell = _PATH_BSHELL;
	}
	options_set_string(
	    &global_options, "default-command", "exec %s", shell);
	

	if (getcwd(cwd, sizeof cwd) == NULL) {
		log_warn("getcwd");
		exit(1);
	}
	options_set_string(&global_options, "default-path", "%s", cwd);

	if (unlock) {
		if (argc != 0) {
			log_warnx("can't specify a command when unlocking");
			exit(1);
		}
		cmdlist = NULL;
		if ((pass = getpass("Password: "******"%s", cause);
				exit(1);
			}
		}
		start_server = 0;
		TAILQ_FOREACH(cmd, cmdlist, qentry) {
			if (cmd->entry->flags & CMD_STARTSERVER) {
				start_server = 1;
				break;
			}
		}
	}
	
 	memset(&cctx, 0, sizeof cctx);
	if (client_init(path, &cctx, start_server, flags) != 0)
		exit(1);
	xfree(path);

	b = buffer_create(BUFSIZ);
	if (unlock) {
		cmd_send_string(b, pass);
		client_write_server(
		    &cctx, MSG_UNLOCK, BUFFER_OUT(b), BUFFER_USED(b));
	} else {
		cmd_list_send(cmdlist, b);
		cmd_list_free(cmdlist);
		client_fill_session(&cmddata);
		client_write_server2(&cctx, MSG_COMMAND,
		    &cmddata, sizeof cmddata, BUFFER_OUT(b), BUFFER_USED(b));
	}
	buffer_destroy(b);

	retcode = 0;
	for (;;) {
		pfd.fd = cctx.srv_fd;
		pfd.events = POLLIN;
		if (BUFFER_USED(cctx.srv_out) > 0)
			pfd.events |= POLLOUT;

		if (poll(&pfd, 1, INFTIM) == -1) {
			if (errno == EAGAIN || errno == EINTR)
				continue;
			fatal("poll failed");
		}

		if (buffer_poll(&pfd, cctx.srv_in, cctx.srv_out) != 0)
			goto out;

	restart:
		if (BUFFER_USED(cctx.srv_in) < sizeof hdr)
			continue;
		memcpy(&hdr, BUFFER_OUT(cctx.srv_in), sizeof hdr);
		if (BUFFER_USED(cctx.srv_in) < (sizeof hdr) + hdr.size)
			continue;
		buffer_remove(cctx.srv_in, sizeof hdr);

		switch (hdr.type) {
		case MSG_EXIT:
		case MSG_SHUTDOWN:
			goto out;
		case MSG_ERROR:
			retcode = 1;
			/* FALLTHROUGH */
		case MSG_PRINT:
			if (hdr.size > INT_MAX - 1)
				fatalx("bad MSG_PRINT size");
			log_info("%.*s",
			    (int) hdr.size, BUFFER_OUT(cctx.srv_in));
			if (hdr.size != 0)
				buffer_remove(cctx.srv_in, hdr.size);
			goto restart;
		case MSG_READY:
			retcode = client_main(&cctx);
			goto out;
		default:
			fatalx("unexpected command");
		}
	}

out:
	options_free(&global_options);
	options_free(&global_window_options);

	close(cctx.srv_fd);
	buffer_destroy(cctx.srv_in);
	buffer_destroy(cctx.srv_out);

#ifdef DEBUG
	xmalloc_report(getpid(), "client");
#endif
	return (retcode);
}
Пример #29
0
int main(int argc, char **argv)
{
	//initial the client
	if (argc>1)
    port = atoi(argv[1]);
    int info_fd = client_init(SERVER_IP);

    char filename[FILENAME_MAXLEN] = {0};
    printf("BLOCKSIZE=  %d\n",BLOCKSIZE);
    printf("Input filename : ");
    scanf("%s",filename);
    int fd=0;
    if((fd = open(filename, O_RDWR)) == -1 )
	{
		printf("open erro !\n");
		exit(-1);
	}	
	
	/*Timer*/
    printf("Timer start!\n");
	time_t t_start, t_end;
	t_start=time(NULL);

	//send file info
    struct stat filestat;
	fstat(fd ,&filestat);
	int last_bs=0;
    struct fileinfo finfo;
	send_fileinfo(info_fd, filename, &filestat, &finfo, &last_bs);

	//
    char id_buf[INT_SIZE] = {0};
    int n=0;
    for(n=0; n<INT_SIZE; n++){
        read(info_fd, &id_buf[n], 1);
    }
    int freeid = *((int *)id_buf);
    printf("freeid = %d\n", freeid);

	//map .
    mbegin = (char *)mmap(NULL, filestat.st_size, PROT_WRITE|PROT_READ, MAP_SHARED, fd , 0);
    close(fd);

    //add task to the list 
    int j=0, num=finfo.count, offset=0;
	pthread_t pid[num];
	memset(pid, 0, num*sizeof(pthread_t));
	int head_len = sizeof(struct head);
	// file can be slipt into blocks
    if(last_bs == 0){
        for(j=0; j<num; j++){
            struct head * p_fhead = new_fb_head(filename, freeid, &offset);
			if (pthread_create(&pid[j], NULL, send_filedata, (void *)p_fhead) != 0){
            printf("%s:pthread_create failed, errno:%d, error:%s\n", __FUNCTION__, errno, strerror(errno));
            exit(-1);
        	}
        }
    }
	//file cannot slipt into blocks
    else{
        for(j=0; j<num-1; j++){
            struct head * p_fhead = new_fb_head(filename, freeid, &offset);
			if (pthread_create(&pid[j], NULL, send_filedata, (void *)p_fhead) != 0){
            	printf("%s:pthread_create failed, errno:%d, error:%s\n", __FUNCTION__, errno, strerror(errno));
            	exit(-1);
        	}
        }
        //the last block
        struct head * p_fhead = (struct head *)malloc(head_len);
		bzero(p_fhead, head_len);
        strcpy(p_fhead->filename, filename);
        p_fhead->id = freeid;
        p_fhead->offset = offset;
        p_fhead->bs = last_bs;

		if (pthread_create(&pid[j], NULL, send_filedata, (void *)p_fhead) != 0){
            printf("%s:pthread_create failed, errno:%d, error:%s\n", __FUNCTION__, errno, strerror(errno));
            exit(-1);
        }
    }

	//join all the pthread
    for (j = 0; j < num; ++j) {
        pthread_join(pid[j], NULL);
    }

	//calculate the time for send file 
	t_end=time(NULL);
	printf("Master prosess exit!\n");
	printf("TIME:%.0fs\n",difftime(t_end,t_start));

    return 0;
}
Пример #30
0
uint8_t client_do_prompt() {
        char cmd[17];
        //scanf("%16s",cmd);
        scan_key(cmd,17);
        if (strcmp(cmd,"init")==0) {
                        client_init();
			print_ok_nl();
                        return 1;
        }
        if (strcmp(cmd,"loop")==0) {
                        uint16_t count = scan_uint16();

                        if (count == 0) {
                                print(PSTR("client loop...."));
                                while(!uart_read_ready()) {
                                        client_loop();
                                }
                                print(PSTR("   end\n\r"));
                        } else {
                                while(count--) {
                                        print_char('.');
                                        client_loop();
                                }
                        }

                        return 1;
        }
	if (strcmp(cmd,"autotune")==0) {
			client_autotune();
			return 1;
	}

	if (strcmp(cmd,"channel")==0) {
			uint8_t c = scan_uint8();
			client_select_channel(c);
			return 1;
	}

	if (strcmp(cmd,"check")==0) {
			uint8_t c = scan_uint8();
			if (client_check_for_server(c)) {
				print(PSTR("ok\r\n"));
			} else {
				print(PSTR("fail\r\n"));
			}
			return 1;
	}

	if (strcmp(cmd,"pad")==0) {
		uint8_t l = client_read_pad();
		print_hb(0,l);
		while(!uart_read_ready()) {
			uint8_t d = client_read_pad();		
			if (d!=l) {
				l = d;
				print_hb(PSTR(" "), d);
			}
		}
		
		return 1;
	}

	if (strcmp(cmd,"reset_stats")==0) {
		stats_ok = 0;
		stats_inv_seq = 0;
		stats_bad_crc = 0;
		stats_timeout = 0;
		print(PSTR("stat reset ok"));
		return 1;
	}

	if (strcmp(cmd,"stats")==0) {
		print_dw(PSTR("ok: "), stats_ok);
		print_dw(PSTR(" inv_seq: "), stats_inv_seq);
		print_dw(PSTR(" bad_crc: "), stats_bad_crc);
		print_dw(PSTR(" timeout: "), stats_timeout);
		print_nl();
		return 1;
	}



        return 1;

}