예제 #1
0
void st_epoll_test(void)
{
    int ret = 0;
    int lsocket = 0;

    ST_THREAD_MANAGE st_manage;
    P_ST_THREAD_MANAGE p_manage = &st_manage;

    if ( !st_threadpool_init(p_manage, 5))
    {
        st_print("st_threadpool_init FAILED!\n");
        return;
    }

    P_EPOLL_STRUCT p_epoll = NULL;

    lsocket = st_buildsocket(10, 7899);
    st_make_nonblock(lsocket);

    if (lsocket == -1)
    {
        st_print("st_buildsocket FAILED!\n");
        return;
    }

    p_epoll = st_make_events(lsocket, 32);
    if (!p_epoll)
    {
        st_print("st_make_events FAILED!\n");
        return;
    }

    st_event_loop(p_epoll, p_manage, response_func);

}
예제 #2
0
void st_shm_test(void)
{
    P_ST_SHM_T p_token = NULL;
    p_token = st_shm_create("RPC_SHARE", 4096);

    //st_memmap_open("RPC_SHARE", 0, 0);

    struct shm_struct* p_st = NULL;
    if ( p_token)
    {
        p_st = (struct shm_struct*) p_token->location;
        p_st->i = 0x77889;
        p_st->c = 'T';
        strcpy(p_st->buf, "TAOZHIJIANG TEST");

        st_print("TEST_DATA:\n");
        st_print("i:%x\t c:%c\t str:%s\n", p_st->i, p_st->c, p_st->buf);
    }

    getchar();

    st_print("Rechecking data:\n");

    st_print("i:%x\t c:%c\t str:%s\n", p_st->i, p_st->c, p_st->buf);


    st_shm_destroy(p_token);

}
예제 #3
0
파일: soduku_test.c 프로젝트: EchoLiao/lang
int main (int argc, char *argv[])
{
    int i, ret;

    for ( i = 0; i < 100; i++ )
    {
        sodk_create(g_sodukuTab);
        if ( st_verification(g_sodukuTab) )
        {
            // st_print(g_sodukuTab);
        }
        else 
        {
            printf("NAL **(( HAD ERROR!!!! ))*** i=%d\n", i);
            st_print(g_sodukuTab);
            assert(0);
        }

        // ret = sodk_dig(g_sodukuTab, SODK_GRADE_LOW);
        // ret = sodk_dig(g_sodukuTab, SODK_GRADE_PRIMARY);
        // ret = sodk_dig(g_sodukuTab, SODK_GRADE_MIDDLE);
        // ret = sodk_dig(g_sodukuTab, SODK_GRADE_HIGH);
        ret = sodk_dig(g_sodukuTab, SODK_GRADE_ASHES);
        st_print(g_sodukuTab);
        printf("NAL **(())*** i=%d, ret=0x%x\n", i, ret);
    }

    return 0;
}
예제 #4
0
void* mutex_thread(void* data)
{
    int i = 0, nloop = 10;
    int ret = 0;

    P_ST_WINSYNC_T p_mutex = (P_ST_WINSYNC_T)data;
    P_ST_MEMMAP_T p_token = (P_ST_MEMMAP_T)p_mutex->extra;

    for (i = 0; i < nloop; i++) 
    {
        ret = WaitForSingleObject(p_mutex, 2000); //2s
        if (ret == ETIMEDOUT)
        {
            st_print("THREAD WAIT TIMEDOUT\n");
            continue;
        }
        st_print("G_LOCK\n"); 
        write(p_token->fd, "GGGGG", 5);
        usleep(200*1000);
        write(p_token->fd, "GGGGG", 5);
        st_print("G_UNLOCK\n");
        ReleaseMutex(p_mutex);
        usleep(100*1000);
    }

    return NULL;
}
예제 #5
0
SSL* st_tls_create_ssl(P_ST_TLS_STRUCT p_st_tls, int sock)
{
    char*   str = NULL;
    X509*   peer_cert = NULL;
    SSL*    p_ssl;

    if ( !p_st_tls || !p_st_tls->p_ctx || sock < 0)
    {
        st_d_print("Invalid argument!\n");
        return NULL;
    }

    RET_NULL_IF_TRUE_S( !(p_ssl = SSL_new (p_st_tls->p_ctx)) );
    RET_NULL_IF_TRUE_S( !SSL_set_fd (p_ssl, sock) );

    if ( p_st_tls->work_status == WORK_SERVER)
    {
        RET_NULL_IF_TRUE_S((SSL_accept(p_ssl) != 1)); 
    }
    else if ( p_st_tls->work_status == WORK_CLIENT)
    {
        RET_NULL_IF_TRUE_S((SSL_connect(p_ssl) != 1));
    }
    else
    {
        SYS_ABORT("YOU SHOULD NOT CALL THIS FUNC!!!\n");
    }
	
#if 1
    peer_cert = SSL_get_peer_certificate (p_ssl);

    if (peer_cert != NULL) 
    {
        str = X509_NAME_oneline (X509_get_subject_name (peer_cert), 0, 0);
        if(str)
        {
            st_print("OBJECT:%s\n", str);
            OPENSSL_free (str);
        }
    
        str = X509_NAME_oneline (X509_get_issuer_name  (peer_cert), 0, 0);
        if(str)
        {
            st_print("ISSUER:%s\n", str);
            OPENSSL_free (str);
        }
    
        /* We could do all sorts of certificate verification stuff here before
           deallocating the certificate. */
    
        X509_free (peer_cert);
    } 
    else
        st_d_print("Peer does not have certificate!!!\n");
#endif

    return p_ssl;
}
예제 #6
0
P_ST_TLS_STRUCT st_tls_create_ctx(P_ST_TLS_STRUCT p_st_tls)
{
    P_SSL_CTX p_ctx = NULL;

    OpenSSL_add_ssl_algorithms();
    SSL_load_error_strings();
    SSL_library_init();     //SSL_library_init() always returns "1"

    tls_rand_seed();

    if ( p_st_tls->work_status == WORK_SERVER )
    {
        st_print("Initialize with TLSv1_server_method() \n");
        RET_NULL_IF_TRUE_S(!(p_ctx = SSL_CTX_new(TLSv1_server_method()))); 
    }
    else if ( p_st_tls->work_status == WORK_CLIENT )
    {
        st_print("Initialize with TLSv1_client_method() \n");
        RET_NULL_IF_TRUE_S(!(p_ctx = SSL_CTX_new(TLSv1_client_method())));
    }
    else
    {
        st_print("Initialize with TLSv1_method() \n");
        RET_NULL_IF_TRUE_S(!(p_ctx = SSL_CTX_new(TLSv1_method())));
    }


    //SSL_CTX_set_default_passwd_cb(p_ctx, no_passphrase_callback);
    SSL_CTX_set_mode(p_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);

    if ( strlen(p_st_tls->ca_file) )
    {
        RET_NULL_IF_TRUE_S( !SSL_CTX_load_verify_locations(p_ctx, p_st_tls->ca_file, NULL));
    }
    else
    {
        st_print("No CAfile Verify!\n");
    }

    RET_NULL_IF_TRUE_S( !SSL_CTX_use_PrivateKey_file(p_ctx, p_st_tls->key_file, SSL_FILETYPE_PEM)); 

    RET_NULL_IF_TRUE_S( !SSL_CTX_use_certificate_chain_file(p_ctx, p_st_tls->cert_file));

    // 判定私钥是否正确  
    RET_NULL_IF_TRUE_S( !SSL_CTX_check_private_key(p_ctx));

    p_st_tls->p_ctx = p_ctx;

    return p_st_tls;
}
예제 #7
0
static void* response_func(void* data)
{
    ssize_t count;
	ssize_t nBytes;
    char buf[512];
    int done = 0;

    int socket = (int)data;
    //st_print("Function Called with %d under %ul \n", num, pthread_self());
    
	nBytes = 0;
	while (TRUE)
	{
		//接收数据
        count = recv (socket, buf + nBytes, 512, 0);
            
        if (count < 0)
        {   
            //数据读完了
            if ( count == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
            {
                // 由于此处的套接字已经是非阻塞的了,怎么处理后面再定
                break;
            }
            else
            {
                st_print("RECV ERROR for socket:%d\n", socket); 
                return NULL;
            }
        }
        else if (count == 0)    //stream socket peer has performed an orderly shutdown
        {
            //对端已经关闭了,这里也关闭
			st_print("Peer Close the Connection, close it!\n");
			close(socket);	// this will reclaim socket	
			return NULL;
        } 
        else 
        {
            nBytes += count;
            continue; // to read
        }
    }
	
	// Data Ready!!!!

    return NULL;
}
예제 #8
0
void st_event_comsumer_test(void)
{
    P_ST_MEMMAP_T p_token = NULL;
    p_token = st_memmap_create(NULL, "RPC_SHARE", 4096);
    char* ptr = p_token->location;
    *ptr = '\0';
    char buf[512];

    if (!p_token)
        return;

    P_ST_WINSYNC_T p_event = (P_ST_WINSYNC_T)CreateEvent(NULL, 0, 0, "RPC_EVENT");
    
    int i = 0, nloop = 100;
    lseek(p_token->fd, 0, SEEK_SET);

    /* back to parent process */
    for (i = 0; i < nloop; i++) 
    {
        WaitForSingleObject(p_event, INFINITE);
        memset(buf, 0, sizeof(buf));
        lseek(p_token->fd, 0, SEEK_SET);
        read(p_token->fd, buf, sizeof(buf));
        st_print("COMSUMER GET:%s\n", buf);
        usleep(300);
    }
    
    st_memmap_close(p_token);
    st_memmap_destroy(p_token);
    CloseHandle(p_event);
    st_winsync_destroy(p_event);
}
예제 #9
0
void st_event_producer_test(void)
{

    P_ST_MEMMAP_T p_token = NULL;
    p_token = st_memmap_open("RPC_SHARE", 1, 1);
    char* ptr = p_token->location;
    *ptr = '\0';
    char buf[512];

    if (!p_token)
        return;

    P_ST_WINSYNC_T p_event = (P_ST_WINSYNC_T)OpenEvent(0, 0, "RPC_EVENT");
    
    int i = 0, nloop = 100;

    WAIT_FOR_ENTER;

    /* back to parent process */
    for (i = 0; i < nloop; i++) 
    {
        snprintf(buf, sizeof(buf), "THIS IS MESSAGE: ID-%d", i);
        lseek(p_token->fd, 0, SEEK_SET);
        write(p_token->fd, buf, strlen(buf)+1);
        st_print("POSTING:%s\n", buf);
        SetEvent(p_event);
    }

    st_memmap_close(p_token);
    CloseHandle(p_event);
    st_winsync_destroy(p_event);
}
예제 #10
0
HANDLE OpenMutex( DWORD dwDesiredAccess,
                BOOL bInheritHandle, const char* lpName)
{
    P_ST_WINSYNC_T p_mutex = NULL;

    if ( !lpName)
    {
        st_print("You may use this function for inter-process, please check!\n");
        return NULL;
    }

    p_mutex = (P_ST_WINSYNC_T)malloc(sizeof(ST_WINSYNC_T));
    if (!p_mutex)
        return NULL;

    memset(p_mutex, 0, sizeof(ST_WINSYNC_T));
    p_mutex->type = SYNC_MUTEX;

    strncpy(p_mutex->sync_name, lpName, PATH_MAX);
    // initial value => 0
    p_mutex->p_sem = sem_open(p_mutex->sync_name, 0, 0644, 0);
    if (p_mutex->p_sem == SEM_FAILED)
    {
        st_d_print("Open Mutex: %s failed!\n", p_mutex->sync_name);
        free(p_mutex);
        return NULL;
    }

    return p_mutex;
}
예제 #11
0
파일: test.c 프로젝트: firstwave-xx/test
int main()
{
	char line[256];
	char *p;
	char c;
	char t;
	int v;
	int i = 0;
	int number = 0;

	st_init();

	printf("INPUT: ");
	gets(line);

	p = line;
	while( (c=*p) != 0 && c!='\n')  {
		if( c == ' ' || c == '\t' ) { p++; continue;}
		else if( '9' >= c && c >= '0' ) {
			p = get_number(p, &number);
			t = 0;

			st_push( t, number);
		}
		else {
			switch( c ) {
				case '*': 
				case '/':
				case '+':
				case '-':
					calc( c ); st_push( c, 0 ); break;
			}
			p ++;
		}
		st_print();
	}

	c = '=';

	calc( c );

	st_print();

	st_pop( &t, &v ); 
	
	printf("Result: %d \n", v);
}
예제 #12
0
파일: bpmatch.cpp 프로젝트: pangon/BpMatch
void st_print(st_node* node) {
	printf("NODO l=%d, leaf=%d [%d-%d]\n", node->length, node->leafId, node->firstLeaf, node->lastLeaf);
	if(node->edges[A]==NULL && node->edges[C]==NULL && node->edges[T]==NULL && node->edges[G]==NULL && node->edges[X]==NULL) printf("-leaf\n");
	for(int i=0;i<5;i++) {
		if(node->edges[i]!=NULL) printf("-*%c*[%d-%d](count=%d)\n", base2char[i], node->edges[i]->start, node->edges[i]->end, node->edges[i]->count);
		}
	for(int i=0;i<5;i++) {
		if(node->edges[i]!=NULL) st_print(node->edges[i]->to);
		}
	}
예제 #13
0
void st_event_thread_test(void)
{
    P_ST_MEMMAP_T p_token = NULL;
    p_token = st_memmap_create(NULL, "RPC_SHARE", 4096);
    char* ptr = p_token->location;
    *ptr = '\0';
    char buf[512];
    int ret = 0;

    if (!p_token)
        return;

    P_ST_WINSYNC_T p_event = (P_ST_WINSYNC_T)CreateEvent(NULL, 0, 0, "RPC_EVENT3");
    
    pthread_t pid;
    p_event->extra = p_token;
    pthread_create(&pid, NULL,event_thread, p_event);

    int i = 0, nloop = 100;
    lseek(p_token->fd, 0, SEEK_SET);

    /* back to parent process */
    for (i = 0; i < nloop; i++) 
    {
        ret = WaitForSingleObject(p_event, 1000); //1s
        if (ret == ETIMEDOUT)
        {
            st_print("WAIT TIME OUT!\n");
            continue;
        }
        memset(buf, 0, sizeof(buf)); 
        lseek(p_token->fd, 0, SEEK_SET);
        read(p_token->fd, buf, sizeof(buf));
        st_print("COMSUMER GET:%s\n", buf);
        usleep(3000);
    }
    
    st_memmap_close(p_token);
    st_memmap_destroy(p_token);
    CloseHandle(p_event);
    st_winsync_destroy(p_event);
}
예제 #14
0
int st_buildsocket(int listen_cnt, int port)
{
    int lsocket;

    lsocket = socket(AF_INET, SOCK_STREAM, 0);
    if (lsocket == -1)
    {
        st_print("Create Socket Error!\n");
        return -1;
    }

	int flag = 1;
	if( setsockopt(lsocket, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == -1 )
	{
		st_print("setsockopt Error!\n");
        return -1;
	}

	struct sockaddr_in svraddr;
	svraddr.sin_family = AF_INET;
	svraddr.sin_port = htons(port);
	svraddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(bind(lsocket, (struct sockaddr *)&svraddr, sizeof(struct sockaddr_in)))
	{
		st_print("Socket Bind Error!\n");
        close(lsocket);
		return -1;
	}


	if(listen(lsocket, listen_cnt))
	{
		st_print("Socket Set Listen Error!\n");
        close(lsocket);
		return -1;
	}

	return lsocket;
}
예제 #15
0
void st_shm_test2(void)
{
    P_ST_SHM_T p_token = NULL;
    p_token = st_shm_open("/RPC_SHARE", 1, 1);

    struct shm_struct* p_st = NULL;

    if ( p_token)
    {
        p_st = (struct shm_struct*) p_token->location;

        st_print("CHECKING MAP DATA:\n");
        st_print("i:%x\t c:%c\t str:%s\n", p_st->i, p_st->c, p_st->buf);
    }

    st_print("Changing the data from another process!\n");
    p_st->i = 0xAA991;
    p_st->c = 'J';
    strcpy(p_st->buf, "NEW INFO HERE!");

    st_shm_close(p_token);
}
예제 #16
0
void* event_thread(void* data)
{
    int i = 0, nloop = 20;
    int ret = 0;
    char buf[512];

    P_ST_WINSYNC_T p_event = (P_ST_WINSYNC_T)data;
    P_ST_MEMMAP_T p_token = (P_ST_MEMMAP_T)p_event->extra;

    for (i = 0; i < nloop; i++) 
    {
        snprintf(buf, sizeof(buf), "THIS IS MESSAGE: ID-%d", i);
        lseek(p_token->fd, 0, SEEK_SET);
        write(p_token->fd, buf, strlen(buf)+1);
        st_print("POSTING:%s\n", buf);
        SetEvent(p_event);
    }

    return NULL;
}
예제 #17
0
void utf8_gbk_test(void)
{
    //char buf[512] = "外边的字到底怎么为什么有的时候通不过呢";
    //utf8_to_gbk(buf, sizeof(buf));
    //gbk_to_utf8(buf, sizeof(buf));

    char line[MAX_LINE];
    int ret = 0;
    FILE* fp = fopen("input.txt","r");
    FILE* fp_gbk = fopen("out.gbk", "w");

    rewind(fp);
    while((ret = st_getline(line, fp)) > 0)
	{
        utf8_to_gbk(line, MAX_LINE);
        fputs(line, fp_gbk);
    }
    fclose(fp);
    fclose(fp_gbk);

    fp_gbk = fopen("out.gbk", "r");
    FILE* fp_utf8 = fopen("out.utf8", "w");
    rewind(fp_gbk);
    while((ret = st_getline(line, fp_gbk)) > 0)
    {
        gbk_to_utf8(line, MAX_LINE);
        fputs(line, fp_utf8);
    }


    fclose(fp_gbk);
    fclose(fp_utf8);

    st_print("TEST TERMINATED!\n");

    return;
}
예제 #18
0
/**
 * 由于自己封装了结构,方便调用,所以有fork亲属关系的进程,不再
 * 让其继承mutex结构,需要创建使用命名Mutex
 */
HANDLE CreateMutex( void* lpMutexAttributes,
                BOOL bInitialOwner, const char* lpName)
{
    P_ST_WINSYNC_T p_mutex = NULL;

    p_mutex = (P_ST_WINSYNC_T)malloc(sizeof(ST_WINSYNC_T));
    if (!p_mutex)
        return NULL;

    memset(p_mutex, 0, sizeof(ST_WINSYNC_T));
    p_mutex->type = SYNC_MUTEX;

    if ( lpName) // Inter-Process
    {
        strncpy(p_mutex->sync_name, lpName, PATH_MAX);
        sem_unlink(lpName); // Just for safe
        //bInitialOwner
        p_mutex->p_sem = sem_open(p_mutex->sync_name, O_CREAT | O_EXCL, 0644, bInitialOwner); 
        if (p_mutex->p_sem == SEM_FAILED)
        {
            st_d_print("Create Mutex: %s failed!\n", p_mutex->sync_name);
            free(p_mutex);
            return NULL;
        }
    }
    else        // Intra-Process
    {
        p_mutex->sync_name[0] = '\0';
        if( sem_init((sem_t *)(&p_mutex->sem), 1/*pshared for forked dismiss*/, 1) != 0)
        {
            st_print("semaphore initilization");
            return NULL;
        }
    }

    return p_mutex;
}
예제 #19
0
void test01 ( )

/******************************************************************************/
/*
  Purpose:

    TEST01 tests CC_TO_ST using a 1-based matrix.

  Discussion:

    This test uses a trivial matrix whose full representation is:

          2  3  0  0  0
          3  0  4  0  6
      A = 0 -1 -3  2  0
          0  0  1  0  0
          0  4  2  0  1

    The 1-based CC representation is

      #  ICC  CCC  ACC
     --  ---  ---  ---
      1    1    1    2
      2    2         3

      3    1    3    3
      4    3        -1
      5    5         4

      6    2    6    4
      7    3        -3
      8    4         1
      9    5         2

     10    3   10    2

     11    2   11    6
     12    5         1

     13    *   13

  Licensing:

    This code is distributed under the GNU LGPL license.

  Modified:

    18 July 2014

  Author:

    John Burkardt
*/
{
# define N 5
# define NCC 12

    double acc[NCC] = {
        2.0,  3.0,
        3.0, -1.0,  4.0,
        4.0, -3.0,  1.0, 2.0,
        2.0,
        6.0, 1.0
    };
    double *ast;
    int ccc[N+1] = {
        1, 3, 6, 10, 11, 13
    };
    int i;
    int icc[NCC] = {
        1, 2,
        1, 3, 5,
        2, 3, 4, 5,
        3,
        2, 5
    };
    int *ist;
    int *jst;
    int m = 5;
    int n = N;
    int ncc = NCC;
    int nst;

    printf ( "\n" );
    printf ( "TEST01\n" );
    printf ( "  Convert a 1-based CC matrix to ST format.\n" );
    /*
      Print the CC matrix.
    */
    cc_print ( m, n, ncc, icc, ccc, acc, "  The CC matrix:" );
    /*
      Convert it.
    */
    ist = ( int * ) malloc ( ncc * sizeof ( int ) );
    jst = ( int * ) malloc ( ncc * sizeof ( int ) );
    ast = ( double * ) malloc ( ncc * sizeof ( double ) );

    cc_to_st ( m, n, ncc, icc, ccc, acc, &nst, ist, jst, ast );
    /*
      Print the ST matrix.
    */
    st_print ( m, n, nst, ist, jst, ast, "  The ST matrix:" );
    /*
      Free memory.
    */
    free ( ast );
    free ( ist );
    free ( jst );

    return;
# undef N
# undef NCC
}
예제 #20
0
static char* code_convert(char* src, int size   ,
                          const char* tocode, const char* fromcode)
{
    char*  in_buf = NULL; char* p_in = NULL;
    char*  out_buf = NULL; char* p_out = NULL;
    size_t in_len = strlen(src);
    size_t out_len = in_len * 4;
    size_t conv_cnt = 0;
    iconv_t cd = 0;

    if (!src || !tocode || !fromcode)
        return NULL;

    in_buf = strdup(src);
    if (!in_buf)
        return NULL;
    out_buf = (char *)malloc(out_len);
    if (!out_buf)
    {
        free(in_buf);
        return NULL;
    }
    p_in = in_buf;
    p_out = out_buf;

    // 忽略输入中非法的字符。测试过程中有这种情况,看实际的效果
    GOTO_IF_TRUE ( (cd = iconv_open(tocode, fromcode)) == (iconv_t)-1, failed);

    memset(out_buf, 0, out_len);
    conv_cnt = iconv(cd, &p_in, &in_len, &p_out, &out_len);
    iconv_close(cd);

    //Perfect ONE
    if ( conv_cnt == 0 && strlen(out_buf) < size)
    {
        //st_print("GOOD: code_convert(%s->%s)[%s]",
        //fromcode, tocode, out_buf);
        memset(src, 0, size);
        strcpy(src, out_buf);
    }
    else if ( strlen(out_buf) > 0)
    {
        st_print("WARNING: code_convert(%s->%s)[%s]",
                 fromcode, tocode, out_buf);
        memset(src, 0, size);
        strcpy(src, out_buf);
    }
    else
    {
        st_print("ERROR: code_convert(%s->%s)[%s]",
                 fromcode, tocode, src);
        goto failed;
    }
    free(in_buf);
    free(out_buf);
    return src;

failed:
    free(in_buf);
    free(out_buf);
    return NULL;
}
예제 #21
0
/**
 * 只会在USR端被调用
 */
void accept_conn_cb(struct evconnlistener *listener,
    evutil_socket_t fd, struct sockaddr *address, int socklen,
    void *ctx)
{
    P_PORTMAP p_map = (P_PORTMAP)ctx; 
    char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

    getnameinfo (address, socklen,
               hbuf, sizeof(hbuf),sbuf, sizeof(sbuf),
               NI_NUMERICHOST | NI_NUMERICSERV);

    st_print("WELCOME NEW CONNECT (HOST=%s, PORT=%s)\n", hbuf, sbuf);

    /* We got a new connection! Set up a bufferevent for it. */
    struct event_base *base = evconnlistener_get_base(listener);

    int srv_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sc_connect_srv(srv_fd) != RET_YES) 
    {
        st_d_error("连接服务器失败!");
        return;
    }

    P_PORTTRANS p_trans = sc_create_trans(atoi(sbuf)); 

    if (!p_trans)
    {
        st_d_error("本地无空闲TRANS!");
        return;
    }

    struct bufferevent *local_bev = 
        bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
    assert(local_bev);
    bufferevent_setcb(local_bev, bufferread_cb, NULL, bufferevent_cb, p_trans);
    //bufferevent_enable(local_bev, EV_READ|EV_WRITE);

    struct bufferevent *srv_bev = 
        bufferevent_socket_new(base, srv_fd, BEV_OPT_CLOSE_ON_FREE);
    assert(srv_bev);
    bufferevent_setcb(srv_bev, bufferread_cb, NULL, bufferevent_cb, p_trans);
    //bufferevent_enable(srv_bev, EV_READ|EV_WRITE);

    p_trans->is_enc = 0;
    p_trans->l_port = atoi(sbuf);
    p_trans->local_bev = local_bev;
    p_trans->srv_bev = srv_bev;

    st_d_print("DDDDD: 当前活动连接数:[[[ %d ]]]", 
               slist_count(&cltopt.trans)); 

    /* 向服务器报告连接请求 */
    CTL_HEAD ret_head;
    memset(&ret_head, 0, CTL_HEAD_LEN);
    ret_head.cmd = HD_CMD_CONN;
    ret_head.daemonport = p_map->daemonport;
    ret_head.usrport = p_map->usrport;
    ret_head.extra_param = atoi(sbuf);
    ret_head.mach_uuid = cltopt.session_uuid;
    ret_head.direct = USR_DAEMON;

    bufferevent_write(srv_bev, &ret_head, CTL_HEAD_LEN);

    st_d_print("客户端创建BEV OK!");

    /**
     * 有些服务是conn连接之后,服务端先发消息,然后客户端再进行响应的,所以 
     * 为了避免这种情况,客户端接收到conn消息之后,需要先向DAEMON端发送一个控制 
     * 消息,打通DAEMON端的数据传输接口 
     */

    return;
}
예제 #22
0
int main(int argc, char* argv[])
{
    int lsocket = -1;   //侦听套接字 
    int dsocket = -1;   //连接套接字

    ushort mix_socket[2];
    memset(mix_socket, 0, sizeof(mix_socket));
 
 	P_EPOLL_STRUCT p_epoll = NULL;

    char buf[4096];
    int cnt = 0;
    int ready = 0;

    // STAGE1, build local listen
    EXIT_IF_TRUE ( (lsocket = st_buildsocket(10, SERV_PORT)) == -1);
    st_make_nonblock(lsocket);

    EXIT_IF_TRUE( (p_epoll = st_make_events(lsocket, 64)) == NULL);
	
    st_print("SERVER prepared OK!\n");

    int e_i = 0;

    while (TRUE)
    {
        ready = epoll_wait(p_epoll->event_fd, p_epoll->p_events, 64, 5000 /*5s*/);

        if (ready == -1) 
        {
            SYS_ABORT("EPOLL_WAIT ERROR!\n");
        }

        if( ready == 0)
        {
            st_print("PROCESS ALIVE!\n");
            continue;
        }

        for (e_i = 0; e_i < ready; ++e_i) 
        {
            if( (p_epoll->p_events[e_i].events & EPOLLERR) )            
            {
                st_d_error("Epoll Error!\n");
                close(p_epoll->p_events[e_i].data.fd);
                continue;
            }
            
            if ( ( p_epoll->p_events[e_i].events & EPOLLHUP ) ||
                 ( p_epoll->p_events[e_i].events & EPOLLRDHUP) )
            {
                st_d_error("Remote Disconnected!\n");
                close(p_epoll->p_events[e_i].data.fd);
                continue;
            }

            if (p_epoll->p_events[e_i].data.fd == lsocket) 
            {
                struct sockaddr in_addr;
                socklen_t in_len;

                dsocket = accept(lsocket,
                               (struct sockaddr *) &in_addr, &in_len);
                if (dsocket == -1) 
                {
                   st_d_error("accept lsocket error!\n");
                   continue;
                }

               	st_make_nonblock(dsocket);
                if (st_add_new_event(dsocket, p_epoll))
                {
                    st_d_error("Add socket:%d to event error!\n", dsocket);
                    close(dsocket);
                    dsocket = -1;   //INVALID
                    break;
                }

                st_print("Server accept new socket:%d\n", dsocket);

                if(mix_socket[0] == 0)
                	mix_socket[0] = dsocket;
                else
                	mix_socket[1] = dsocket;
           } 
           else     //数据转发部分
           {
                if(p_epoll->p_events[e_i].data.fd == mix_socket[0])
                {
                    memset(buf, 0, sizeof(buf)); 
                    cnt = recv(mix_socket[0], buf, sizeof(buf), 0);
                    if (cnt > 0)
                    {
                    	//write(1, buf, cnt);
                        send(mix_socket[1], buf, cnt, 0);
                    }   
                    continue;
                }
                else if(p_epoll->p_events[e_i].data.fd == mix_socket[1])
                {
                    memset(buf, 0, sizeof(buf));   
                    cnt = recv(mix_socket[1], buf, sizeof(buf), 0);
                    if (cnt > 0)
                    {
                    	//write(1, buf, cnt);
                        send(mix_socket[0], buf, cnt, 0);
                    }
                    continue;
                }
           }
       }
    }

    st_print("PROCESS TERMINATED!\n");

    return 0;
}
예제 #23
0
/*  main function takes a PLATYPUS source file as
 *  an argument at the command line.
 *  usage: platy source_file_name [-stz size][-sts:A | -sts:D]
 */    
int main(int argc, char ** argv){

	FILE *fi;       /* input file handle */	
        int loadsize = 0; /*the size of the file loaded in the buffer */
        int st_def_size = ST_DEF_SIZE; /* Sumbol Table default size */
        char sort_st = 0;      /*Symbol Table sort switch */
        int ansi_c = !ANSI_C; /* ANSI C flag */
/* Check if the compiler option is set to compile ANSI C */
/* __DATE__, __TIME__, __LINE__, __FILE__, __STDC__ are predefined preprocessor macros*/
  if(ansi_c){
    err_printf("Date: %s  Time: %s",__DATE__, __TIME__);
    err_printf("ERROR: Compiler is not ANSI C compliant!\n");
    exit(1);
  }

/*check for correct arrguments - source file name */
      if (argc <= 1){
/* __DATE__, __TIME__, __LINE__, __FILE__ are predefined preprocessor macros*/
       err_printf("Date: %s  Time: %s",__DATE__, __TIME__);
       err_printf("Runtime error at line %d in file %s", __LINE__, __FILE__);
       err_printf("%s%s%s",argv[0],": ","Missing source file name.");
       err_printf("%s%s%s","Usage: ", "platy", "  source_file_name [-stz size][-sts:A | -sts:D]");
        exit(EXIT_FAILURE);
	}	

 /* check for optional switches - symbol table size and/or sort */
 if (argc == 3){
    if (strcmp(argv[2],"-sts:A") && strcmp(argv[2],"-sts:D") ){
      err_printf("%s%s%s",argv[0],": ","Invalid switch.");
      err_printf("%s%s\b\b\b\b%s","Usage: ", argv[0], " source file name [-stz size][-sts:A | -sts:D]");
      exit(EXIT_FAILURE);
    }
    if(strcmp(argv[2],"-sts:A"))
     sort_st = 'D';
    else 
     sort_st = 'A';
 }
/* symbol table size specified */ 
 if (argc == 4){
   if (strcmp(argv[2],"-stz")){
     err_printf("%s%s%s",argv[0],": ","Invalid switch.");
     err_printf("%s%s\b\b\b\b%s","Usage: ", argv[0], " source file name [-stz size][-sts:A | -sts:D]");
     exit(EXIT_FAILURE);
   }
/* convert the symbol table size */
    st_def_size = atoi(argv[3]);
      if (st_def_size <= 0){
	err_printf("%s%s%s",argv[0],": ","Invalid switch.");
	err_printf("%s%s\b\b\b\b%s","Usage: ", argv[0], " source file name [-stz size][-sts:A | -sts:D]");
	exit(EXIT_FAILURE);
      }
 }
if (argc == 5){  
    if (strcmp(argv[2],"-stz")){
     err_printf("%s%s%s",argv[0],": ","Invalid switch.");
     err_printf("%s%s\b\b\b\b%s","Usage: ", argv[0], " source file name [-stz size][-sts:A | -sts:D]");
     exit(EXIT_FAILURE);
   }
/* convert the symbol table size */
    st_def_size = atoi(argv[3]);
      if (st_def_size <= 0){
	err_printf("%s%s%s",argv[0],": ","Invalid switch.");
	err_printf("%s%s\b\b\b\b%s","Usage: ", argv[0], " source file name [-stz size][-sts:A | -sts:D]");
	exit(EXIT_FAILURE);
   }
    
    if (strcmp(argv[4],"-sts:A")&& strcmp(argv[4],"-sts:D") ){
      err_printf("%s%s%s",argv[0],": ","Invalid switch.");
      err_printf("%s%s\b\b\b\b%s","Usage: ", argv[0], " source file name [-stz size][-sts:A | -sts:D]");
      exit(EXIT_FAILURE);
    }
   if(strcmp(argv[4],"-sts:A"))
     sort_st = 'D';
    else 
     sort_st = 'A';
 }
/* create a source code input buffer - multiplicative mode */	
	sc_buf = b_create(INIT_CAPACITY,INC_FACTOR,'m');
	if (sc_buf == NULL){
	  err_printf("%s%s%s",argv[0],": ","Could not create source buffer");
	  exit(EXIT_FAILURE);
	}

/* create symbol table */
  sym_table = st_create(st_def_size);
  if (!sym_table.st_size){
    err_printf("%s%s%s",argv[0],": ","Could not create symbol table");
    exit (EXIT_FAILURE);
  }

/*open source file */
	if ((fi = fopen(argv[1],"r")) == NULL){
		err_printf("%s%s%s%s",argv[0],": ", "Cannot open file: ",argv[1]);
		exit (1);
	}
/* load source file into input buffer  */
     printf("Reading file %s ....Please wait\n",argv[1]);
     loadsize = ca_load (fi,sc_buf);
     if(loadsize == R_FAIL_1)
       err_printf("%s%s%s",argv[0],": ","Error in loading buffer.");

/* close source file */	
 	fclose(fi);
/*find the size of the file  */
    if (loadsize == LOAD_FAIL){
     printf("The input file %s %s\n", argv[1],"is not completely loaded.");
     printf("Input file size: %ld\n", get_filesize(argv[1]));
    }
/* pack and display the source buffer */

       if(ca_pack(sc_buf)){
         display(sc_buf);
  }
/* create string Literal Table */
  str_LTBL = b_create(INIT_CAPACITY,INC_FACTOR,'a');
	if (str_LTBL == NULL){
		err_printf("%s%s%s",argv[0],": ","Could not create string buffer");
		exit(EXIT_FAILURE);
	}

/*registrer exit function */	
 atexit(garbage_collect);
	
/*Testbed for buffer, scanner,symbol table and parser*/

/* Initialize scanner input buffer  
	scanner_init(sc_buf);
*/        
        line = 1;
        ca_addc(sc_buf, EOF);
        printf("\nParsing the source file...\n\n");
	
        parser(sc_buf);
        
/* print Symbol Table */      
        if(sym_table.st_size && sort_st){   
           st_print(sym_table);
         if(sort_st){
           printf("\nSorting symbol table...\n");
           st_sort(sym_table,sort_st);
           st_print(sym_table);
         }
       }
       
	return (EXIT_SUCCESS); /* same effect as exit(0) */
}/*end of main */
예제 #24
0
bool_t check_string_print(void) {

	uint64_t total;
	bool_t result = true;
	stringer_t *strings[14];

	mm_set(strings, 0, sizeof(strings));

	strings[0] = st_print(NULLER_T | CONTIGUOUS | HEAP, "%.*s", st_length_int(constant), st_char_get(constant));
	strings[1] = st_print(NULLER_T | JOINTED | HEAP, "%.*s", st_length_int(strings[0]), st_char_get(strings[0]));
	strings[2] = st_print(BLOCK_T | CONTIGUOUS | HEAP, "%.*s", st_length_int(strings[1]), st_char_get(strings[1]));
	strings[3] = st_print(BLOCK_T | JOINTED | HEAP, "%.*s", st_length_int(strings[2]), st_char_get(strings[2]));
	strings[4] = st_print(MANAGED_T | CONTIGUOUS | HEAP, "%.*s", st_length_int(strings[3]), st_char_get(strings[3]));
	strings[5] = st_print(MANAGED_T | JOINTED | HEAP, "%.*s", st_length_int(strings[4]), st_char_get(strings[4]));
	strings[6] = st_print(MAPPED_T | JOINTED | HEAP, "%.*s", st_length_int(strings[5]), st_char_get(strings[5]));

	strings[7] = st_print(NULLER_T | CONTIGUOUS | SECURE, "%.*s", st_length_int(strings[6]), st_char_get(strings[6]));
	strings[8] = st_print(NULLER_T | JOINTED | SECURE, "%.*s", st_length_int(strings[7]), st_char_get(strings[7]));
	strings[9] = st_print(BLOCK_T | CONTIGUOUS | SECURE, "%.*s", st_length_int(strings[8]), st_char_get(strings[8]));
	strings[10] = st_print(BLOCK_T | JOINTED | SECURE, "%.*s", st_length_int(strings[9]), st_char_get(strings[9]));
	strings[11] = st_print(MANAGED_T | CONTIGUOUS | SECURE, "%.*s", st_length_int(strings[10]), st_char_get(strings[10]));
	strings[12] = st_print(MANAGED_T | JOINTED | SECURE, "%.*s", st_length_int(strings[11]), st_char_get(strings[11]));
	strings[13] = st_print(MAPPED_T | JOINTED | SECURE, "%.*s", st_length_int(strings[12]), st_char_get(strings[12]));

	for (int i = 0; i < 14 && strings[i]; i++) {
		for (unsigned int j = total = 0; strings[i] && j < st_length_get(strings[i]); j++) {
			total += *(st_char_get(strings[i]) + j);
		}

		if (total != 5366) {
			result = false;
		}
	}

	log_print("%28.28s = %s", "print", result ? "passed" : "failed");

	for (int i = 0; i < 14; i++) {
		if (strings[i])
			st_free(strings[i]);
	}

	return result;

}
예제 #25
0
void st_event_loop(P_EPOLL_STRUCT p_epoll, P_ST_THREAD_MANAGE p_manage, void* handler(void* data))
{
    if (!p_epoll)
        return;
    struct epoll_event* p_events = p_epoll->p_events;
    int listen_socket = p_epoll->event.data.fd;

    int e_i = 0;
    int ready = 0;

    for ( ; ; )
    {
        ready = epoll_wait(p_epoll->event_fd, p_events, p_epoll->max_events, -1); 
        for (e_i = 0; e_i < ready; e_i++)
        {
			if( (p_epoll->p_events[e_i].events & EPOLLERR) )			
            {
                st_d_print("Epoll Error!\n");
                close(p_epoll->p_events[e_i].data.fd);
                continue;
            }
			
			if ( ( p_epoll->p_events[e_i].events & EPOLLHUP ) ||
				 ( p_epoll->p_events[e_i].events & EPOLLRDHUP) )
			{
				st_d_print("Remote Disconnected!\n");
                close(p_epoll->p_events[e_i].data.fd);
				continue;
			}
            
            if (listen_socket == p_events[e_i].data.fd)
            {
                 /* 新链接到了(可能会有多个连接同时到来) */
                while (1)
                {
                    struct sockaddr in_addr;
                    socklen_t in_len;
                    int infd;
                    char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

                    in_len = sizeof(struct sockaddr);
                    infd = accept (listen_socket, &in_addr, &in_len); //非阻塞的Socket
                    if (infd == -1)
                        break;

                    int sk = getnameinfo (&in_addr, in_len,
                                       hbuf, sizeof(hbuf),
                                       sbuf, sizeof(sbuf),
                                       NI_NUMERICHOST | NI_NUMERICSERV);
                    if (sk == 0)
                    {
                        st_print("Accept NEW Connect:[%d} "
                                 "(host=%s, port=%s)\n", infd, hbuf, sbuf);
                    }

                    if (st_add_new_event(infd, p_epoll))
                    {
                        st_print("Add socket:%d to event error!\n", infd);
                        break;
                    }

                    continue;       //可能有多个连接
                }
            }
            else
            {
                //有侦听的套接字发送数据的请求,添加你的处理
                if (p_manage && handler)
                {
                    st_threadpool_push_task(p_manage, handler, (void *)p_events[e_i].data.fd);  //传值调用简单些!
                }
#if 0
                while (1)
                {
                    ssize_t count;
                    char buf[512];

                    count = read (p_events[e_i].data.fd, buf, sizeof(buf));
                    if (count == -1)
                    {
                        /* If errno == EAGAIN, that means we have read all
                         data. So go back to the main loop. */
                        if (errno != EAGAIN)
                        {
                            perror ("read");
                            done = 1;
                        }

                        break;
                    }
                    else if (count == 0)
                    {
                      /* End of file. The remote has closed the
                         connection. */
                      done = 1;
                      break;
                    }

                    /* Write the buffer to standard output */
                    int s = write (1, buf, count);
                    if (s == -1)
                    {
                        perror ("write");
                        abort ();
                    }
                }

                if (done)
                {
                    printf ("Closed connection on descriptor %d\n",
                          p_events[e_i].data.fd);

                    /* Closing the descriptor will make epoll remove it
                     from the set of descriptors which are monitored. */
                    close (p_events[e_i].data.fd);
                }
#endif
            }
        }
    }
}
예제 #26
0
void* st_shm_open(const char* share_name, int fixaddr, int writable)
{
    P_ST_SHM_T p_token = NULL;
    mode_t	mode = 0;
    int	    flag = 0;
	int map_flag = 0;
	FILE*     fp = NULL;
    char rw_buf[512];
	char path_buf[PATH_MAX];

    mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
    if (writable)
    {
        flag = O_RDWR ; 
        map_flag = PROT_READ | PROT_WRITE;
    }
    else
    {
        flag = O_RDONLY;
        map_flag = PROT_READ;
    }
	
	p_token = (P_ST_SHM_T)malloc(sizeof(ST_SHM_T));
    if (! p_token)
        return NULL;
    
	memset(p_token, 0, sizeof(ST_SHM_T));
    p_token->location = NULL;
    p_token->fd = -1;
    p_token->size = 0;
    // For compatible
	if(share_name[0] != '/')
	{
		p_token->shmname[0] = '/';
		strncpy(p_token->shmname + 1, share_name, NAME_MAX);
	}
	else
	{
		strncpy(p_token->shmname, share_name, NAME_MAX);
	}
	
	p_token->fd = shm_open(p_token->shmname, flag, mode);
	if( p_token->fd < 0)
	{
		perror("Create shm_open failed!");
		goto failed;
	}
	
    snprintf(path_buf, PATH_MAX, "%s/%s", ST_SHM_PREFIX, share_name);
    if((fp = fopen(path_buf, "r")))
    {
        rewind(fp);
        fscanf(fp,"ADDR:%p,SIZE:%u\n", &p_token->location,
               &p_token->size);
        fclose(fp);
        st_d_print("MAPINFO ADDR:%p,SIZE:%u\n", p_token->location,
               p_token->size);
    }
	else
	{
		st_print("Open shm info failed with %s\n", path_buf);
		goto failed;
	}


    if (fixaddr)
        p_token->location = mmap(p_token->location, p_token->size,
                      map_flag,
                      MAP_SHARED | MAP_FIXED, p_token->fd, 0);
    else
        p_token->location = mmap(NULL, p_token->size,
                      map_flag,
                      MAP_SHARED, p_token->fd, 0);

    if ((void *)p_token->location == (void *)MAP_FAILED)
    {
        perror("Call mmap failed:\n");
        goto failed;
    }

    return p_token;

failed:
    free(p_token);
    return NULL;
}
예제 #27
0
// POSIX要求的共享名字必须是  /sharename  < NAME_MAX
//
void* st_shm_create(const char* share_name, size_t max_size)
{
	char path_buf[PATH_MAX];
	P_ST_SHM_T p_token = NULL;
	FILE* fp = NULL;
	char    rw_buf[512];
	
    if (!share_name)
        return NULL;
	
    p_token = (P_ST_SHM_T)malloc(sizeof(ST_SHM_T));
    if (! p_token)
    {
        return NULL;
    }
	
	if ( access(ST_SHM_PREFIX, W_OK) != 0)
        mkdir(ST_SHM_PREFIX, 0777);

	// Additional
	shm_unlink(share_name);

    memset(p_token, 0, sizeof(ST_SHM_T));
	p_token->location = NULL;
    p_token->fd = -1;
    p_token->size = max_size;
	
	// For compatible
	if(share_name[0] != '/')
	{
		p_token->shmname[0] = '/';
		strncpy(p_token->shmname + 1, share_name, NAME_MAX);
	}
	else
	{
		strncpy(p_token->shmname, share_name, NAME_MAX);
	}

	p_token->fd = shm_open(p_token->shmname, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, 
		S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
	if( p_token->fd < 0)
	{
		perror("Create shm_open failed!");
		goto failed;
	}
    
    if( ftruncate(p_token->fd, max_size) == -1)
	{
		perror("ftruncate share mem failed!");
		goto failed;
	}

    p_token->location = mmap( NULL, p_token->size,
                      PROT_READ | PROT_WRITE,
                      MAP_SHARED, p_token->fd, 0);
    if ((void *)p_token->location == (void *)MAP_FAILED)
    {
        st_print("Call mmap failed:%s\n", p_token->shmname);
        goto failed;
    }
		
	//Store the address in mapfile for referenec
    strncpy(path_buf, ST_SHM_PREFIX, PATH_MAX);
    strncat(path_buf, p_token->shmname, NAME_MAX);
	if ( access(ST_SHM_PREFIX, W_OK) == 0)
	{
		st_d_print("shm file exists, delete it anyway!\n");
		remove(path_buf);
	}
	
    if((fp = fopen(path_buf, "w")))
    {
        snprintf(rw_buf, sizeof(rw_buf), "ADDR:%p,SIZE:%u\n", p_token->location, 
                 p_token->size);
        fwrite(rw_buf, strlen(rw_buf)+1, 1, fp);
        fclose(fp);
    }

    st_d_print("ShareName:%s,\t Location:%p,\t MapSize:%u\n", 
               p_token->shmname, p_token->location, p_token->size);
		   
    return p_token;
     
failed:
    free(p_token);
    return NULL;
}
예제 #28
0
void st_mutex_test_intra(void)
{
    P_ST_MEMMAP_T p_token = NULL;
    p_token = st_memmap_create(NULL, "RPC_SHARE", 4096);
    char* ptr = p_token->location;
    *ptr = '\0';
    char buf[512];

    if (!p_token)
        return;

    P_ST_WINSYNC_T p_mutex = (P_ST_WINSYNC_T)CreateMutex(NULL, 0, "RPC_MUTEX");
    
    int i = 0, nloop = 10;
    lseek(p_token->fd, 0, SEEK_SET);


    if (fork() == 0) 
    { /* child process*/
        //虽然系统保证sem_t是共享位置,但是由于其它部分没有存放到共享地址,所以父子进程不能
        //共享匿名Mutex...
        p_mutex = (P_ST_WINSYNC_T)OpenMutex(0, 0, "RPC_MUTEX");

        pthread_t pid;
        p_mutex->extra = p_token;
        pthread_create(&pid, NULL,mutex_thread, p_mutex);

        for (i = 0; i < nloop; i++) 
        {
            WaitForSingleObject(p_mutex, INFINITE);
            st_print("C_LOCK\n");
            write(p_token->fd, "CCCCC", 5);
            usleep(500*1000);
            write(p_token->fd, "CCCCC", 5);
            st_print("C_UNLOCK\n");
            ReleaseMutex(p_mutex);
            usleep(400*1000);
        }

        pthread_join(pid, NULL);

        CloseHandle(p_mutex);
        st_memmap_close(p_token);

        exit(0);
    }

    /* back to parent process */
    for (i = 0; i < nloop; i++) 
    {
        WaitForSingleObject(p_mutex, INFINITE);
        st_print("P_LOCK\n");
        write(p_token->fd, "PPPPP", 5);
        usleep(400*1000);
        write(p_token->fd, "PPPPP", 5);
        st_print("P_UNLOCK\n");
        ReleaseMutex(p_mutex);
        usleep(500*1000);
    }

    wait(NULL);
    
    lseek(p_token->fd, 0, SEEK_SET);
    int sz = read(p_token->fd, buf, 512);
    buf[sz] = '\0';
    st_print("INFO(%d):%s\n",strlen(buf),buf);

    st_memmap_close(p_token);
    st_memmap_destroy(p_token);
    CloseHandle(p_mutex);
    st_winsync_destroy(p_mutex);

}
예제 #29
0
void test02 ( )

/******************************************************************************/
/*
  Purpose:

    TEST02 tests ST_TO_CC on a matrix stored in a file.

  Discussion:

    We assume no prior knowledge about the matrix except the filename.

  Licensing:

    This code is distributed under the GNU LGPL license.

  Modified:

    23 July 2014

  Author:

    John Burkardt
*/
{
  double *acc;
  double *ast;
  int *ccc;
  char filename_st[] = "west_st.txt";
  int i_max;
  int i_min;
  int *icc;
  int *ist;
  int j_max;
  int j_min;
  int *jst;
  int m;
  int n;
  int ncc;
  int nst;

  printf ( "\n" );
  printf ( "TEST02\n" );
  printf ( "  Convert a sparse matrix from ST to CC format.\n" );
  printf ( "  ST: sparse triplet,    I, J,  A.\n" );
  printf ( "  CC: compressed column, I, CC, A.\n" );
  printf ( "  This matrix is read from the file '%s'\n", filename_st );
/*
  Get the size of the ST matrix.
*/
  st_header_read ( filename_st, &i_min, &i_max, &j_min, &j_max, &m, &n, &nst );

  st_header_print ( i_min, i_max, j_min, j_max, m, n, nst );
/*
  Allocate space.
*/
  ist = ( int * ) malloc ( nst * sizeof ( int ) );
  jst = ( int * ) malloc ( nst * sizeof ( int ) );
  ast = ( double * ) malloc ( nst * sizeof ( double ) );
/*
  Read the ST matrix.
*/
  st_data_read ( filename_st, m, n, nst, ist, jst, ast );
/*
  Decrement the 1-based data.
*/
  i4vec_dec ( nst, ist );
  i4vec_dec ( nst, jst );
/*
  Print the ST matrix.
*/
  st_print ( m, n, nst, ist, jst, ast, "  The matrix in ST format:" );
/*
  Get the CC size.
*/
  ncc = st_to_cc_size ( nst, ist, jst );

  printf ( "\n" );
  printf ( "  Number of CC values = %d\n", ncc );
/*
  Create the CC indices.
*/
  icc = ( int * ) malloc ( ncc * sizeof ( int ) );
  ccc = ( int * ) malloc ( ( n + 1 ) * sizeof ( int ) );

  st_to_cc_index ( nst, ist, jst, ncc, n, icc, ccc );
/*
  Create the CC values.
*/
  acc = st_to_cc_values ( nst, ist, jst, ast, ncc, n, icc, ccc );
/*
  Print the CC matrix.
*/
  cc_print ( m, n, ncc, icc, ccc, acc, "  CC Matrix:" );
/*
  Free memory.
*/
  free ( acc );
  free ( ast );
  free ( ccc );
  free ( icc );
  free ( ist );
  free ( jst );

  return;
}
예제 #30
0
void test01 ( )

/******************************************************************************/
/*
  Purpose:

    TEST01 tests ST_TO_CC using a tiny matrix.

  Discussion:

    This test uses a trivial matrix whose full representation is:

          2  3  0  0  0
          3  0  4  0  6
      A = 0 -1 -3  2  0
          0  0  1  0  0
          0  4  2  0  1

    A (1-based) ST representation, reading in order by rows is:

      I  J   A
     -- --  --
      1  1   2
      1  2   3

      2  1   3
      2  3   4
      2  5   6

      3  2  -1
      3  3  -3
      3  4   2

      4  3   1

      5  2   4
      5  3   2
      5  5   1

    The CC representation (which goes in order by columns) is

      #   I  JC   A
     --  --  --  --
      1   1   1   2
      2   2       3

      3   1   3   3
      4   3      -1
      5   5       4

      6   2   6   4
      7   3      -3
      8   4       1
      9   5       2

     10   3  10   2

     11   2  11   6
     12   5       1

     13   *  13

  Licensing:

    This code is distributed under the GNU LGPL license.

  Modified:

    23 July 2014

  Author:

    John Burkardt
*/
{
# define NST 12

  double *acc;
  double ast[NST] = {
    2.0,  3.0, 
    3.0,  4.0,  6.0, 
   -1.0, -3.0,  2.0, 
    1.0, 
    4.0,  2.0,  1.0 };
  int *ccc;
  int i_max;
  int i_min;
  int *icc;
  int ist[NST] = {
    1, 1, 
    2, 2, 2, 
    3, 3, 3, 
    4, 
    5, 5, 5 };
  int j_max;
  int j_min;
  int jst[NST] = {
    1, 2, 
    1, 3, 5, 
    2, 3, 4, 
    3, 
    2, 3, 5 };
  int m = 5;
  int n = 5;
  int ncc;
  int nst = NST;

  printf ( "\n" );
  printf ( "TEST01\n" );
  printf ( "  Convert a sparse matrix from ST to CC format.\n" );
  printf ( "  ST: sparse triplet,    I, J,  A.\n" );
  printf ( "  CC: compressed column, I, CC, A.\n" );

  i_min = i4vec_min ( nst, ist );
  i_max = i4vec_max ( nst, ist );
  j_min = i4vec_min ( nst, jst );
  j_max = i4vec_max ( nst, jst );

  st_header_print ( i_min, i_max, j_min, j_max, m, n, nst );
/*
  Decrement the 1-based data.
*/
  i4vec_dec ( nst, ist );
  i4vec_dec ( nst, jst );
/*
  Print the ST matrix.
*/
  st_print ( m, n, nst, ist, jst, ast, "  The matrix in ST format:" );
/*
  Get the CC size.
*/
  ncc = st_to_cc_size ( nst, ist, jst );

  printf ( "\n" );
  printf ( "  Number of CC values = %d\n", ncc );
/*
  Create the CC indices.
*/
  icc = ( int * ) malloc ( ncc * sizeof ( int ) );
  ccc = ( int * ) malloc ( ( n + 1 ) * sizeof ( int ) );

  st_to_cc_index ( nst, ist, jst, ncc, n, icc, ccc );
/*
  Create the CC values.
*/
  acc = st_to_cc_values ( nst, ist, jst, ast, ncc, n, icc, ccc );
/*
  Print the CC matrix.
*/
  cc_print ( m, n, ncc, icc, ccc, acc, "  CC Matrix:" );
/*
  Free memory.
*/
  free ( acc );
  free ( ccc );
  free ( icc );

  return;
# undef NST
}