Exemple #1
0
int main(int argc,char *argv[])
{
    struct addrinfo *ailist,*aip;
    struct addrinfo hint;
    int             sockfd,err;

    hint.ai_flags       = AI_PASSIVE;
    hint.ai_family      = 0;
    hint.ai_socktype    = SOCK_STREAM;
    hint.ai_protocol    = 0;
    hint.ai_addrlen     = 0;
    hint.ai_canonname   = NULL;
    hint.ai_addr        = NULL;
    hint.ai_next        = NULL;

    if( (err = getaddrinfo(NULL,"www",&hint,&ailist)) != 0 ){
        printf("uuwebserver getaddrinfo error: %s\n",gai_strerror(errno));
        exit(EXIT_ERROR);
    }

    for(aip = ailist;aip != NULL;aip=aip->ai_next){
        if((sockfd = initserver(SOCK_STREAM,aip->ai_addr,aip->ai_addrlen,QLEN)) >= 0){
            serve(sockfd);
            exit(EXIT_NORMAL);
        }

    }
    exit(EXIT_ERROR);
}
/**
 * tcp_server - 启动tcp服务器
 * @host: 服务器IP地址或者服务器主机名
 * @port: 服务器端口
 * 成功返回监听套接字
 */
 int tcp_server(const char *host, unsigned short port)
 {
     int listenfd;

 	struct sockaddr_in servaddr;
 	bzero(&servaddr, sizeof(servaddr));
 	servaddr.sin_family = AF_INET;
 	if (host != NULL)
 	{
 		if (inet_aton(host, &servaddr.sin_addr) == 0)
 		{
 			struct hostent *hp;
 			hp = gethostbyname(host);
 			if (hp == NULL)
 				ERR_EXIT("gethostbyname");

 			servaddr.sin_addr = *(struct in_addr*)hp->h_addr;
 		}
 	}
 	else
        /* 将主机字节序转换为网络字节序 */
 		servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

 	servaddr.sin_port = htons(port);

    if( (listenfd = initserver(SOCK_STREAM, (struct sockaddr *)&servaddr, sizeof(servaddr), SOMAXCONN)) < 0)
        ERR_EXIT("tcp_server");

 	return listenfd;
 }
Exemple #3
0
int main(int argc, char *argv[])
{
	struct addrinfo *ailist, *aip;
	struct addrinfo hint;
	int sockfd, err, n;
	char *host;

	if (argc != 1)
		err_quit("usage: rpsd");
	if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
		n = HOST_NAME_MAX; /* best guess */
	host = Malloc(n);
	if (gethostname(host, n) < 0)
		err_sys("gethostname error");
	daemonize("rpsd");
	bzero(&hint, sizeof(hint));
	hint.ai_flags = AI_CANONNAME;
	hint.ai_socktype = SOCK_DGRAM;
	hint.ai_canonname = NULL;
	hint.ai_addr = NULL;
	hint.ai_next = NULL;
	if ((err = getaddrinfo(host, "rpsd", &hint, &ailist)) != 0) {
		syslog(LOG_ERR, "rpsd: getaddrinfo error: %s",
		       strerror(errno));		
	}
	for (aip = ailist; aip != NULL; aip = aip->ai_next) {
		if ((sockfd = initserver(SOCK_DGRAM, aip->ai_addr,
					 aip->ai_addrlen, 0)) >= 0) {
			serve(sockfd);
			exit(0);
		}
	}
	exit(1);
}
Exemple #4
0
int main(int argc, char* argv[])
{
	struct addrinfo *ailist, *aip;
	struct addrinfo hint;
	int sockfd, err, n;
	char *host;

	if(argc != 1)
	{
		err_quit("usage: tuptimed");
	}

#ifdef _SC_HOST_NAME_MAX
	n = sysconf(_SC_HOST_NAME_MAX);
	if(n<0)
#endif
	  n = HOST_NAME_MAX;

	host = (char*)malloc(n);

	if(host == NULL)
	{
		err_sys("malloc error");
	}

	if(gethostname(host, n) < 0)
	{
		err_sys("gethostname error");
	}

	//daemonize("ruptimed");

	hint.ai_flags = AI_CANONNAME;
	hint.ai_family = 0;
	hint.ai_socktype = SOCK_STREAM;
	hint.ai_protocol = 0;
	hint.ai_addrlen = 0;
	hint.ai_canonname = NULL;
	hint.ai_addr = NULL;
	hint.ai_next = NULL;

	if((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0)
	{
		syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s", gai_strerror(err));
		exit(1);
	}

	for(aip=ailist; aip!=NULL; aip=aip->ai_next)
	{
		if((sockfd = initserver(SOCK_STREAM, aip->ai_addr, aip->ai_addrlen, QLEN)) >= 0)
		{
			serve(sockfd);
			exit(0);
		}
	}

	exit(1);
}
Exemple #5
0
int main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int             sockfd, err,n;
    char            *host;

    if (argc != 1)
    {
        printf("usage: ruptimed");
        exit(EXIT_FAILURE);
    }

    if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
    {
        n = HOST_NAME_MAX;
    }

    if ((host = malloc(n)) == NULL)
    {
        printf("malloc error");
        exit(EXIT_FAILURE);
    }

    if (gethostname(host, n) < 0)
    {
        printf("gethostname error");
        exit(EXIT_FAILURE);
    }

    daemonize("ruptimed");
    memset(&hint, 0, sizeof(hint));
    hint.ai_flags = AI_CANONNAME;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0)
    {
        syslog(LOG_ERR, "ruptimed: getaddrinfo error %s",gai_strerror(err));
        exit(EXIT_FAILURE);
    }
    for (aip = ailist; aip != NULL; aip = aip->ai_next)
    {
        if (sockfd = initserver(SOCK_STREAM, aip->ai_addr, aip->ai_addrlen,QLEN) >= 0)
        {
            serve(sockfd);
            exit(EXIT_FAILURE);
        }
    }
    exit(EXIT_FAILURE);
}
Exemple #6
0
int
main(int argc, char *argv[])
{
    int fd;

    if (!parseargs(argc, argv))
        usage();
    else {
        fd = initserver(port, qlen);
        fprintf(stdout, "Server HTTP on port %d ...\n", port);
        serve(fd);
    }

    return 0;
}
int main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int sockfd, err, n;
    char *host;

    if(argc != 1)
        err_quit("usage: %s", argv[0]);
    //取得系统参数
    //Max length of a hostname, not including the terminating null byte
    if((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
        n = HOST_NAME_MAX;
    if((host = malloc(n)) == NULL) 
        err_sys("malloc error");
    if(gethostname(host, n) < 0) 
        err_sys("gethostname error");
    //daemonize("ruptimed");

    memset(&hint, 0, sizeof(hint));
    hint.ai_flags = AI_CANONNAME;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    if((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0) {
        syslog(LOG_ERR, "ruptimed: getaddrinfo error %s", 
               gai_strerror(err));  //此函数用来返回getaddrinfo函数的错误码返回的信息
        exit(1);
    }
    for(aip = ailist; aip != NULL; aip = aip->ai_next) {
        #if 0
        struct sockaddr_in *socktmp;
        socktmp = (struct sockaddr_in *)(aip->ai_addr);
        printf("the port id is %d, the address is %s\n", ntohs(socktmp->sin_port),
                inet_ntoa(socktmp->sin_addr));
        #endif
        if((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
                                aip->ai_addrlen, QLEN)) >= 0) {
            serve(sockfd);
            exit(0);
        }
        
    }
    exit(0);
}
Exemple #8
0
int main(int argc, char *argv[])
{
	struct addrinfo	*ailist, *aip;
	struct addrinfo	hint;
	int				sockfd, err, n;
	char			*host;

	if (argc != 1)
		err_quit("usage: ./%s",argv[0]);
#ifdef _SC_HOST_NAME_MAX
	n = sysconf(_SC_HOST_NAME_MAX);
	if (n < 0)	/* best guess */
#endif
		n = HOST_NAME_MAX;
	host = malloc(n);
	if (host == NULL)
		err_sys("malloc error");
	if (gethostname(host, n) < 0)
		err_sys("gethostname error");
	init_LED();
	printf("hostname=%s\n",host);

	daemonize("Zynq@Server");
	hint.ai_flags = AI_PASSIVE;
	hint.ai_family = 0;
	hint.ai_socktype = SOCK_STREAM;
	hint.ai_protocol = 0;
	hint.ai_addrlen = 0;
	hint.ai_canonname = NULL;
	hint.ai_addr = NULL;
	hint.ai_next = NULL;
	if ((err = getaddrinfo(host, "2001", &hint, &ailist)) != 0) {
		syslog(LOG_ERR, "Zynq@Server: getaddrinfo error: %s",
		  gai_strerror(err));
		exit(1);
	}
	for (aip = ailist; aip != NULL; aip = aip->ai_next) {
		if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
		  aip->ai_addrlen, QLEN)) >= 0) {
			serve(sockfd);
			exit(0);
		}
	}
	exit(1);
}
Exemple #9
0
int main(int argc, char *argv[]){
	struct addrinfo *ailist, *aip;
	struct addrinfo hint;
	int sockfd, err, n;
	char *host;

	if(argc != 1)
		err_quit("usage: ruptimed");
#ifdef _SC_HOST_NAME_MAX
	n = sysconf(_SC_HOST_NAME_MAX);
	printf("n = %d\n", n);
	if(n < 0) /*best guess*/
#endif
		n = HOST_NAME_MAX;
	printf("HOST_NAME_MAX:%d\n", n);
	if((host = malloc(n)) == NULL)
		err_sys("malloc error");
	if(gethostname(host, n) < 0)
		err_sys("gethostname error");
	printf("The host:%s\n", host);
	/*daemonize("ruptimed");*/
	hint.ai_flags = AI_CANONNAME;
	hint.ai_family = 0;
	hint.ai_socktype = SOCK_DGRAM;
	hint.ai_protocol = 0;
	hint.ai_addrlen = 0;
	hint.ai_canonname = NULL;
	hint.ai_addr = NULL;
	hint.ai_next = NULL;
	if((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0){
		syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s", gai_strerror(err));
		exit(1);
	}
	for(aip = ailist; aip != NULL; aip = aip->ai_next){
		printf("family %d\n", aip->ai_family);
		if(aip->ai_family == AF_INET){
			if((sockfd = initserver(SOCK_DGRAM, aip->ai_addr, aip->ai_addrlen, 0)) >= 0){
				/*printf("sockfd:%d\n", sockfd);*/
				serve(sockfd);
				exit(0);
			}
		}
	}
	exit(1);
}
Exemple #10
0
int main(int argc, char *argv[])
{
	struct addrinfo	*ailist, *aip;
	struct addrinfo	hint;
	int				sockfd, err, n;
	char			*host;

	if (argc != 1)
		err_quit("usage: ruptimed");
	if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
		n = HOST_NAME_MAX;	/* best guess */
//    printf("host namelength = %d\n", n);
	if ((host = (char *)malloc(n)) == NULL)
		printf("malloc error");
	if (gethostname(host, n) < 0)
		printf("gethostname error");
    
    printf("host name = %s\n", host);
	//daemonize("ruptimed");
	memset(&hint, 0, sizeof(hint));
	hint.ai_flags = AI_CANONNAME;
	hint.ai_socktype = SOCK_STREAM;
	hint.ai_canonname = NULL;
	hint.ai_addr = NULL;
	hint.ai_next = NULL;
//    printf("................................\n");

	if ((err = getaddrinfo("127.0.0.1", "ruptime", &hint, &ailist)) != 0) {
    // host改为了127.0.0.1 ,获取的可能无法getaddrinfo,见youdaonote记录,可能需要设置etc/service里面的 
		syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s",
		  gai_strerror(err));
        printf("exit 1111 %s\n",gai_strerror(err));
		exit(1);
	}
	for (aip = ailist; aip != NULL; aip = aip->ai_next) {
		if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
		  aip->ai_addrlen, QLEN)) >= 0) {
          printf("serve before \n");
			serve(sockfd);
			exit(0);
		}
	}
	exit(1);
    return 0;
}
Exemple #11
0
int main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int sockfd, err, n;
    char *host;

    if (argc != 1) {
        printf("input arg\n");
        return -1;
    }
    n = HOST_NAME_MAX;
    host = malloc(n);
    if (host == NULL) {
        printf("malloc error\n");
        return -1;
    }
    if (gethostname(host, n) < 0) {
        printf("gethost name error\n");
        return -1;
    }

//	daemonize("ruptimed");
    hint.ai_flags = AI_CANONNAME;
    hint.ai_family = 0;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_protocol = 0;
    hint.ai_addrlen = 0;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;

    if (err = getaddrinfo(host, "ruptime", &hint, &ailist))
        exit(-1);
    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
                                 aip->ai_addrlen, QLEN)) >= 0) {
            serve(sockfd);
            return 0;
        }
    }
    exit(1);
}
Exemple #12
0
int
main(int argc, char *argv[])
{
  struct addrinfo *ailist, *aip;
  struct addrinfo hint;
  int sockfd, err, n;
  char *host;

  if (argc != 1)
    err_quit("usage: ruptimed");

  n = get_hostname_max();
  host = malloc(n);
  if (host == NULL)
    err_sys("malloc error");
  if (gethostname(host, n) < 0)
    err_sys("gethostname error");

  daemonize("ruptimed");

  hint.ai_flags = AI_CANONNAME;
  hint.ai_family = 0;
  hint.ai_socktype = SOCK_DGRAM;
  hint.ai_protocol = 0;
  hint.ai_addrlen = 0;
  hint.ai_canonname = NULL;
  hint.ai_next = NULL;

  if ((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0) {
    syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s", gai_strerror(err));
    exit(1);
  }

  for (aip = ailist; aip != NULL; aip = aip->ai_next) {
    if ((sockfd = initserver(SOCK_DGRAM, aip->ai_addr, aip->ai_addrlen, 0)) >= 0) {
      serve(sockfd);
      exit(0);
    }
  }

  exit(1);
}
int main()
{
    // TODO: Test with missing values

    printf("Initializing...\r\n");

    Logging::setCurrLevel(Logging::INFO); // Show everything

    printf("You should now see an INFO message shown for testing purposes\r\n");

    Logging::log(Logging::INFO, "Testing showing of an INFO message\r\n");

    initserver(false, true);

    printf("Running PositionUpdater tests\r\n");

    testPositionUpdater();

    printf("All tests completed successfully\r\n");
    return 1;
};
Exemple #14
0
int main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int sockfd, err, n;
    char *host;

    if (argc != 1)
        err_quit("usage: ruptimed");
    if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
        n = HOST_NAME_MAX;
    host = malloc(n);
    printf("hello -fd\n");
    if (gethostname(host, n) < 0)
        err_sys("gethostname error");
    printf("hostname: %s\n", host);
    /*daemonize("ruptimed");*/
    memset(&hint, 0, sizeof(hint));
    hint.ai_flags = AI_CANONNAME;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(host, NULL, &hint, &ailist)) != 0)
    {
        syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s",
               gai_strerror(err));
        exit(1);
    }
    for (aip = ailist; aip != NULL; aip = aip->ai_next)
    {
        if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
                                 aip->ai_addrlen, QLEN)) >= 0)
        {
            serve(sockfd);
            exit(0);
        }
    }
    exit(1);
}
Exemple #15
0
int main(int argc, char **argv) {
    int err;
    sigset_t oldmask;
    pthread_t tid;

    sigemptyset(&mask);
    sigaddset(&mask, SIGPIPE); //向信号集中添加SIGPIPE
    if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
        log_exit(err, "SIG_BLOCK error");
    err = pthread_create(&tid, NULL, sig_handler, 0);
    if (err != 0)
        log_exit(err, "Cannot create thread!");

    init_config();
    int listenfd = initserver();
    set_noblock(listenfd);
    threadpool_t *tp = threadpool_create(8);
    main_loop(tp, listenfd);

    threadpool_join(tp);
    exit(0);
}
Exemple #16
0
int
main(int argc, char *argv[])
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int             sockfd, err, n;
    char            *host;

    if (argc != 1)
        err_quit("usage: ruptimed");
    if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
        n = HOST_NAME_MAX;  /* best guess */
    if ((host = malloc(n)) == NULL)
        err_sys("malloc error");
    if (gethostname(host, n) < 0)
        err_sys("gethostname error");
    memset(&hint, 0, sizeof(hint));
    hint.ai_flags = AI_CANONNAME;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_canonname = NULL;
    hint.ai_addr = NULL;
    hint.ai_next = NULL;
    if ((err = getaddrinfo(host, "12345", &hint, &ailist)) != 0) {
        fprintf(stderr, "ruptimed: getaddrinfo error: %s\n",
          gai_strerror(err));
        exit(1);
    }
    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
          aip->ai_addrlen, QLEN)) >= 0) {
            serve(sockfd);
            exit(0);
        }
    }
    exit(1);
}
MessageWind::MessageWind(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MessageWind)
{
     QTextCodec::setCodecForTr(QTextCodec::codecForName("gb2312"));
    ui->setupUi(this);
    setFixedSize(width(),height());
    setWindowTitle(tr("信风"));
    ReadFileName readfile;
    readfile.ReadALLFile("messages.xml", "contacts.xml", "key.txt", "directory.txt"); //从文件中读取信息
    initserver();
    myName=tr("我");
    myNumber=getmyownnumber();
    connect(ui->contactsTreeWidget,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(DoubleClicked(QTreeWidgetItem*,int)));
    connect(ui->contactsTreeWidget,SIGNAL(itemCollapsed(QTreeWidgetItem*)),this,SLOT(Collapsed(QTreeWidgetItem*)));
    connect(ui->contactsTreeWidget,SIGNAL(itemExpanded(QTreeWidgetItem*)),this,SLOT(Expanded(QTreeWidgetItem*)));
    connect(ui->receiveBoxButton,SIGNAL(clicked()),this,SLOT(receiveBoxButtonClicked()));
    connect(ui->writeButton,SIGNAL(clicked()),this,SLOT(writeButtonClicked()));
    connect(ui->settingButton,SIGNAL(clicked()),this,SLOT(settingButtonClicked()));
    connect(ui->sendBoxButton,SIGNAL(clicked()),this,SLOT(sendBoxButtonClicked()));
    connect(ui->draftBoxButton,SIGNAL(clicked()),this,SLOT(draftBoxButtonClicked()));
    init();
    update();
}
Exemple #18
0
/*
 * 改进:使用多线程 线程池 测试客户端的信息 查看connect后自动分配的信息
 * 来报文写到文件中
 * 使用进程监控状态自动重启
 * 系统守护进程
 */
int main ( int argc, char *argv[] )
{
    struct addrinfo     *ailist;
    int                 listenfd;
    int                 unixfd;
    char                *host;
    char                buf[128];

#ifdef DEBUG
    /* 进程和客户端无关 后台执行 */
    signal(SIGHUP,SIG_IGN);//终端推出
    signal(SIGINT,SIG_IGN);//ctrl+C
    signal(SIGCLD,SIG_IGN);//子进程退出时发送的信号

    if( fork() != 0 )
        exit(0);
    else
        setpgrp();
#endif

    signal(SIGALRM,SIG_IGN);//子进程退出时发送的信号

    /* 第一次执行 */
    if(!sonpid)
        initson();

#if defined(Darwin)
    atexit(killson);
#endif

    /* 自己的unix域连接 */
//    sleep(1);
//    if((unixfd=cli_conn(UNIXFILE))<0)
//        err_sys( "cli_conn error" );


    /* 父进程获取外部数据 由wrfd写到子进程 由子进程处理业务 */
    //setenvadd( "LD_LIBRARY_PATH", "/home/cbs/priv/xcz/project/src", 1 );
    /* 获取本机主机名 */
    if( (host=getmyname( )) == NULL )
        err_sys( "get host name err" );

    printf("%s\n", host);
    /* 根据主机名和端口号初始化sockaddr结构 */
//    preconnect( host, "12345", SOCK_STREAM, &ailist );
//    free( host );
//    host = NULL;
//    //    printf("%hu\n", ntohs((( struct sockaddr_in * )( ailist->ai_addr ))->sin_port));
//    //    struct in_addr saddr;
//    //    saddr=(( struct sockaddr_in * )( ailist->ai_addr ))->sin_addr;
//    //    struct sockaddr a;
//    //    a=*( ailist->ai_addr );
//    //    printf("AF_INET %d %d\n", a.sa_family, AF_INET);
//    /*   侦听所有网卡 */
//    (( struct sockaddr_in * )(ailist->ai_addr))->sin_addr.s_addr=htonl( INADDR_ANY );
//    /* 打印一些信息 */
//    zl_connect_out_func( ailist->ai_addr );
//    /* 绑定端口 声明最大连接数 */
//    if ( ( listenfd = initserver( ailist->ai_socktype, ailist->ai_addr, ailist->ai_addrlen, 200 ) ) < 0 )
//    {
//        err_sys( "initserver err" );
//    }
//    freeaddrinfo( ailist );

    struct sockaddr_in  addr;
    struct sockaddr     *addrp;
    int                 socktype;
    socklen_t           addrlen;
    memset( &addr, 0x00, sizeof(addr) );
    addr.sin_family = AF_INET;
    addr.sin_port = htons(12345);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addrlen=sizeof(struct sockaddr);
    addrp=(struct sockaddr *)&addr;
    /* 绑定端口 声明最大连接数 */
    if ( ( listenfd = initserver( SOCK_STREAM, addrp, addrlen, 100 ) ) < 0 )
    {
        err_sys( "initserver err" );
    }
    zl_connect_out_func( addrp );

    unsigned long addrsize;
    int           connectfd;
    int           n,i;
    char          *p=NULL;
    char          recvbuf[SIZERCV+1];

    addrsize = sizeof( struct sockaddr );


    if(0)
    {
        i=0;
        costtime(0);
        system("date");
        while(++i<20000)
        {
            /* 自发送 测试unix域套接字效率 */
            if((unixfd=cli_conn(UNIXFILE))<0)
            {
            printf("%s%d\n",AT,i);
            fflush(NULL);
                err_sys( "%scli_conn error %d", AT, unixfd );
            }
            switch(i%7)
            {
                case 0:
                    sprintf(buf,"%d 111",i);
                    break;
                case 1:
                    sprintf(buf,"%d 121",i);
                    break;
                case 2:
                    sprintf(buf,"%d 314",i);
                    break;
                case 3:
                    sprintf(buf,"%d 315",i);
                    break;
                case 4:
                    sprintf(buf,"%d 604",i);
                    break;
                case 5:
                    sprintf(buf,"%d 900",i);
                    break;
                case 6:
                    sprintf(buf,"%d 990",i);
                    break;
            }
            if((n=write( unixfd, buf, strlen(buf) ))<0)
                printf("%s,send faild %s\n", AT, strerror(errno));
            close( unixfd );

            if(i%100==0)
                printf("%d %lf\n", i, costtime(1));
        }
        system("date");
    }


    while(1)
    {
        /* 这样单节点的accept对大并发的支持简直惨不忍睹 2w笔来账单纯接收不进行任何处理花了70s
         * 而使用select+多线程只需要10s 还是服务器运行在台式机虚拟机2核cpu 1G内存的情况下
         */
        if (( connectfd = accept( listenfd, NULL, ( socklen_t *)&addrsize ) ) == -1 )
        {
            printf( "%saccept err", AT );
            continue;
        }
        i=0;
        p=NULL;
        while( (n = recv( connectfd, recvbuf, SIZERCV, 0 )) > 0 )
        {
            recvbuf[n]=0;
            if (p)
                p=realloc(p,strlen(p)+n+1);
            else
                p=malloc(n+1);
            strcpy( p+i, recvbuf );
            i+=n;
        }
        close( connectfd );
        if (n<0)
            printf("%s,recv out err %d\n", AT,n);
//        printf("%s %s\n", AT, p);
        n=0;
        do
        {
            if((unixfd=cli_conn(UNIXFILE))<0)
            {
                /* 来的数据太多 unix域套接字connect的时候 会refuse 重新尝试就好
                 * 经测试 也就尝试140次左右可connect成功
                 */
                n++;
                if(!(n&0xFF))//256的倍数打印
                  printf( "%scli_conn error %d retried %d times", AT, unixfd, n );
                continue;
            }
        }while(0);
        write(unixfd, p, i);
        close( unixfd );
        free(p);
        p=NULL;
    }
    close( listenfd );



    return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
Exemple #19
0
/* Since a socket endpoint is represented as a file descriptor, we can use
 * read() and write() to communicate with a socket, as long as it is
 * connected. Although we can exchange data using read() and write(), that
 * is about all we can do with these two functions. If we want to specify
 * options, receive packets from multiple clients, or send out-of-band data,
 * we need to use on of the six socket functions designed for data transfer.
 *
 * The simplest one is send(). It is similar to write(), but allows us to
 * specify flags to change how the data we want to transmit is treated.
 * #include <sys/socket.h>
 * ssize_t send(int sockfd, const void *buf, size_t nbytes, int flags);
 *      Returns: number of bytes sent if OK, -1 on error
 * Like write(), the socket has to be connected to use send(). The buf and
 * nbytes arguments have the same meaning as they do with write().
 * send()函数的flags可能取值为:MSG_DONTROUTE, MSG_DONTWAIT, MSG_EOR, MSG_OOB
 *
 * If send() returns success, it doesn't necessarily mean that the process
 * at the other end of the connection receives the data. All we are
 * guaranteed is that when send() succeeds, the data has been delivered to
 * the network drivers without error.
 *
 * With a protocol that supports message boundaries, if we try to send a
 * single message larger than the maximum supported by the protocol, send()
 * will fail with errno set to EMSGSIZE. With a byte-stream protocol, send()
 * will block until the entire amount of data has been transmitted.
 *
 * The sendto() function is similar to send(). The diffrence is that
 * sendto() allows us to specify a destination address to be used with
 * connectionless socket.
 * ssize_t sendto(int sockfd, const void *buf, size_t nbytes, int flags,
 *      const struct sockaddr *destaddr, socklen_t destlen);
 *      Returns: number of bytes sent if OK, -1 on error 
 * With a connection-oriented socket, the destination address is ignored, as
 * the destination is implied by the connection. With a connectionless
 * socket, we can't use send() unless the destination address is first set
 * by calling connect(), so sendto() gives us an alternate way to send a
 * message.
 *
 * We have one more choice when transmitting data over a socket. We can call
 * sendmsg() with a msghdr structure to specify multiple buffers from which
 * to transmit data, similar to the writev() function.
 * ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
 *      Returns: number of bytes sent if OK, -1 on error
 * 关于这个函数的其他信息可查看man手册.
 */
int main(void)
{
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int sockfd, n, err;
    char *hostname;

/* To find out its address, the server needs to get the name of the host on
 * which it is running. Some systems don't define the _SC_HOST_NAME_MAX
 * constant, so we use HOST_NAME_MAX in this case. If the system doesn't
 * define HOST_NAME_MAX, we define it ourselves. POSIX.1 states that the
 * minimum value for the host name is 255 bytes, not including the
 * terminating null, so we define HOST_NAME_MAX to be 256 to include the
 * terminating null.
 * man sysconf 中对 HOST_NAME_MAX, _SC_HOST_NAME_MAX 解释如下:
 * Max length of a hostname, not including the terminating null byte, as
 * returned by gethostname(). Must not be less than _POSIX_HOST_NAME_MAX
 * (255).
 */
#ifdef _SC_HOST_NAME_MAX
    n = sysconf(_SC_HOST_NAME_MAX);
    if (n < 0)
#endif
        n = HOST_NAME_MAX;
    if ((hostname = malloc(n)) == NULL) {
        perror("malloc error");
        exit(1);
    }

    if (gethostname(hostname, n) < 0) {
        perror("gethostname error");
        exit(1);
    }

    daemonize("ruptimed");

    hint.ai_flags = AI_CANONNAME;
    hint.ai_family = 0;
    hint.ai_socktype = SOCK_STREAM; /* 只获取tcp类型的服务 */
    hint.ai_protocol = 0;
    hint.ai_addrlen = 0;
    hint.ai_addr = NULL;
    hint.ai_canonname = NULL;
    hint.ai_next = NULL;
    /* 注意, "ruptime" 服务并不是标准服务,系统中默认是没有这个服务的,运行
     * 时,getaddrinfo()函数报错: Servname not supported for ai_socktype
     * 解决这个问题的方法是:将"ruptime"服务添加到/etc/services文件中,这样
     * getaddrinfo()函数就能获取到该服务,不会再报错.
     */
    if ((err = getaddrinfo(hostname, "ruptime", &hint, &ailist)) != 0) {
        syslog(LOG_ERR, "getaddrinfo error: %s\n", gai_strerror(err));
        exit(1);
    }
    for (aip = ailist; aip != NULL; aip = aip->ai_next) {
        if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
                        aip->ai_addrlen, QLEN)) >= 0) {
            serve(sockfd);
            exit(0);
        }
    }

    exit(1);
}
Exemple #20
0
/*
 * Main print server thread.  Accepts connect requests from
 * clients and spawns additional threads to service requests.
 *
 * LOCKING: none.
 */
int
main(int argc, char *argv[])
{
	pthread_t			tid;
	struct addrinfo		*ailist, *aip;
	int					sockfd, err, i, n, maxfd;
	char				*host;
	fd_set				rendezvous, rset;
	struct sigaction	sa;
	struct passwd		*pwdp;

	if (argc != 1)
		err_quit("usage: printd");
	daemonize("printd");

	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sa.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &sa, NULL) < 0)
		log_sys("sigaction failed");
	sigemptyset(&mask);
	sigaddset(&mask, SIGHUP);
	sigaddset(&mask, SIGTERM);
	if ((err = pthread_sigmask(SIG_BLOCK, &mask, NULL)) != 0)
		log_sys("pthread_sigmask failed");

	n = sysconf(_SC_HOST_NAME_MAX);
	if (n < 0)	/* best guess */
		n = HOST_NAME_MAX;
	if ((host = malloc(n)) == NULL)
		log_sys("malloc error");
	if (gethostname(host, n) < 0)
		log_sys("gethostname error");

	if ((err = getaddrlist(host, "print", &ailist)) != 0) {
		log_quit("getaddrinfo error: %s", gai_strerror(err));
		exit(1);
	}
	FD_ZERO(&rendezvous);
	maxfd = -1;
	for (aip = ailist; aip != NULL; aip = aip->ai_next) {
		if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,
		  aip->ai_addrlen, QLEN)) >= 0) {
			FD_SET(sockfd, &rendezvous);
			if (sockfd > maxfd)
				maxfd = sockfd;
		}
	}
	if (maxfd == -1)
		log_quit("service not enabled");

	pwdp = getpwnam(LPNAME);
	if (pwdp == NULL)
		log_sys("can't find user %s", LPNAME);
	if (pwdp->pw_uid == 0)
		log_quit("user %s is privileged", LPNAME);
	if (setgid(pwdp->pw_gid) < 0 || setuid(pwdp->pw_uid) < 0)
		log_sys("can't change IDs to user %s", LPNAME);

	init_request();
	init_printer();

	err = pthread_create(&tid, NULL, printer_thread, NULL);
	if (err == 0)
		err = pthread_create(&tid, NULL, signal_thread, NULL);
	if (err != 0)
		log_exit(err, "can't create thread");
	build_qonstart();

	log_msg("daemon initialized");

	for (;;) {
		rset = rendezvous;
		if (select(maxfd+1, &rset, NULL, NULL, NULL) < 0)
			log_sys("select failed");
		for (i = 0; i <= maxfd; i++) {
			if (FD_ISSET(i, &rset)) {
				/*
				 * Accept the connection and handle the request.
				 */
				if ((sockfd = accept(i, NULL, NULL)) < 0)
					log_ret("accept failed");
				pthread_create(&tid, NULL, client_thread,
				  (void *)((long)sockfd));
			}
		}
	}
	exit(1);
}
Exemple #21
0
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  listenout
 *       Author:  Chenzhi Xu
 *      Created:  11/19/15 14:29:29
 *  Description:  侦听外部来报
 *                当和外部使用中间件时,此函数接收来自中间件的数据
 *                将数据传给儿子,由儿子处理数据,父亲只负责接收数据
 * =====================================================================================
 */
int listenout()
{
    struct addrinfo     *ailist;
    struct sockaddr_in  addr;
    struct sockaddr     *addrp;
    int                 socktype;
    socklen_t           addrlen;
    int                 listensockfd;
    int                 listenunixfd;
    int                 nzero;
    char                *host;
#if defined(NZERO)
    nzero=NZERO;
#elif defined(_SC_NZERO)
    nzero=sysconf(_SC_NZERO);
#else
#error NZERO undefined
#endif
    /* 获取本机主机名 */
    if( (host=getmyname( )) == NULL )
        err_sys( "get host name err" );

    printf("%s%s\n", AT, host);
    /* 根据主机名和端口号初始化sockaddr结构 */
//    preconnect( host, "12344", SOCK_STREAM, &ailist );
//    addrlen=ailist->ai_addrlen;
//    /* 直接取第一条记录 不考虑匹配多条的情况 */
//    memcpy( &addr, ailist->ai_addr, addrlen );
//    socktype=ailist->ai_socktype;
//    free( host );
//    host = NULL;
//    freeaddrinfo( ailist );
    //    printf("%hu\n", ntohs((( struct sockaddr_in * )( ailist->ai_addr ))->sin_port));
    //    struct in_addr saddr;
    //    saddr=(( struct sockaddr_in * )( ailist->ai_addr ))->sin_addr;
    //    struct sockaddr a;
    //    a=*( ailist->ai_addr );
    //    printf("AF_INET %d %d\n", a.sa_family, AF_INET);



    /* sock套接字 侦听内部其他系统的数据
     * 外部使用中间件 中间件进程和此进程使用unix域套接字通讯
     */
    memset( &addr, 0x00, sizeof(addr) );
    addr.sin_family = AF_INET;
    addr.sin_port = htons(12344);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addrlen=sizeof(struct sockaddr);
    addrp=(struct sockaddr *)&addr;
    /* 绑定端口 声明最大连接数 */
    if ( ( listensockfd = initserver( SOCK_STREAM, addrp, addrlen, 100 ) ) < 0 )
    {
        err_sys( "initserver err" );
    }
    zl_connect_out_func( addrp );
    /* 打开及设置keepalive内容 */
    SocketKeepalive( listensockfd );

    /* unix域套接字 */
    if ((listenunixfd=serv_listen(UNIXFILE))<0)
    {
        printf("%s%d %s\n",AT, listenunixfd, strerror(errno));
        err_sys("serv_listen error");
    }

    /* 设置执行时关闭 */
    set_cloexec( listensockfd );
    set_cloexec( listenunixfd );

    /* 设置进程优先级 */
//    ni=getpriority(PRIO_PROCESS,0);
//    printf("%s,now nice=%d\n", AT, ni);
//#ifndef Darwin
    nice(nzero/2);
//#endif
//    setpriority(PRIO_PROCESS,0,nzero);
    printf("%snice=%d\n", AT, getpriority(PRIO_PROCESS,0));
//    printf("%s,sockfd=%d unixfd=%d\n", AT, listensockfd, listenunixfd);

    if( SelectAndHandle( listensockfd, listenunixfd ) != 0 )
        err_msg( "handle err" );

    close( listensockfd );
    close( listenunixfd );
    return 0;
}