Mingw 编写c测试程序

1.线程和信号量

#include 
#include "stdio.h"
# include 
#include 
#include 
#include 
#include "pthread.h"
#include 
#include 
#include "error.h"

sem_t sem_g;

static void *threadWrite(void *arg){
    int count = 0;
    for(;;){
        _sleep(1000);
        printf("write data %d\n",count++);
        _sleep(1000);
        sem_post(&sem_g);
    }
}

void onctrlc(int arg){
    printf("ctrl-c \n");
}

static void *threadRead(void *arg){
    struct timespec ts;
    int count=0;

    for(;;){
        clock_gettime( CLOCK_REALTIME,&ts );
        ts.tv_sec  += 1; //wait 1 second
        int err = sem_timedwait(&sem_g,&ts);
         if(err==0){
            printf("read sem ok %d \n",count++);
        }else{
             if(errno == ETIMEDOUT)
                printf("read timeout\n");
             else
                printf("read error %d \n",err);
        }
        _sleep(5);
    }
}

extern int sockServer();

int main() {
    //signal(SIGINT,onctrlc);
    pthread_t tidRead,tidWrite;
    //sockServer();
    sem_init(&sem_g,0,0);
    pthread_create(&tidRead,NULL,threadRead,NULL);
    pthread_create(&tidRead,NULL,threadWrite,NULL);
    for(;;){
        _sleep(1000);
    }
}

2.socket

//
// Created by wxynj on 2020/5/19.
//

#include 
#include 
#include 
#include   

#define DESIRED_ADDRESS "0.0.0.0"
#define DESIRED_PORT 3500
#define BUFSIZE 512

int sockServer(){
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(DESIRED_PORT);
    addr.sin_addr.s_addr = inet_addr(DESIRED_ADDRESS);
    WSADATA wsaData;

    if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
    {
        printf("Failed to load Winsock.\n"); //Winsock 初始化错误
        return -1;
    }

    int sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == -1) {
        perror("Socket creation error");
        return EXIT_FAILURE;
    }
    if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) == -1) {
        perror("Bind error");
        close(sock);
        return EXIT_FAILURE;
    }

    struct sockaddr_in addrclient = {0};
    char buf[BUFSIZE];
    int addrlen = sizeof(addrclient);

    int readden = recvfrom(sock,buf,1024,0,(sockaddr *)&addrclient,&addrlen);
    if (readden > 0) {
        printf("Client with IP %s sent datagram\n", inet_ntoa(addrclient.sin_addr));
        write (STDOUT_FILENO, buf, readden);
    }
    sendto(sock, "hello", 5, 0, (sockaddr*)&addrclient, sizeof(addrclient));

}

cmakelists.txt

cmake_minimum_required(VERSION 3.16)
project(third)
set(CMAKE_CXX_STANDARD 14)
add_executable(third main.cpp udptest.cpp)
LINK_DIRECTORIES(X:/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib)
target_link_libraries(third libws2_32.a)

测试:

root@xxxxx:~# nc -u 10.1.3.41 3500
ddd
hello
 

 

你可能感兴趣的:(Mingw 编写c测试程序)