Linux write 途中收到 EINTR

案例:

使用 QProcess 執行一個命令,該命令會輸出文字到 stdout。呼叫都使用 QProcess 中的 waitForReadyRead 等待可讀。當讀到資料後,透過 write 寫 COM port 資料。

現象:發現偶爾 COM write 會失敗。
原因:write 偶爾會收到 EINTR,資料未被寫出去。此 EINTR 發生是因為 QProcess 結束後使用 Linux signal 通知原始呼叫的執行緒,如果此時呼叫的執行緒在執行 COM write,就會被中斷。

順序可能是這樣:
thread 1 call QProcess
thread 2 read data and write to stdout
thread 1 read output data
thread 1 call write
thread 2 finished and raise a signal to inform thread 1
thread 1 was interrupted, write returns EINTR

此問題在多核 CPU 下比較容易發生。單核發生的情況很低,目前未看見。

留言

熱門文章