我需要帮助我的应用程序。这是一个简单的程序,响应命令行参数。如果第一次调用应用程序,它将在专门的另一个线程上启动为管道服务器(阻塞、非重叠),而主线程则执行其他操作。现在,用户仍然可以使用相同的应用程序可执行文件和命令行参数调用应用程序,但由于它不是应用程序的第一个实例,它会通过管道将命令行参数传递给第一个实例,然后结束自身。因此,它就像一种模式语言中的单例进程。
理想情况下,应该是这样的:
理想情况下,应该是这样的:
app.exe "first" // starts app.exe as a pipe server and prints "first"
app.exe "second" // client process causes server instance to print "second"
app.exe "third" // client process causes server instance to print "third"
app.exe "fourth" // client process causes server instance to print "fourth"
app.exe "fifth" // client process causes server instance to print "fifth"
app.exe -quit // client process causes server instance to terminate.
现在,我唯一的问题是,当我执行上述代码时会发生以下情况:
app.exe "first" // starts app.exe as a pipe server and prints "first"
app.exe "second" // client process returns a GetLastError code of 233
app.exe "third" // client process causes server instance to print "third"
app.exe "fourth" // client process returns a GetLastError code of 233
app.exe "fifth" // client process causes server instance to print "fifth"
app.exe -quit // client process returns a GetLastError code of 233
我的管道服务器代码大致如下(伪代码):
CreateNamedPipe();
// Code below now runs on a separate thread...
while( !Quit )
{
if( ConnectNamedPipe() is successful )
{
if( PeekNamedPipe() has a message )
{
ReadFile();
ProcessReceivedMessage();
}
FileFlushBuffers();
DisconnectNamedPipe();
}
}
CloseHandle( the pipe );
我的客户端版本如下(伪代码):
if( WaitNamedPipe( FOREVER ) != 0 )
{
GetParametersAndFormAMessage();
CreateFile();
WriteFile(); // Sends message to the pipe server
}
CloseHandle();
根据MSDN文档,如果服务器使用DisconnectNamedPipe()方法,客户端将被强制断开连接,并在下一次尝试连接时收到错误。你认为这是原因吗?如果是,那么我如何在不出现额外错误的情况下断开客户端的连接呢?否则,还有什么需要我知道的来使这个工作?我花了很多时间来解决这个问题。
ConnectNamedPipe
步骤应该包括一个相当短的超时时间,以便它定期取消阻塞以检查终止条件,例如像if(shouldQuit) return
这样的标志。 - dss539