C++Builder Programming Forum
C++Builder  |  Delphi  |  FireMonkey  |  C/C++  |  Free Pascal  |  Firebird
볼랜드포럼 BorlandForum
 경고! 게시물 작성자의 사전 허락없는 메일주소 추출행위 절대 금지
C++빌더 포럼
Q & A
FAQ
팁&트릭
강좌/문서
자료실
컴포넌트/라이브러리
메신저 프로젝트
볼랜드포럼 홈
헤드라인 뉴스
IT 뉴스
공지사항
자유게시판
해피 브레이크
공동 프로젝트
구인/구직
회원 장터
건의사항
운영진 게시판
회원 메뉴
북마크
볼랜드포럼 광고 모집

C++빌더 Q&A
C++Builder Programming Q&A
[51376] Re:CPort-3.10 컴포넌트의 Close() 호출시 프로그램 다운 증상
최상천 [kangnung] 2501 읽음    2007-11-27 16:58
저도 모든 232통신은 CPort 컴포넌트를 사용합니다.

저도 이런 저런 경험을 많이 했는데 Indy는 써보지 않아 뭐라고 답해 드리기 뭐하네요.

첫째로, 일단 Indy를 쓰지 마시고 CPort 컴포넌트만 써 보세요.
이유는 Indy의 스레드 컴포넌트가 어떻게 동작하는지 정확하게 모르니까...
TThread와 별반 달라보이지 않는데 궂이 Indy를 쓰시는 목적은???

둘째는, 스레드1과 스레드2에서 동시에 통신을 시도하네요. 이와 같은 경우 거의 100% 동기를 맞추지 못할 겁니다.
두개의 스레드를 동시에 사용하는데 있어서 동기화는 필수 입니다. 더구나 기존의 Mutex, Critical Section, Semaphore 같은 것으로는 232통신의 동기화를 맞추지 못할 것입니다. 이와는 다른 방법으로 동기화를 구현해 보시길 바랍니다.

세째는, CPort의 SyncMethod를 smWindowSync로 설정해 보세요.

네째는, ProcessMessages Method는 타이머이벤트 핸들러 내에서는 사용해서는 안됩니다. --> 이건 보나스...

유산균 님이 쓰신 글 :
: 안녕하세요... 이곳에서 빌더에 대해 많은것을 항상 배워가는 유저입니다.
:
: PC와 개발 Board간에 Serial 통신 프로그램을 작성하게 되어 개발 도중... 문제가 발생하여 질문드립니다.
:
: 에러 상황은 Comport1->Closer() 호출시 가끔 try문에도 잡히지 않는 다운 증상이 나타납니다.
: 그때 해당 프로그램 CPU사용율을 보면 47%~50%(테스트 PC가 듀오여서 한쪽 CPU를 다 사용하는것으로 보입니다.)사용하며 동작하지 않습니다.
: 가만보니 무한루프에 빠져있어 보이네요 ^^;;
:
: 제가 몇가지 테스트 해본 결과는 다음과 같습니다.
:
: 1. Serial RX, TX가 없는 상황에서 Comport Open(), Close()는 100% 정상 동작합니다.
:
: 2. RX만 보내도 Tx만 보내도 아니면 둘다 다 보내더라도 가끔 Close시 다운 증상이 나타납니다.
:
: 3. Tx, Rx 보내는 딜레이를 빠르게 하면 할수록 다운 증상은 더 빨리 나타납니다.
:
: 4. 추적 결과 확실히 Comport1->Close(); 구문에서 잡혀 있습니다.
:
:
: 갑갑합니다. 뭔가 해결 방안이나 아니면 피해 갈수 있는 방법이 있는지 간절히 조언 부탁드립니다.
:
:
:
:
: 간단한 테스트 소스를 첨부하겟습니다.
: 테스트 환경은 PC는 Windows XP pro이고 Builder6.0에서 프로그래밍 했습니다. 사용 컴포넌트는 CPort-3.10과 Indy9.0의 Thread 컴포넌트를 사용했습니다.
:
: //##########################################
: //##########################################
: //######## unit1.h
: //##########################################
: //##########################################
: //---------------------------------------------------------------------------
:
: #ifndef Unit1H
: #define Unit1H
: //---------------------------------------------------------------------------
: #include <Classes.hpp>
: #include <Controls.hpp>
: #include <StdCtrls.hpp>
: #include <Forms.hpp>
: #include "CPort.hpp"
: #include "CPortCtl.hpp"
: #include "IdThreadComponent.hpp"
: #include <IdBaseComponent.hpp>
: //---------------------------------------------------------------------------
: class TForm1 : public TForm
: {
: __published:    // IDE-managed Components
:     TComPort *ComPort1;
:     TComComboBox *ComComboBox1;
:     TComComboBox *ComComboBox2;
:     TComLed *ComLed1;
:     TComLed *ComLed2;
:     TComLed *ComLed3;
:     TButton *Button1;
:     TLabel *Label1;
:     TLabel *Label2;
:     TLabel *Label3;
:     TListBox *Debug_ListBox;
:     TEdit *Edit1;
:     TButton *Button2;
:     TIdThreadComponent *IdThreadComponent1;
:     TIdThreadComponent *IdThreadComponent2;
:     TEdit *Edit2;
:     void __fastcall Button1Click(TObject *Sender);
:     void __fastcall Button2Click(TObject *Sender);
:     void __fastcall IdThreadComponent1Run(
:           TIdCustomThreadComponent *Sender);
:     void __fastcall IdThreadComponent2Run(
:           TIdCustomThreadComponent *Sender);
: private:    // User declarations
: public:        // User declarations
:     __fastcall TForm1(TComponent* Owner);
:
:     PAsync Serial_TX_AsyncPtr;
:     PAsync Serial_RX_AsyncPtr;
:
:     AnsiString DebugMsg;
:     void __fastcall DisplayDebugLog(void);
:
:
: };
: //---------------------------------------------------------------------------
: extern PACKAGE TForm1 *Form1;
: //---------------------------------------------------------------------------
: #endif
:
: //##########################################
: //##########################################
: //######## unit1.cpp
: //##########################################
: //##########################################
: //---------------------------------------------------------------------------
:
: #include <vcl.h>
: #pragma hdrstop
:
: #include "Unit1.h"
: //---------------------------------------------------------------------------
: #pragma package(smart_init)
: #pragma link "CPort"
: #pragma link "CPortCtl"
: #pragma link "IdThreadComponent"
: #pragma resource "*.dfm"
: TForm1 *Form1;
: //---------------------------------------------------------------------------
: __fastcall TForm1::TForm1(TComponent* Owner)
:     : TForm(Owner)
: {
:     InitAsync(Form1->Serial_RX_AsyncPtr);
:     InitAsync(Form1->Serial_TX_AsyncPtr);
: }
: //---------------------------------------------------------------------------
: #define MAX_DEBUG_LINE  100
: void __fastcall TForm1::DisplayDebugLog(void) {
:
:     try {
: #if 1
:         // ListBox GUI Update Stop
:         Form1->Debug_ListBox->Items->BeginUpdate();
:
:         int DelLineCnt =  Form1->Debug_ListBox->Count - (MAX_DEBUG_LINE-1) ;
:
:         // Delete Old line
:         if ( DelLineCnt > 0 )
:             while (DelLineCnt--)
:                 Form1->Debug_ListBox->Items->Delete(DelLineCnt);
:
:         // Display Message
:         Form1->Debug_ListBox->Items->Add(Form1->DebugMsg);
:         // Set Fource at Last Line
:         Form1->Debug_ListBox->ItemIndex = Form1->Debug_ListBox->Items->Count-1;
:
:         // ListBox GUI Update Start
:         Form1->Debug_ListBox->Items->EndUpdate();
: #endif
: #if 0
:         if ( Form1->CheckBox1->Checked ) {
:             FILE *out;
:             if((out=fopen(DebugFileName.c_str(),"at")) == NULL) {
:                 ShowMessage("Failed write to config file");
:                 return;
:             }
:             fputs(Form1->DebugMsg.c_str(),out); fputs("\n\r",out);
:             fclose(out);
:         }
: #endif
:     } catch ( ... ) {
:         ShowMessage("Exception : DisplayDebugLog");
:     }
: }
: //---------------------------------------------------------------------------
: void __fastcall TForm1::Button1Click(TObject *Sender)
: {
:     int cnt = 0;
:     try {
:         if ( ComPort1->Connected ) {    // Disconnect
:
:             if ( Form1->ComPort1->IsAsyncCompleted(Serial_RX_AsyncPtr) ) {
:                 Form1->ComPort1->WaitForAsync(Serial_RX_AsyncPtr);
:             }
:
:             if ( Form1->ComPort1->IsAsyncCompleted(Serial_TX_AsyncPtr) ) {
:                 Form1->ComPort1->WaitForAsync(Serial_TX_AsyncPtr);
:             }
:
:             cnt = 0;
:             while ( !Form1->IdThreadComponent1->Stopped ) {
:                 Form1->DebugMsg = "try IdThreadComponent1 stop : "+IntToStr(cnt);
:                 Form1->IdThreadComponent1->Synchronize(&(Form1->DisplayDebugLog));
:
:                 Form1->IdThreadComponent1->Stop();
:                 Sleep((unsigned long)100);
:                 cnt++;
:             }
:
:             cnt = 0;
:             while ( !Form1->IdThreadComponent2->Stopped ) {
:                 Form1->DebugMsg = "try IdThreadComponent2 stop : "+IntToStr(cnt);
:                 Form1->IdThreadComponent1->Synchronize(&(Form1->DisplayDebugLog));
:
:                 Form1->IdThreadComponent2->Stop();
:                 Sleep((unsigned long)100);
:                 cnt++;
:             }
:
:             Application->ProcessMessages();
:             Sleep((unsigned long)100);
:
:             Form1->ComPort1->Close();
:
:             Form1->Button1->Caption = "Connect";
:
:         } else {                        // Connect
:
:             Form1->ComPort1->Open();
:
:             Form1->IdThreadComponent1->Start();
:             Form1->IdThreadComponent2->Start();
:
:             Form1->Button1->Caption = "Disconnect";
:         }
:     } catch ( ... ) {
:         ShowMessage("Exception : Button1Click");
:     }
: }
: //---------------------------------------------------------------------------
: void __fastcall TForm1::Button2Click(TObject *Sender)
: {
:
:     if ( Form1->Button2->Caption == "Send" ) {
:         Form1->IdThreadComponent2->Start();
:         Form1->Button2->Caption = "Stop";
:     } else {
:         Form1->IdThreadComponent2->Stop();
:         Form1->Button2->Caption = "Send";
:     }
:
:
: }
: //---------------------------------------------------------------------------
: void __fastcall TForm1::IdThreadComponent1Run(
:       TIdCustomThreadComponent *Sender)
: {
:     try {
:         int Serial_Rd_Cnt = Form1->ComPort1->InputCount();
:
:
:         if ( Serial_Rd_Cnt ) {
:
:             char *rx_buf = (char *)malloc( Serial_Rd_Cnt * sizeof(char));
:
:             Form1->ComPort1->ReadAsync(rx_buf, Serial_Rd_Cnt, Serial_RX_AsyncPtr);
:             //Form1->ComPort1->Read(rx_buf, Serial_Rd_Cnt);
:
:             Form1->DebugMsg = "RX ("+IntToStr(Serial_Rd_Cnt) + ") : ";
:             for ( int i = 0 ; i < Serial_Rd_Cnt ; i++ ) {
:                 Form1->DebugMsg += IntToHex(rx_buf[i],2) + " ";
:             }
:             Form1->IdThreadComponent1->Synchronize(&(Form1->DisplayDebugLog));
:
:             free(rx_buf);
:         }
:
:         Sleep((unsigned long)1);
:     } catch ( ... ) {
:         ShowMessage("Exception : IdThreadComponent1Run");
:     }
: }
: //---------------------------------------------------------------------------
:
:
:
: void __fastcall TForm1::IdThreadComponent2Run(
:       TIdCustomThreadComponent *Sender)
: {
:     try {
:         int length = Form1->Edit1->Text.Length();
:         char *buf = (char *)malloc(length * sizeof(char));
:
:         memcpy( buf, Form1->Edit1->Text.c_str(),length);
:
:         Form1->ComPort1->WriteAsync(buf, length, Serial_TX_AsyncPtr);
:
:         Form1->DebugMsg = "TX ("+IntToStr(length) + ") : ";
:         for ( int i = 0 ; i < length ; i++ ) {
:             Form1->DebugMsg += IntToHex(buf[i],2) + " ";
:         }
:         Form1->IdThreadComponent2->Synchronize(&(Form1->DisplayDebugLog));
:
:         free(buf);
:
:         Sleep((unsigned long)StrToIntDef(Form1->Edit2->Text, 100));
:     } catch ( ... ) {
:         ShowMessage("Exception : IdThreadComponent2Run");
:     }
: }
: //---------------------------------------------------------------------------

+ -

관련 글 리스트
51357 CPort-3.10 컴포넌트의 Close() 호출시 프로그램 다운 증상 유산균 2477 2007/11/26
51376     Re:CPort-3.10 컴포넌트의 Close() 호출시 프로그램 다운 증상 최상천 2501 2007/11/27
Google
Copyright © 1999-2015, borlandforum.com. All right reserved.