我有以下代碼用于在 Ubuntu 18.04 上作業。現在,我在 Ubuntu 20.04 中編譯并運行它,但由于某種原因,代碼停止作業。
該代碼旨在從命名管道中讀取。為了測驗它,我創建了管道,mkfifo /tmp/pipe然后我用echo "message" >> /tmp/pipe.
第一次fgets()執行該方法時,函式從管道回傳期望值;但是從第二次呼叫開始,NULL即使我執行了幾個 echo 命令,該方法也會回傳并且代碼卡在回圈中。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <sstream>
#include <fstream>
#include <limits>
#include <iomanip>
#include <iostream>
#include <cstdlib>
using namespace std;
FILE* result_pipe_stream;
string read_result_from_pipe(){
if (result_pipe_stream == NULL){
printf("\n[BINDING-COMMONS] ERROR: Pipe is not set");
return NULL;
}
std::stringstream oss;
while (1) {
char buf[BUFSIZ];
if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL ) {
int buflen = strlen(buf);
if (buflen >0){
if (buf[buflen-1] == '\n'){
buf[buflen-1] = '\0';
oss << buf;
return oss.str();
} else {
oss << buf;
// line was truncated. Read another block to complete line.
}
}
}
}
}
int main(int argc, char *argv[]){
result_pipe_stream = fopen("/tmp/pipe" , "r");
while (1){
cout << read_result_from_pipe() << '\n';
}
}
- 為什么代碼不再起作用了?我假設某些庫在發行版中發生了變化,并且 fgets 不再能夠從管道中正確讀取
- 我該如何解決這個問題?
uj5u.com熱心網友回復:
if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL )- >一旦fgets()恢復NULL,由于最終的檔案,它將繼續回傳NULL后續呼叫不讀 ,除非最終的檔案指示為result_pipe_stream被清除-像clearerr()。代碼陷入無限回圈,不再閱讀,它應該。
真正的問題是為什么它在 Ubuntu 18.04 中“有效”。我懷疑該版本不兼容。
while (1) {
char buf[BUFSIZ];
if( fgets (buf, BUFSIZ, result_pipe_stream) != NULL ) {
...
}
// Perhaps assess why here, end-of-file, input error, too often here, ...
clearerr(result_pipe_stream); // add
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329661.html
