c++多线程,程序运行一段时间后主线程还在正常运行,但是子线程自动挂掉了,求解

时间:2023-02-21 22:12:15
一个简单的udp通信程序,在线程中给服务端发指令,收数据。但是程序运行了10多个小时后,子线程就挂掉了,实在是不知道原因,求大虾指教啊

7 个解决方案

#1


下面附上代码
#include <WinSock2.h>
#include <time.h>
#include <Windows.h>
#include <tchar.h>
#include <process.h>
#include <iostream>

using namespace std;

#pragma comment(lib,"ws2_32.lib")
char g_szLogFile[1024];
CRITICAL_SECTION g_lock;

int WriteToLog(char* str)
{
printf("debug info = %s \n",str);
FILE* log;
log = fopen(g_szLogFile, "a+");
if (log == NULL)
return -1;

fseek(log,0,SEEK_END);
LONG64 size = ftell(log);
fseek(log,0,SEEK_SET);

if (size > 1024*1024*50)
{
fclose(log);

log = fopen(g_szLogFile, "w");
if (log == NULL)
return -1;
}
time_t t = time(0);
char tmp[64] = {0 };
strftime(tmp, sizeof(tmp), "%Y/%m/%d %X %A ", localtime(&t));

fprintf(log, "%s:%s\n", tmp,str);
fclose(log);
return 0;
}

typedef struct __INFO
{
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;
char path[1024];
}Info;


void run(void* param)
{
Info* pInfo = (Info *)param;

SOCKET m_sendsock = pInfo->m_sendsock;
SOCKET m_recvsock = pInfo->m_recvsock;
SOCKADDR_IN m_addrServer = pInfo->m_addrServer;
char sendBuf[10] ;
int ret = 0;
SOCKADDR_IN saClient;

char cRecvBuff[50] = {0};
int nSize = sizeof (SOCKADDR_IN);
int nbSize = 0;
int iValue = 0;
char t[50];
memset(sendBuf,0,sizeof(sendBuf));

strcpy(sendBuf,"M4S00");


ret = connect(m_sendsock,(struct sockaddr *)&m_addrServer,sizeof(m_addrServer));

if (ret != 0)
{
char buf[1200]= { 0};
sprintf (buf," 对方服务器关闭,connect error  ret = %d",ret);
EnterCriticalSection(&g_lock);
WriteToLog(buf);
LeaveCriticalSection(&g_lock);
return ;
}

if ( strlen(sendBuf) != sendto(m_sendsock, sendBuf, strlen(sendBuf),0, (SOCKADDR*)&m_addrServer, sizeof(SOCKADDR)))
{
EnterCriticalSection(&g_lock);
WriteToLog(" sendto 失败");
LeaveCriticalSection(&g_lock);

return ;
}
memset(&saClient,0,sizeof(saClient));
//char cRecvBuff[800] = {0};
memset(cRecvBuff,0,sizeof(cRecvBuff));
    nSize = sizeof (SOCKADDR_IN);

//WriteToLog(" recvfrom wait");
    nbSize=recvfrom (m_recvsock,cRecvBuff,800,0,(SOCKADDR FAR *) &saClient,&nSize); //若接收失败则提示错误
//WriteToLog(" recvfrom end");

if (nbSize <=0 )
{
EnterCriticalSection(&g_lock);
WriteToLog("recvfrom error");
LeaveCriticalSection(&g_lock);

return ;
}

    iValue = 0;
if( cRecvBuff[10] & 0x01) //10
{
iValue = 1;
}
//char t[256];
memset(t,0,sizeof(t));
sprintf(t, "%d", iValue);
EnterCriticalSection(&g_lock);
::WritePrivateProfileString(TEXT("ACE"), TEXT("Value"),t, pInfo->path);
LeaveCriticalSection(&g_lock);
  Sleep(1000);
}

void pthread(void* param)
{
int count = 0;
EnterCriticalSection(&g_lock);
WriteToLog("服务开启成功");
LeaveCriticalSection(&g_lock);
while (1)
{
Sleep(1000);
run(param);
count++;
if (count%300 == 0)
{
EnterCriticalSection(&g_lock);
WriteToLog("运行了10分钟");
LeaveCriticalSection(&g_lock);
count = 0;
}
}
EnterCriticalSection(&g_lock);
WriteToLog("线程死掉");
LeaveCriticalSection(&g_lock);

}

int main(void)
{
int m_iPort;
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;


char szFilePath[MAX_PATH + 1]={0};  
GetModuleFileNameA(NULL, szFilePath, MAX_PATH);  
(strrchr(szFilePath, '\\'))[0] = 0; // 删除文件名,只获得路径字串  
string path = szFilePath; 
path += "\\configure.ini";

GetPrivateProfileString(_T("CONFIGURE"), _T("LOGFILE "),NULL, g_szLogFile, sizeof(g_szLogFile),path.c_str());
char szport[50] = {};
char szip[50]={};
char szpath[50] ={};
GetPrivateProfileString(_T("CONFIGURE"), _T("PORT "),NULL, szport, sizeof(szport),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("IP "),NULL, szip, sizeof(szip),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("Path"),NULL, szpath, sizeof(szpath),path.c_str());

char buf[1024]= {0};
sprintf(buf,"读取的配置路径: %s",szFilePath);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的对方服务器ip: %s",szip);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的自己的配置端口号: %s",szport);
WriteToLog(buf);

m_iPort = atoi(szport);

WSADATA wsaData;   //指向WinSocket信息结构的指针
if(WSAStartup(MAKEWORD(1,1), &wsaData)!=0)//进行WinSocket的初始化
{
WSACleanup();
}

if( ( m_sendsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}

if( ( m_recvsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(m_iPort);             
sin.sin_addr.s_addr = htonl(INADDR_ANY);


int val = 1;

if(setsockopt(m_recvsock,SOL_SOCKET,SO_REUSEADDR,(char*)&val,sizeof(val)) != 0)
{

WriteToLog(" setsockopt error");
return -1;
}

if( bind(m_recvsock, (SOCKADDR FAR *)&sin, sizeof(sin)) == -1)
{
WriteToLog(" 绑定失败");
return -1;
}
//bind(m_sendsock, (SOCKADDR FAR *)&sin, sizeof(sin));     //???
m_addrServer.sin_family = AF_INET;
m_addrServer.sin_addr.s_addr = inet_addr(szip);
m_addrServer.sin_port = htons(18003);

Info param;
memset(&param,0,sizeof(param));

param.m_addrServer = m_addrServer;
param.m_recvsock = m_recvsock;
param.m_sendsock = m_sendsock;
strcpy(param.path,path.c_str());

InitializeCriticalSection(&g_lock);
HANDLE hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
long nCode = STILL_ACTIVE;
while(1)
{
Sleep(2000);
if(true != GetExitCodeThread(hThrd,(LPDWORD)&nCode))
{
EnterCriticalSection(&g_lock);
WriteToLog("GetExitCodeThread error");
LeaveCriticalSection(&g_lock);
MessageBox(NULL,TEXT("程序开启出错,请重新开启"),TEXT("ERROR"),MB_OK);
break;
}
else
{
if (nCode != STILL_ACTIVE )
{
while (hThrd != NULL)
{
   CloseHandle(hThrd);
   EnterCriticalSection(&g_lock);
   WriteToLog("清除上个线程空间");
   LeaveCriticalSection(&g_lock);
}
  nCode = STILL_ACTIVE;
  hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
  EnterCriticalSection(&g_lock);
  WriteToLog("重新开启线程");
  LeaveCriticalSection(&g_lock);

}
}
}

return 0;
}

							     

#2


#include <WinSock2.h>
#include <time.h>
#include <Windows.h>
#include <tchar.h>
#include <process.h>
#include <iostream>

using namespace std;

#pragma comment(lib,"ws2_32.lib")
char g_szLogFile[1024];
CRITICAL_SECTION g_lock;

int WriteToLog(char* str)
{
printf("debug info = %s \n",str);
FILE* log;
log = fopen(g_szLogFile, "a+");
if (log == NULL)
return -1;

fseek(log,0,SEEK_END);
LONG64 size = ftell(log);
fseek(log,0,SEEK_SET);

if (size > 1024*1024*50)
{
fclose(log);

log = fopen(g_szLogFile, "w");
if (log == NULL)
return -1;
}
time_t t = time(0);
char tmp[64] = {0 };
strftime(tmp, sizeof(tmp), "%Y/%m/%d %X %A ", localtime(&t));

fprintf(log, "%s:%s\n", tmp,str);
fclose(log);
return 0;
}

typedef struct __INFO
{
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;
char path[1024];
}Info;


void run(void* param)
{
Info* pInfo = (Info *)param;

SOCKET m_sendsock = pInfo->m_sendsock;
SOCKET m_recvsock = pInfo->m_recvsock;
SOCKADDR_IN m_addrServer = pInfo->m_addrServer;
char sendBuf[10] ;
int ret = 0;
SOCKADDR_IN saClient;

char cRecvBuff[50] = {0};
int nSize = sizeof (SOCKADDR_IN);
int nbSize = 0;
int iValue = 0;
char t[50];
memset(sendBuf,0,sizeof(sendBuf));

strcpy(sendBuf,"M4S00");


ret = connect(m_sendsock,(struct sockaddr *)&m_addrServer,sizeof(m_addrServer));

if (ret != 0)
{
char buf[1200]= { 0};
sprintf (buf," 对方服务器关闭,connect error  ret = %d",ret);
EnterCriticalSection(&g_lock);
WriteToLog(buf);
LeaveCriticalSection(&g_lock);
return ;
}

if ( strlen(sendBuf) != sendto(m_sendsock, sendBuf, strlen(sendBuf),0, (SOCKADDR*)&m_addrServer, sizeof(SOCKADDR)))
{
EnterCriticalSection(&g_lock);
WriteToLog(" sendto 失败");
LeaveCriticalSection(&g_lock);

return ;
}
memset(&saClient,0,sizeof(saClient));
//char cRecvBuff[800] = {0};
memset(cRecvBuff,0,sizeof(cRecvBuff));
    nSize = sizeof (SOCKADDR_IN);

//WriteToLog(" recvfrom wait");
    nbSize=recvfrom (m_recvsock,cRecvBuff,800,0,(SOCKADDR FAR *) &saClient,&nSize); //若接收失败则提示错误
//WriteToLog(" recvfrom end");

if (nbSize <=0 )
{
EnterCriticalSection(&g_lock);
WriteToLog("recvfrom error");
LeaveCriticalSection(&g_lock);

return ;
}

    iValue = 0;
if( cRecvBuff[10] & 0x01) //10
{
iValue = 1;
}
//char t[256];
memset(t,0,sizeof(t));
sprintf(t, "%d", iValue);
EnterCriticalSection(&g_lock);
::WritePrivateProfileString(TEXT("ACE"), TEXT("Value"),t, pInfo->path);
LeaveCriticalSection(&g_lock);
  Sleep(1000);
}

void pthread(void* param)
{
int count = 0;
EnterCriticalSection(&g_lock);
WriteToLog("服务开启成功");
LeaveCriticalSection(&g_lock);
while (1)
{
Sleep(1000);
run(param);
count++;
if (count%300 == 0)
{
EnterCriticalSection(&g_lock);
WriteToLog("运行了10分钟");
LeaveCriticalSection(&g_lock);
count = 0;
}
}
EnterCriticalSection(&g_lock);
WriteToLog("线程死掉");
LeaveCriticalSection(&g_lock);

}

int main(void)
{
int m_iPort;
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;


char szFilePath[MAX_PATH + 1]={0};  
GetModuleFileNameA(NULL, szFilePath, MAX_PATH);  
(strrchr(szFilePath, '\\'))[0] = 0; // 删除文件名,只获得路径字串  
string path = szFilePath; 
path += "\\configure.ini";

GetPrivateProfileString(_T("CONFIGURE"), _T("LOGFILE "),NULL, g_szLogFile, sizeof(g_szLogFile),path.c_str());
char szport[50] = {};
char szip[50]={};
char szpath[50] ={};
GetPrivateProfileString(_T("CONFIGURE"), _T("PORT "),NULL, szport, sizeof(szport),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("IP "),NULL, szip, sizeof(szip),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("Path"),NULL, szpath, sizeof(szpath),path.c_str());

char buf[1024]= {0};
sprintf(buf,"读取的配置路径: %s",szFilePath);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的对方服务器ip: %s",szip);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的自己的配置端口号: %s",szport);
WriteToLog(buf);

m_iPort = atoi(szport);

WSADATA wsaData;   //指向WinSocket信息结构的指针
if(WSAStartup(MAKEWORD(1,1), &wsaData)!=0)//进行WinSocket的初始化
{
WSACleanup();
}

if( ( m_sendsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}

if( ( m_recvsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(m_iPort);             
sin.sin_addr.s_addr = htonl(INADDR_ANY);


int val = 1;

if(setsockopt(m_recvsock,SOL_SOCKET,SO_REUSEADDR,(char*)&val,sizeof(val)) != 0)
{

WriteToLog(" setsockopt error");
return -1;
}

if( bind(m_recvsock, (SOCKADDR FAR *)&sin, sizeof(sin)) == -1)
{
WriteToLog(" 绑定失败");
return -1;
}
//bind(m_sendsock, (SOCKADDR FAR *)&sin, sizeof(sin));     //???
m_addrServer.sin_family = AF_INET;
m_addrServer.sin_addr.s_addr = inet_addr(szip);
m_addrServer.sin_port = htons(18003);

Info param;
memset(&param,0,sizeof(param));

param.m_addrServer = m_addrServer;
param.m_recvsock = m_recvsock;
param.m_sendsock = m_sendsock;
strcpy(param.path,path.c_str());

InitializeCriticalSection(&g_lock);
HANDLE hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
long nCode = STILL_ACTIVE;
while(1)
{
Sleep(2000);
if(true != GetExitCodeThread(hThrd,(LPDWORD)&nCode))
{
EnterCriticalSection(&g_lock);
WriteToLog("GetExitCodeThread error");
LeaveCriticalSection(&g_lock);
MessageBox(NULL,TEXT("程序开启出错,请重新开启"),TEXT("ERROR"),MB_OK);
break;
}
else
{
if (nCode != STILL_ACTIVE )
{
while (hThrd != NULL)
{
   CloseHandle(hThrd);
   EnterCriticalSection(&g_lock);
   WriteToLog("清除上个线程空间");
   LeaveCriticalSection(&g_lock);
}
  nCode = STILL_ACTIVE;
  hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
  EnterCriticalSection(&g_lock);
  WriteToLog("重新开启线程");
  LeaveCriticalSection(&g_lock);

}
}
}

return 0;
}

#3


来人啊 !!!!!!! c++多线程,程序运行一段时间后主线程还在正常运行,但是子线程自动挂掉了,求解

#4


c++多线程,程序运行一段时间后主线程还在正常运行,但是子线程自动挂掉了,求解
回去看log吧。。。

#5


while (hThrd != NULL)
{
   CloseHandle(hThrd);
   EnterCriticalSection(&g_lock);
   WriteToLog("清除上个线程空间");
   LeaveCriticalSection(&g_lock);
}


你这个while什么意思?你后面CloseHandle了,但是并不一定这个hThrd就成为NULL了吧,而且一般没有显示的hThrd = NULL,这个值还是原始的值,也就是类似野指针了……

#6


有时不将“调用函数名字+各参数值,进入函数后各参数值,中间变量值,退出函数前准备返回的值,返回函数到调用处后函数名字+各参数值+返回值”这些信息写日志到文件中是无论如何也发现不了问题在哪里的,包括捕获各种异常、写日志到屏幕、单步或设断点或生成core文件、……这些方法都不行! 写日志到文件参考下面:
仅供参考:
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#ifdef WIN32
    #pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
    #include <windows.h>
    #include <process.h>
    #include <io.h>
    #define  MYVOID             void
    #define  vsnprintf          _vsnprintf
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  MYVOID             void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef WIN32
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
    Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
    usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;

    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
#define ASIZE    200
#define BSIZE    240
#define CSIZE      2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
    int  head;
    int  tail;
    int  size;
    char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
    int i,j,k;
    char binstr[80];

    Lock(&cs_HEX);
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%03d %04x -",cn,i);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
            }
            Log("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
        }
        Log("%s\n",binstr);
    }
    Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    lent=0;
    Lock(cs);
    if (fbuf->size>=len) {
        lent=len;
        if (fbuf->head+lent>BSIZE) {
            len1=BSIZE-fbuf->head;
            memcpy(buf     ,fbuf->data+fbuf->head,len1);
            len2=lent-len1;
            memcpy(buf+len1,fbuf->data           ,len2);
            fbuf->head=len2;
        } else {
            memcpy(buf     ,fbuf->data+fbuf->head,lent);
            fbuf->head+=lent;
        }
        fbuf->size-=lent;
    }
    Unlock(cs);
    return lent;
}
MYVOID thdB(void *pcn) {
    char        *recv_buf;
    int          recv_nbytes;
    int          cn;
    int          wc;
    int          pb;

    cn=(int)pcn;
    Log("%03d thdB              thread begin...\n",cn);
    while (1) {
        sleep_ms(10);
        recv_buf=(char *)Cbuf;
        recv_nbytes=CSIZE;
        wc=0;
        while (1) {
            pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
            if (pb) {
                Log("%03d recv %d bytes\n",cn,pb);
                HexDump(cn,recv_buf,pb);
                sleep_ms(1);
            } else {
                sleep_ms(1000);
            }
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef WIN32
    pthread_exit(NULL);
#endif
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    Lock(cs);
    lent=len;
    if (fbuf->size+lent>BSIZE) {
        lent=BSIZE-fbuf->size;
    }
    if (fbuf->tail+lent>BSIZE) {
        len1=BSIZE-fbuf->tail;
        memcpy(fbuf->data+fbuf->tail,buf     ,len1);
        len2=lent-len1;
        memcpy(fbuf->data           ,buf+len1,len2);
        fbuf->tail=len2;
    } else {
        memcpy(fbuf->data+fbuf->tail,buf     ,lent);
        fbuf->tail+=lent;
    }
    fbuf->size+=lent;
    Unlock(cs);
    return lent;
}
MYVOID thdA(void *pcn) {
    char        *send_buf;
    int          send_nbytes;
    int          cn;
    int          wc;
    int           a;
    int          pa;

    cn=(int)pcn;
    Log("%03d thdA              thread begin...\n",cn);
    a=0;
    while (1) {
        sleep_ms(100);
        memset(Abuf,a,ASIZE);
        a=(a+1)%256;
        if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
        send_buf=(char *)Abuf;
        send_nbytes=ASIZE;
        Log("%03d sending %d bytes\n",cn,send_nbytes);
        HexDump(cn,send_buf,send_nbytes);
        wc=0;
        while (1) {
            pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
            Log("%03d sent %d bytes\n",cn,pa);
            HexDump(cn,send_buf,pa);
            send_buf+=pa;
            send_nbytes-=pa;
            if (send_nbytes<=0) break;//
            sleep_ms(1000);
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef WIN32
    pthread_exit(NULL);
#endif
}
int main() {
#ifdef WIN32
    InitializeCriticalSection(&cs_log);
    InitializeCriticalSection(&cs_HEX );
    InitializeCriticalSection(&cs_BBB );
#else
    pthread_t threads[2];
    int threadsN;
    int rc;
    pthread_mutex_init(&cs_log,NULL);
    pthread_mutex_init(&cs_HEX,NULL);
    pthread_mutex_init(&cs_BBB,NULL);
#endif
    Log("Start===========================================================\n");

    BBB.head=0;
    BBB.tail=0;
    BBB.size=0;

#ifdef WIN32
    _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
    _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
#else
    threadsN=0;
    rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
    rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
#endif

    if (!access("No_Loop",0)) {
        remove("No_Loop");
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    while (1) {
        sleep_ms(1000);
        if (No_Loop) break;//
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    sleep_ms(3000);
    Log("End=============================================================\n");
#ifdef WIN32
    DeleteCriticalSection(&cs_BBB );
    DeleteCriticalSection(&cs_HEX );
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_BBB);
    pthread_mutex_destroy(&cs_HEX);
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}

#7


char cRecvBuff[50] = {0};
nbSize=recvfrom (m_recvsock,cRecvBuff,800,0,(SOCKADDR FAR *) &saClient,&nSize); //若接收失败则提示错误


缓冲区才50,你要收800~不知道你想干嘛.....

#1


下面附上代码
#include <WinSock2.h>
#include <time.h>
#include <Windows.h>
#include <tchar.h>
#include <process.h>
#include <iostream>

using namespace std;

#pragma comment(lib,"ws2_32.lib")
char g_szLogFile[1024];
CRITICAL_SECTION g_lock;

int WriteToLog(char* str)
{
printf("debug info = %s \n",str);
FILE* log;
log = fopen(g_szLogFile, "a+");
if (log == NULL)
return -1;

fseek(log,0,SEEK_END);
LONG64 size = ftell(log);
fseek(log,0,SEEK_SET);

if (size > 1024*1024*50)
{
fclose(log);

log = fopen(g_szLogFile, "w");
if (log == NULL)
return -1;
}
time_t t = time(0);
char tmp[64] = {0 };
strftime(tmp, sizeof(tmp), "%Y/%m/%d %X %A ", localtime(&t));

fprintf(log, "%s:%s\n", tmp,str);
fclose(log);
return 0;
}

typedef struct __INFO
{
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;
char path[1024];
}Info;


void run(void* param)
{
Info* pInfo = (Info *)param;

SOCKET m_sendsock = pInfo->m_sendsock;
SOCKET m_recvsock = pInfo->m_recvsock;
SOCKADDR_IN m_addrServer = pInfo->m_addrServer;
char sendBuf[10] ;
int ret = 0;
SOCKADDR_IN saClient;

char cRecvBuff[50] = {0};
int nSize = sizeof (SOCKADDR_IN);
int nbSize = 0;
int iValue = 0;
char t[50];
memset(sendBuf,0,sizeof(sendBuf));

strcpy(sendBuf,"M4S00");


ret = connect(m_sendsock,(struct sockaddr *)&m_addrServer,sizeof(m_addrServer));

if (ret != 0)
{
char buf[1200]= { 0};
sprintf (buf," 对方服务器关闭,connect error  ret = %d",ret);
EnterCriticalSection(&g_lock);
WriteToLog(buf);
LeaveCriticalSection(&g_lock);
return ;
}

if ( strlen(sendBuf) != sendto(m_sendsock, sendBuf, strlen(sendBuf),0, (SOCKADDR*)&m_addrServer, sizeof(SOCKADDR)))
{
EnterCriticalSection(&g_lock);
WriteToLog(" sendto 失败");
LeaveCriticalSection(&g_lock);

return ;
}
memset(&saClient,0,sizeof(saClient));
//char cRecvBuff[800] = {0};
memset(cRecvBuff,0,sizeof(cRecvBuff));
    nSize = sizeof (SOCKADDR_IN);

//WriteToLog(" recvfrom wait");
    nbSize=recvfrom (m_recvsock,cRecvBuff,800,0,(SOCKADDR FAR *) &saClient,&nSize); //若接收失败则提示错误
//WriteToLog(" recvfrom end");

if (nbSize <=0 )
{
EnterCriticalSection(&g_lock);
WriteToLog("recvfrom error");
LeaveCriticalSection(&g_lock);

return ;
}

    iValue = 0;
if( cRecvBuff[10] & 0x01) //10
{
iValue = 1;
}
//char t[256];
memset(t,0,sizeof(t));
sprintf(t, "%d", iValue);
EnterCriticalSection(&g_lock);
::WritePrivateProfileString(TEXT("ACE"), TEXT("Value"),t, pInfo->path);
LeaveCriticalSection(&g_lock);
  Sleep(1000);
}

void pthread(void* param)
{
int count = 0;
EnterCriticalSection(&g_lock);
WriteToLog("服务开启成功");
LeaveCriticalSection(&g_lock);
while (1)
{
Sleep(1000);
run(param);
count++;
if (count%300 == 0)
{
EnterCriticalSection(&g_lock);
WriteToLog("运行了10分钟");
LeaveCriticalSection(&g_lock);
count = 0;
}
}
EnterCriticalSection(&g_lock);
WriteToLog("线程死掉");
LeaveCriticalSection(&g_lock);

}

int main(void)
{
int m_iPort;
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;


char szFilePath[MAX_PATH + 1]={0};  
GetModuleFileNameA(NULL, szFilePath, MAX_PATH);  
(strrchr(szFilePath, '\\'))[0] = 0; // 删除文件名,只获得路径字串  
string path = szFilePath; 
path += "\\configure.ini";

GetPrivateProfileString(_T("CONFIGURE"), _T("LOGFILE "),NULL, g_szLogFile, sizeof(g_szLogFile),path.c_str());
char szport[50] = {};
char szip[50]={};
char szpath[50] ={};
GetPrivateProfileString(_T("CONFIGURE"), _T("PORT "),NULL, szport, sizeof(szport),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("IP "),NULL, szip, sizeof(szip),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("Path"),NULL, szpath, sizeof(szpath),path.c_str());

char buf[1024]= {0};
sprintf(buf,"读取的配置路径: %s",szFilePath);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的对方服务器ip: %s",szip);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的自己的配置端口号: %s",szport);
WriteToLog(buf);

m_iPort = atoi(szport);

WSADATA wsaData;   //指向WinSocket信息结构的指针
if(WSAStartup(MAKEWORD(1,1), &wsaData)!=0)//进行WinSocket的初始化
{
WSACleanup();
}

if( ( m_sendsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}

if( ( m_recvsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(m_iPort);             
sin.sin_addr.s_addr = htonl(INADDR_ANY);


int val = 1;

if(setsockopt(m_recvsock,SOL_SOCKET,SO_REUSEADDR,(char*)&val,sizeof(val)) != 0)
{

WriteToLog(" setsockopt error");
return -1;
}

if( bind(m_recvsock, (SOCKADDR FAR *)&sin, sizeof(sin)) == -1)
{
WriteToLog(" 绑定失败");
return -1;
}
//bind(m_sendsock, (SOCKADDR FAR *)&sin, sizeof(sin));     //???
m_addrServer.sin_family = AF_INET;
m_addrServer.sin_addr.s_addr = inet_addr(szip);
m_addrServer.sin_port = htons(18003);

Info param;
memset(&param,0,sizeof(param));

param.m_addrServer = m_addrServer;
param.m_recvsock = m_recvsock;
param.m_sendsock = m_sendsock;
strcpy(param.path,path.c_str());

InitializeCriticalSection(&g_lock);
HANDLE hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
long nCode = STILL_ACTIVE;
while(1)
{
Sleep(2000);
if(true != GetExitCodeThread(hThrd,(LPDWORD)&nCode))
{
EnterCriticalSection(&g_lock);
WriteToLog("GetExitCodeThread error");
LeaveCriticalSection(&g_lock);
MessageBox(NULL,TEXT("程序开启出错,请重新开启"),TEXT("ERROR"),MB_OK);
break;
}
else
{
if (nCode != STILL_ACTIVE )
{
while (hThrd != NULL)
{
   CloseHandle(hThrd);
   EnterCriticalSection(&g_lock);
   WriteToLog("清除上个线程空间");
   LeaveCriticalSection(&g_lock);
}
  nCode = STILL_ACTIVE;
  hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
  EnterCriticalSection(&g_lock);
  WriteToLog("重新开启线程");
  LeaveCriticalSection(&g_lock);

}
}
}

return 0;
}

							     

#2


#include <WinSock2.h>
#include <time.h>
#include <Windows.h>
#include <tchar.h>
#include <process.h>
#include <iostream>

using namespace std;

#pragma comment(lib,"ws2_32.lib")
char g_szLogFile[1024];
CRITICAL_SECTION g_lock;

int WriteToLog(char* str)
{
printf("debug info = %s \n",str);
FILE* log;
log = fopen(g_szLogFile, "a+");
if (log == NULL)
return -1;

fseek(log,0,SEEK_END);
LONG64 size = ftell(log);
fseek(log,0,SEEK_SET);

if (size > 1024*1024*50)
{
fclose(log);

log = fopen(g_szLogFile, "w");
if (log == NULL)
return -1;
}
time_t t = time(0);
char tmp[64] = {0 };
strftime(tmp, sizeof(tmp), "%Y/%m/%d %X %A ", localtime(&t));

fprintf(log, "%s:%s\n", tmp,str);
fclose(log);
return 0;
}

typedef struct __INFO
{
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;
char path[1024];
}Info;


void run(void* param)
{
Info* pInfo = (Info *)param;

SOCKET m_sendsock = pInfo->m_sendsock;
SOCKET m_recvsock = pInfo->m_recvsock;
SOCKADDR_IN m_addrServer = pInfo->m_addrServer;
char sendBuf[10] ;
int ret = 0;
SOCKADDR_IN saClient;

char cRecvBuff[50] = {0};
int nSize = sizeof (SOCKADDR_IN);
int nbSize = 0;
int iValue = 0;
char t[50];
memset(sendBuf,0,sizeof(sendBuf));

strcpy(sendBuf,"M4S00");


ret = connect(m_sendsock,(struct sockaddr *)&m_addrServer,sizeof(m_addrServer));

if (ret != 0)
{
char buf[1200]= { 0};
sprintf (buf," 对方服务器关闭,connect error  ret = %d",ret);
EnterCriticalSection(&g_lock);
WriteToLog(buf);
LeaveCriticalSection(&g_lock);
return ;
}

if ( strlen(sendBuf) != sendto(m_sendsock, sendBuf, strlen(sendBuf),0, (SOCKADDR*)&m_addrServer, sizeof(SOCKADDR)))
{
EnterCriticalSection(&g_lock);
WriteToLog(" sendto 失败");
LeaveCriticalSection(&g_lock);

return ;
}
memset(&saClient,0,sizeof(saClient));
//char cRecvBuff[800] = {0};
memset(cRecvBuff,0,sizeof(cRecvBuff));
    nSize = sizeof (SOCKADDR_IN);

//WriteToLog(" recvfrom wait");
    nbSize=recvfrom (m_recvsock,cRecvBuff,800,0,(SOCKADDR FAR *) &saClient,&nSize); //若接收失败则提示错误
//WriteToLog(" recvfrom end");

if (nbSize <=0 )
{
EnterCriticalSection(&g_lock);
WriteToLog("recvfrom error");
LeaveCriticalSection(&g_lock);

return ;
}

    iValue = 0;
if( cRecvBuff[10] & 0x01) //10
{
iValue = 1;
}
//char t[256];
memset(t,0,sizeof(t));
sprintf(t, "%d", iValue);
EnterCriticalSection(&g_lock);
::WritePrivateProfileString(TEXT("ACE"), TEXT("Value"),t, pInfo->path);
LeaveCriticalSection(&g_lock);
  Sleep(1000);
}

void pthread(void* param)
{
int count = 0;
EnterCriticalSection(&g_lock);
WriteToLog("服务开启成功");
LeaveCriticalSection(&g_lock);
while (1)
{
Sleep(1000);
run(param);
count++;
if (count%300 == 0)
{
EnterCriticalSection(&g_lock);
WriteToLog("运行了10分钟");
LeaveCriticalSection(&g_lock);
count = 0;
}
}
EnterCriticalSection(&g_lock);
WriteToLog("线程死掉");
LeaveCriticalSection(&g_lock);

}

int main(void)
{
int m_iPort;
SOCKET m_sendsock;
SOCKET m_recvsock;
SOCKADDR_IN m_addrServer;


char szFilePath[MAX_PATH + 1]={0};  
GetModuleFileNameA(NULL, szFilePath, MAX_PATH);  
(strrchr(szFilePath, '\\'))[0] = 0; // 删除文件名,只获得路径字串  
string path = szFilePath; 
path += "\\configure.ini";

GetPrivateProfileString(_T("CONFIGURE"), _T("LOGFILE "),NULL, g_szLogFile, sizeof(g_szLogFile),path.c_str());
char szport[50] = {};
char szip[50]={};
char szpath[50] ={};
GetPrivateProfileString(_T("CONFIGURE"), _T("PORT "),NULL, szport, sizeof(szport),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("IP "),NULL, szip, sizeof(szip),path.c_str());
GetPrivateProfileString(_T("CONFIGURE"), _T("Path"),NULL, szpath, sizeof(szpath),path.c_str());

char buf[1024]= {0};
sprintf(buf,"读取的配置路径: %s",szFilePath);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的对方服务器ip: %s",szip);
WriteToLog(buf);

memset(buf,0,sizeof(buf));
sprintf(buf,"读取的自己的配置端口号: %s",szport);
WriteToLog(buf);

m_iPort = atoi(szport);

WSADATA wsaData;   //指向WinSocket信息结构的指针
if(WSAStartup(MAKEWORD(1,1), &wsaData)!=0)//进行WinSocket的初始化
{
WSACleanup();
}

if( ( m_sendsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}

if( ( m_recvsock = socket(AF_INET, SOCK_DGRAM, 0) ) == INVALID_SOCKET )
{
WriteToLog( "创建套接字失败!" );
WSACleanup( );
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(m_iPort);             
sin.sin_addr.s_addr = htonl(INADDR_ANY);


int val = 1;

if(setsockopt(m_recvsock,SOL_SOCKET,SO_REUSEADDR,(char*)&val,sizeof(val)) != 0)
{

WriteToLog(" setsockopt error");
return -1;
}

if( bind(m_recvsock, (SOCKADDR FAR *)&sin, sizeof(sin)) == -1)
{
WriteToLog(" 绑定失败");
return -1;
}
//bind(m_sendsock, (SOCKADDR FAR *)&sin, sizeof(sin));     //???
m_addrServer.sin_family = AF_INET;
m_addrServer.sin_addr.s_addr = inet_addr(szip);
m_addrServer.sin_port = htons(18003);

Info param;
memset(&param,0,sizeof(param));

param.m_addrServer = m_addrServer;
param.m_recvsock = m_recvsock;
param.m_sendsock = m_sendsock;
strcpy(param.path,path.c_str());

InitializeCriticalSection(&g_lock);
HANDLE hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
long nCode = STILL_ACTIVE;
while(1)
{
Sleep(2000);
if(true != GetExitCodeThread(hThrd,(LPDWORD)&nCode))
{
EnterCriticalSection(&g_lock);
WriteToLog("GetExitCodeThread error");
LeaveCriticalSection(&g_lock);
MessageBox(NULL,TEXT("程序开启出错,请重新开启"),TEXT("ERROR"),MB_OK);
break;
}
else
{
if (nCode != STILL_ACTIVE )
{
while (hThrd != NULL)
{
   CloseHandle(hThrd);
   EnterCriticalSection(&g_lock);
   WriteToLog("清除上个线程空间");
   LeaveCriticalSection(&g_lock);
}
  nCode = STILL_ACTIVE;
  hThrd = (HANDLE)_beginthread(pthread,0,(void*)&param);
  EnterCriticalSection(&g_lock);
  WriteToLog("重新开启线程");
  LeaveCriticalSection(&g_lock);

}
}
}

return 0;
}

#3


来人啊 !!!!!!! c++多线程,程序运行一段时间后主线程还在正常运行,但是子线程自动挂掉了,求解

#4


c++多线程,程序运行一段时间后主线程还在正常运行,但是子线程自动挂掉了,求解
回去看log吧。。。

#5


while (hThrd != NULL)
{
   CloseHandle(hThrd);
   EnterCriticalSection(&g_lock);
   WriteToLog("清除上个线程空间");
   LeaveCriticalSection(&g_lock);
}


你这个while什么意思?你后面CloseHandle了,但是并不一定这个hThrd就成为NULL了吧,而且一般没有显示的hThrd = NULL,这个值还是原始的值,也就是类似野指针了……

#6


有时不将“调用函数名字+各参数值,进入函数后各参数值,中间变量值,退出函数前准备返回的值,返回函数到调用处后函数名字+各参数值+返回值”这些信息写日志到文件中是无论如何也发现不了问题在哪里的,包括捕获各种异常、写日志到屏幕、单步或设断点或生成core文件、……这些方法都不行! 写日志到文件参考下面:
仅供参考:
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#ifdef WIN32
    #pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
    #include <windows.h>
    #include <process.h>
    #include <io.h>
    #define  MYVOID             void
    #define  vsnprintf          _vsnprintf
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  MYVOID             void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef WIN32
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
    Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
    usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;

    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
#define ASIZE    200
#define BSIZE    240
#define CSIZE      2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
    int  head;
    int  tail;
    int  size;
    char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
    int i,j,k;
    char binstr[80];

    Lock(&cs_HEX);
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%03d %04x -",cn,i);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
            }
            Log("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
        }
        Log("%s\n",binstr);
    }
    Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    lent=0;
    Lock(cs);
    if (fbuf->size>=len) {
        lent=len;
        if (fbuf->head+lent>BSIZE) {
            len1=BSIZE-fbuf->head;
            memcpy(buf     ,fbuf->data+fbuf->head,len1);
            len2=lent-len1;
            memcpy(buf+len1,fbuf->data           ,len2);
            fbuf->head=len2;
        } else {
            memcpy(buf     ,fbuf->data+fbuf->head,lent);
            fbuf->head+=lent;
        }
        fbuf->size-=lent;
    }
    Unlock(cs);
    return lent;
}
MYVOID thdB(void *pcn) {
    char        *recv_buf;
    int          recv_nbytes;
    int          cn;
    int          wc;
    int          pb;

    cn=(int)pcn;
    Log("%03d thdB              thread begin...\n",cn);
    while (1) {
        sleep_ms(10);
        recv_buf=(char *)Cbuf;
        recv_nbytes=CSIZE;
        wc=0;
        while (1) {
            pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
            if (pb) {
                Log("%03d recv %d bytes\n",cn,pb);
                HexDump(cn,recv_buf,pb);
                sleep_ms(1);
            } else {
                sleep_ms(1000);
            }
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef WIN32
    pthread_exit(NULL);
#endif
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    Lock(cs);
    lent=len;
    if (fbuf->size+lent>BSIZE) {
        lent=BSIZE-fbuf->size;
    }
    if (fbuf->tail+lent>BSIZE) {
        len1=BSIZE-fbuf->tail;
        memcpy(fbuf->data+fbuf->tail,buf     ,len1);
        len2=lent-len1;
        memcpy(fbuf->data           ,buf+len1,len2);
        fbuf->tail=len2;
    } else {
        memcpy(fbuf->data+fbuf->tail,buf     ,lent);
        fbuf->tail+=lent;
    }
    fbuf->size+=lent;
    Unlock(cs);
    return lent;
}
MYVOID thdA(void *pcn) {
    char        *send_buf;
    int          send_nbytes;
    int          cn;
    int          wc;
    int           a;
    int          pa;

    cn=(int)pcn;
    Log("%03d thdA              thread begin...\n",cn);
    a=0;
    while (1) {
        sleep_ms(100);
        memset(Abuf,a,ASIZE);
        a=(a+1)%256;
        if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
        send_buf=(char *)Abuf;
        send_nbytes=ASIZE;
        Log("%03d sending %d bytes\n",cn,send_nbytes);
        HexDump(cn,send_buf,send_nbytes);
        wc=0;
        while (1) {
            pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
            Log("%03d sent %d bytes\n",cn,pa);
            HexDump(cn,send_buf,pa);
            send_buf+=pa;
            send_nbytes-=pa;
            if (send_nbytes<=0) break;//
            sleep_ms(1000);
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef WIN32
    pthread_exit(NULL);
#endif
}
int main() {
#ifdef WIN32
    InitializeCriticalSection(&cs_log);
    InitializeCriticalSection(&cs_HEX );
    InitializeCriticalSection(&cs_BBB );
#else
    pthread_t threads[2];
    int threadsN;
    int rc;
    pthread_mutex_init(&cs_log,NULL);
    pthread_mutex_init(&cs_HEX,NULL);
    pthread_mutex_init(&cs_BBB,NULL);
#endif
    Log("Start===========================================================\n");

    BBB.head=0;
    BBB.tail=0;
    BBB.size=0;

#ifdef WIN32
    _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
    _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
#else
    threadsN=0;
    rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
    rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
#endif

    if (!access("No_Loop",0)) {
        remove("No_Loop");
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    while (1) {
        sleep_ms(1000);
        if (No_Loop) break;//
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    sleep_ms(3000);
    Log("End=============================================================\n");
#ifdef WIN32
    DeleteCriticalSection(&cs_BBB );
    DeleteCriticalSection(&cs_HEX );
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_BBB);
    pthread_mutex_destroy(&cs_HEX);
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}

#7


char cRecvBuff[50] = {0};
nbSize=recvfrom (m_recvsock,cRecvBuff,800,0,(SOCKADDR FAR *) &saClient,&nSize); //若接收失败则提示错误


缓冲区才50,你要收800~不知道你想干嘛.....