这是针对HW 我项目的一些背景知识。我正在编写客户端/服务器程序。我的客户端是生成我的服务器进程,然后通过命名管道向服务器发送文件名和搜索词。我的服务器是在文件中搜索搜索词的实例,并发回它找到的内容。它工作正常,直到我的最后两行。搜索完整个文件后,服务器将告诉客户端找到搜索词的总次数。然后,客户端将以特殊格式的行输出此信息。为了告诉我的客户这是特殊的“总”行的时间,我让我的服务器发送“最后一行”。客户端应该从管道中检索它,进入条件语句来处理特殊行,然后从管道中获取服务器的总计。
这是我的问题:我的客户端正在识别“最后一行”输入并进入正确的条件语句,但是当它从管道中获取总计时,它总是返回空白。如果管道里什么都没有,它不应该阻塞吗?如果这不是问题,为什么/如何空白进入管道?我有一份声明证明整体总数正在进入管道
客户:
...
char endMessage[] ="Server-EOF";
read(fd2, buffer, maxBufferSize);
while(strcmp(buffer,endMessage) != 0)
{
if(strcmp(buffer, "final line") ==0)
{
read(fd2, buffer, maxBufferSize);
cout <<"final line buffer is:<< buffer << endl;
cout <<"Client : PID " <<clientPID << "- Target >>"<< requestedTarget
<<"<< in File >>" <<requestedFileName<< "<< " << buffer <<endl;
}
else{
cout << "Client :PID " << clientPID <<" - Target >>" <<requestedTarget
<<"<< " << buffer << endl;
}
read(fd2, buffer, maxBufferSize);
}
服务器:
size_t found;
getline(rf,tempLine);
while (!rf.eof())
{
currentLineNumber++;
found= tempLine.find(requestedTarget);
while(found != string::npos)
{
totalTimesFoundInFile++;
totalTimesFoundOnLine++;
found=tempLine.find(requestedTarget, found+1);
}
if(totalTimesFoundOnLine != 0)
{
int n = sprintf(stringToSend, "Appeared on Line %d, %d times",currentLineNumber,
totalTimesFoundOnLine);
write(fd2, stringToSend, sizeof(stringToSend));
}
getline(rf,tempLine);
totalTimesFoundOnLine = 0;
}
int t = sprintf(stringToSend, "Appeared a Total of %d Times",totalTimesFoundInFile);
cout <<"Final string to send: " << stringToSend <<endl;
char finalLine[] = "final line";
write(fd2, finalLine, sizeof(finalLine));
cout <<"Just put 'finalLine' into pipe" <<endl;
write(fd2, stringToSend, sizeof(stringToSend));
cout <<"Just put final string into pipe" <<endl;
char endingMessage[]="Server-EOF";
write(fd2, endingMessage, sizeof(endingMessage));
输出:
Final string to send: Appeared a Total of 4 Times
Just put 'finalLine' into pipe
Just put final string into pipe
Client :PID 12684 - Target >>apple<< Appeared on Line 1, 1 times
Client :PID 12684 - Target >>apple<< Appeared on Line 2, 1 times
Client :PID 12684 - Target >>apple<< Appeared on Line 4, 2 times
final line Buffer is:
Client : PID 12684- Target >>apple<< in File >>pipedTest.txt<<
我试图编辑出无关紧要的内容,但如果需要澄清,我会仔细观察这个帖子。
编辑我做了一些检查,看起来我的服务器正在通过其代码并返回。这可能是问题吗?是否关闭/清除管道?如果是这样,有没有办法让我的服务器在返回之前在我的客户端上等待?