2013-04-10 64 views
1

我在perl(5.12 ActiveState)中使用線程來允許在Windows上的兩個不同COM端口上進行並行和異步寫入。這就是我的代碼的樣子:當Perl線程退出時,串口處理程序錯誤

#!/usr/bin/perl 

use warnings; 
use strict; 
use Win32::SerialPort; 
use threads; 

my $ComPortObj = new Win32::SerialPort ("COM10") or die ("This is the bitter end..."); 
[... omit port settings ...] 

my $ComPortObj2 = new Win32::SerialPort ("COM6") or die ("This is the bitter end..."); 
[... omit port settings ...]  

my $s_read = ""; 

my $HangupThr = async 
{ 
    # printf("THREAD - Wait 3 seconds\n"); 
    # sleep(3); 
    print("THREAD - write on COM10: AT\n"); 
    $ComPortObj->write("AT\r") || die ("Unable to send command\n"); 
    printf("THREAD - Wait 1 second\n"); 
    sleep(1); 
    $s_read = $ComPortObj2->input; 
    # $s_read =~ s/\n/N/g; 
    # $s_read =~ s/\r/R/g; 
    print("THREAD - read from COM6: $s_read\n"); 
    return 1; 

}; 
$HangupThr->detach(); 

# printf("MAIN - Wait 4 seconds\n"); 
# sleep(4); 
print("MAIN - write on COM6: AT\n"); 
$ComPortObj2->write("AT\r") || die ("Unable to send command\n"); 
printf("MAIN - Wait 1 second\n"); 
sleep(1); 
$s_read = $ComPortObj->input; 
# $s_read =~ s/\n/N/g; 
# $s_read =~ s/\r/R/g; 
print("MAIN - read from COM10: $s_read\n"); 

$ComPortObj->close(); 
$ComPortObj2->close(); 

我得到的是程序退出時的錯誤。完整的輸出:

MAIN - write on COM6: AT 
THREAD - write on COM10: AT 
MAIN - Wait 1 second 
THREAD - Wait 1 second 
MAIN - read from COM10: AT 
OK 

THREAD - read from COM6: AT 
OK 

Error in PurgeComm at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1 
The operation completed successfully. 
Error in GetCommTimeouts at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1 
Error Closing handle 184 for \\.\COM6 
The handle is invalid. 
Error closing Read Event handle 188 for \\.\COM6 
The handle is invalid. 
Error closing Write Event handle 192 for \\.\COM6 
The handle is invalid. 
Error in PurgeComm at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1 
The handle is invalid. 
Error in GetCommTimeouts at C:\userdata\Perl scripts\src\handler_error.pl line 0 thread 1 
Error Closing handle 144 for \\.\COM10 
The handle is invalid. 
Error closing Read Event handle 148 for \\.\COM10 
The handle is invalid. 
Error closing Write Event handle 180 for \\.\COM10 
The handle is invalid. 

這是關係到串口處理程序清除,這是我對線程如何perl的重複不知道。我在線程中嘗試了各種密切的嘗試,主要...沒有成功。此外,我必須在主程序和線程中使用相同的端口。任何建議來防止這些錯誤?

非常感謝!

回答

0

您正在處理串行端口,並且在任何時候,只有一個進程可以控制串行端口(某些終端交換機提供多次登錄,但那不是您的情況)在一個進程連接到COM的窗口中,它會自動斷開其他進程。你可以嘗試通過嘗試登錄到相同的COM端口兩次從Windows機器和其他端口應該斷開連接,這應該導致無效的句柄,你看到的錯誤。

其他的事情,你可以嘗試

  1. 創建COM對象線程,使用它和訪問它在其他線程之前銷燬對象
+0

我做了一些實驗,只有這樣,才能避免錯誤是在啓動線程之前關閉主程序中的所有com對象。實際上,錯誤與線程啓動時產生的重複com對象有關。請查看以下@pilcrow的評論以瞭解更多詳情。是的,一旦我沒有重複,我不得不正確地打開和關閉線程內的COM對象。 – 2013-04-15 15:21:38