---
title: "进程间通信（八）"
author: "winzenghua"
date: "2009-08-11T23:25:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-08-11T23:25:00Z"
id: 948803
url: "https://java4gis.iteye.com/blog/948803"
---

**搜索数据库**

在CD关键字上的搜索比较复杂。函数的用户希望一旦调用就启动一个搜索。我们在第7章通过将在第一次调用上的\*first\_call\_ptr设置为true并且函数返回第一个匹配结果来满足这种需求。在接下来的搜索函数调用中，\*first\_call\_ptr设置为false，从而会返回更多的匹配，每次调用返回一个匹配结果。

现在我们已经将程序分为两个进程，我们不能再允许搜索在服务器端一次处理一个实体，因为另一个不同的客户端也许会由服务器请求一个不同的搜索，而我们的搜索仍在处理之中。我们不能使得服务器端为每一个客户端单独存储搜索内容（搜索已经进行到哪里），因为当一个用户找到他们要找的CD关键值时或是客户端出现问题，客户端就可以简单的停止搜索。

我们或者可以改变搜索执行的方式，或者是，正如我们在这里所选择的，在接口例程中隐藏复杂性。我们所做的就是使得服务器返回所有可能的搜索匹配，然后将他们存储在一个临时文件中直到客户端请求他们。

**试验－－查找**

1 这个函数看起更为复杂，因为他调用我们会在下一节讨论的三个管道函数：send\_mess\_to\_server,start\_resp\_from\_server与read\_resp\_from\_server。

cdc\_entry search\_cdc\_entry(const char \*cd\_catalog\_ptr, int \*first\_call\_ptr)  
{  
message\_db\_t mess\_send;  
message\_db\_t mess\_ret;  
static FILE \*work\_file = (FILE \*)0;  
static int entries\_matching = 0;  
cdc\_entry ret\_val;  
ret\_val.catalog\[0] = ‘\\0’;  
if (!work\_file && (\*first\_call\_ptr == 0)) return(ret\_val);

2 下面是搜索的第一个调用，在这里\*first\_call\_ptr设置为true。为了防止我们忘记，立即将其设置为false。在这个函数中创建一个work\_file并且初始化客户端消息结构。

if (\*first\_call\_ptr) {  
\*first\_call\_ptr = 0;  
if (work\_file) fclose(work\_file);  
work\_file = tmpfile();  
if (!work\_file) return(ret\_val);  
mess\_send.client\_pid = mypid;  
mess\_send.request = s\_find\_cdc\_entry;  
strcpy(mess\_send.cdc\_entry\_data.catalog, cd\_catalog\_ptr);

3 接下是一个三层的条件测试。如果消息成功的发送到服务器，客户端会等待服务器的响应。当服务器的read操作成功，搜索匹配就会被记入work\_file中，而相应的entries\_matching也会增加。

if (send\_mess\_to\_server(mess\_send)) {  
if (start\_resp\_from\_server()) {  
while (read\_resp\_from\_server(&mess\_ret)) {  
if (mess\_ret.response == r\_success) {  
fwrite(&mess\_ret.cdc\_entry\_data, sizeof(cdc\_entry), 1, work\_file);  
entries\_matching++;  
} else {  
break;  
}  
} /* while \*/  
} else {  
fprintf(stderr, “Server not responding\\n”);  
}  
} else {  
fprintf(stderr, “Server not accepting requests\\n”);  
}

4 下面的测试检测搜索是否成功。然后fseek调用会将work\_file设置为数据将要写入的下一个位置。

if (entries\_matching == 0) {  
fclose(work\_file);  
work\_file = (FILE \*)0;  
return(ret\_val);  
}  
(void)fseek(work\_file, 0L, SEEK\_SET);

5 如果这并不是第一次使用特定的搜索模式调用搜索函数，下面的代码会检测是否还有余下的匹配。最后，下一个匹配项会被读入ret\_val结构中。前面的检测认为存在一个匹配项。

} else {  
/* not \*first\_call\_ptr \*/  
if (entries\_matching == 0) {  
fclose(work\_file);  
work\_file = (FILE \*)0;  
return(ret\_val);  
}  
}  
fread(&ret\_val, sizeof(cdc\_entry), 1, work\_file);  
entries\_matching—;  
return(ret\_val);  
}

**服务器接口**

就如客户端有一个对app\_ui.c程序的一个接口，服务器端也需要一个程序来控制（重命名的）cd\_access.c，现在是cd\_dbm.c。服务器的main函数如下。

**试验－－server.c**

1 我们在程序的开始处声明了几个全局变量，一个process\_command函数原型，以及一个信号捕获函数来保证一个干净的退出。

#include &lt;unistd.h&gt;  
#include &lt;stdlib.h&gt;  
#include &lt;stdio.h&gt;  
#include &lt;fcntl.h&gt;  
#include &lt;limits.h&gt;  
#include &lt;signal.h&gt;  
#include &lt;string.h&gt;  
#include &lt;errno.h&gt;  
#include &lt;sys/types.h&gt;  
#include &lt;sys/stat.h&gt;  
#include “cd\_data.h”  
#include “cliserv.h”  
int save\_errno;  
static int server\_running = 1;  
static void process\_command(const message\_db\_t mess\_command);  
void catch\_signals()  
{  
server\_running = 0;  
}

2 现在我们来了解一下main函数。在检测信号捕获例程正确之后，程序检测我们是否在命令行传递了一个-i选项。如果我们传递了，程序就会创建一个新的数据库。如果cd\_dbm.c中的database\_initialize例程失败，就会显示一个错误消息。如果一切正常而且服务器正在运行，由客户端来的请求就会被传递给process\_command函数，这个函数我们将会稍后介绍。

int main(int argc, char \*argv\[]) {  
struct sigaction new\_action, old\_action;  
message\_db\_t mess\_command;  
int database\_init\_type = 0;  
new\_action.sa\_handler = catch\_signals;  
sigemptyset(&new\_action.sa\_mask);  
new\_action.sa\_flags = 0;  
if ((sigaction(SIGINT, &new\_action, &old\_action) != 0) ||  
(sigaction(SIGHUP, &new\_action, &old\_action) != 0) ||  
(sigaction(SIGTERM, &new\_action, &old\_action) != 0)) {  
fprintf(stderr, “Server startup error, signal catching failed\\n”);  
exit(EXIT\_FAILURE);  
}  
if (argc &gt; 1) {  
argv++;  
if (strncmp(“-i”, \*argv, 2) == 0) database\_init\_type = 1;  
}  
if (!database\_initialize(database\_init\_type)) {  
fprintf(stderr, “Server error:-\\  
could not initialize database\\n”);  
exit(EXIT\_FAILURE);  
}  
if (!server\_starting()) exit(EXIT\_FAILURE);  
while(server\_running) {  
if (read\_request\_from\_client(&mess\_command)) {  
process\_command(mess\_command);  
} else {  
if(server\_running) fprintf(stderr, “Server ended - can not \\  
read pipe\\n”);  
server\_running = 0;  
}  
} /* while \*/  
server\_ending();  
exit(EXIT\_SUCCESS);  
}

3 所有的客户端消息都会被传递给process\_command函数，在那里他们会被传递给一个case语句，从而执行cd\_dbm.c中的正确调用。

static void process\_command(const message\_db\_t comm)  
{  
message\_db\_t resp;  
int first\_time = 1;  
resp = comm; /* copy command back, then change resp as required \*/  
if (!start\_resp\_to\_client(resp)) {  
fprintf(stderr, “Server Warning:-\\  
start\_resp\_to\_client %d failed\\n”, resp.client\_pid);  
return;  
}  
resp.response = r\_success;  
memset(resp.error\_text, ‘\\0’, sizeof(resp.error\_text));  
save\_errno = 0;  
switch(resp.request) {  
case s\_create\_new\_database:  
if (!database\_initialize(1)) resp.response = r\_failure;  
break;  
case s\_get\_cdc\_entry:  
resp.cdc\_entry\_data =  
get\_cdc\_entry(comm.cdc\_entry\_data.catalog);  
break;  
case s\_get\_cdt\_entry:  
resp.cdt\_entry\_data =  
get\_cdt\_entry(comm.cdt\_entry\_data.catalog,  
comm.cdt\_entry\_data.track\_no);  
break;  
case s\_add\_cdc\_entry:  
if (!add\_cdc\_entry(comm.cdc\_entry\_data)) resp.response =  
r\_failure;  
break;  
case s\_add\_cdt\_entry:  
if (!add\_cdt\_entry(comm.cdt\_entry\_data)) resp.response =  
r\_failure;  
break;  
case s\_del\_cdc\_entry:  
if (!del\_cdc\_entry(comm.cdc\_entry\_data.catalog)) resp.response  
\= r\_failure;  
break;  
case s\_del\_cdt\_entry:  
if (!del\_cdt\_entry(comm.cdt\_entry\_data.catalog,  
comm.cdt\_entry\_data.track\_no)) resp.response = r\_failure;  
break;  
case s\_find\_cdc\_entry:  
do {  
resp.cdc\_entry\_data =  
search\_cdc\_entry(comm.cdc\_entry\_data.catalog,  
&first\_time);  
if (resp.cdc\_entry\_data.catalog\[0] != 0) {  
resp.response = r\_success;  
if (!send\_resp\_to\_client(resp)) {  
fprintf(stderr, “Server Warning:-\\  
failed to respond to %d\\n”, resp.client\_pid);  
break;  
}  
} else {  
resp.response = r\_find\_no\_more;  
}  
} while (resp.response == r\_success);  
break;  
default:  
resp.response = r\_failure;  
break;  
} /* switch \*/  
sprintf(resp.error\_text, “Command failed:\\n\\t%s\\n”,  
strerror(save\_errno));  
if (!send\_resp\_to\_client(resp)) {  
fprintf(stderr, “Server Warning:-\\  
failed to respond to %d\\n”, resp.client\_pid);  
}  
end\_resp\_to\_client();  
return;  
}

在我们了解实际的管道实现之前，让我们来讨论一下在客户端与服务器进程之间传递数据需要发生的事件序列。图13-9显示所启动的客户端与服务器进程以及在处理命令与响应时双方是如何循环的。

在这个实现中，形势有一些困难，因为对于一个搜索请求，客户端向服务器传递一个单一命令，然后希望由服务器接收一个或多个响应。这会导致其他额外的一些复杂性，主要在客户端。