高分跪求串口问题:createfile 返回错误5 拒绝访问
程序频繁初始化串口。程序运行一段时间都正常。但是过一段时间后createfile()返回 INVALID_HANDLE_VALUE 用GetLastError()得到错误号为5 拒绝访问。不知道是什么原因。是不是createfile()过于频繁的原因。跪求大牛解答
初始化串口程序为
初始化串口程序如下:(没有加入收发缓冲区初始化以及清空操作是因为已经在另外的函数中完成一次.不需要频繁操作)
BOOL CSerialPort::InitPort_Send(CWnd* pPortOwner, // the owner (CWnd) of the port (receives message)
UINT portnr, // portnumber (1..4)
UINT baud, // baudrate
char parity, // parity
UINT databits, // databits
UINT stopbits, // stopbits
DWORD dwCommEvents, // EV_RXCHAR, EV_CTS etc
UINT writebuffersize) // size to the writebuffer
{
//AfxMessageBox( "INIT ");
m_pOwner = pPortOwner;
m_nPortNr = portnr;
m_dwCommEvents = dwCommEvents;
BOOL bResult = FALSE;
char *szPort = new char[50];
char *szBaud = new char[50];
EnterCriticalSection(&m_csCommunicationSync);
// if the port is already opened: close it
if (m_hComm != NULL)
{
CloseHandle(m_hComm);
m_hComm = NULL;
}
Sleep(0);
// prepare port strings
sprintf(szPort, "COM%d ", portnr);
sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d ", baud, parity, databits, stopbits);
// get a handle to the port
m_hComm = CreateFile(szPort,
GENERIC_READ ¦ GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
if (m_hComm == INVALID_HANDLE_VALUE)
{
// port not found
DWORD dwError = GetLastError();
delete [] szPort;
delete [] szBaud;
LeaveCriticalSection(&m_csCommunicationSync);
Flag_stop = TRUE;
return FALSE;
}
// set the timeout values
m_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
m_CommTimeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
m_CommTimeouts.ReadTotalTimeoutConstant = 20;
m_CommTimeouts.WriteTotalTimeoutMultiplier = 1000;
m_CommTimeouts.WriteTotalTimeoutConstant = 1000;
// configure
if (SetCommTimeouts(m_hComm, &m_CommTimeouts))
{
if (SetCommMask(m_hComm, dwCommEvents))
{
if (GetCommState(m_hComm, &m_dcb))
{
m_dcb.EvtChar = 'q ';
m_dcb.fRtsControl = RTS_CONTROL_ENABLE; // set RTS bit high!
if (BuildCommDCB(szBaud, &m_dcb))
{
if (SetCommState(m_hComm, &m_dcb)) ; // normal operation... continue
else
ProcessErrorMessage( "SetCommState() ");
}
else
ProcessErrorMessage( "BuildCommDCB() ");
}
else
ProcessErrorMessage( "GetCommState() ");
}
else
ProcessErrorMessage( "SetCommMask() ");
}
else
ProcessErrorMessage( "SetCommTimeouts() ");
delete [] szPort;
delete [] szBaud;
// release critical section
LeaveCriticalSection(&m_csCommunicationSync);
TRACE( "Initialisation for communicationport %d completed.\nUse Startmonitor to communicate.\n ", portnr);
Flag_stop = FALSE;
return TRUE;
}