﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>语源科技BlogJava-Love program</title><link>http://www.blogjava.net/tourer/</link><description>In the way......</description><language>zh-cn</language><lastBuildDate>Sat, 18 Apr 2026 11:14:10 GMT</lastBuildDate><pubDate>Sat, 18 Apr 2026 11:14:10 GMT</pubDate><ttl>60</ttl><item><title>c++标准库——set和multiset容器</title><link>http://www.blogjava.net/tourer/archive/2010/10/29/336481.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Fri, 29 Oct 2010 05:51:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/10/29/336481.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/336481.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/10/29/336481.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/336481.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/336481.html</trackback:ping><description><![CDATA[<fieldset><legend>
<span style="font-size: large;">
<a href="http://ewangplay.appspot.com/?p=23002" rel="bookmark" title="Permanent Link to c++标准库——set和multiset容器"><br />
</a></span></legend>
<div>
<p><span style="line-height: normal; font-size: 16px;"><span style="font-size: medium;">1 set和multiset容器的能力<br />
set
和multiset容器的内部结构通常由平衡二叉树(balanced binary
tree)来实现。当元素放入容器中时，会按照一定的排序法则自动排序，默认是按照less&lt;&gt;排序规则来排序。这种自动排序的特性加速了元
素查找的过程，但是也带来了一个问题：不可以直接修改set或multiset容器中的元素值，因为这样做就可能违反了元素自动排序的规则。如果你希望修
改一个元素的值，必须先删除原有的元素，再插入新的元素。<br />
<br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">2 set和multiset容器的操作<br />
</span><strong><span style="font-size: medium;">Constructor and Destructor</span></strong><span style="font-size: medium;"><br />
</span>
<ul style="margin-top: 0px; margin-bottom: 0px;">
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">set c: 创建一个空的set或multiset容器</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">set c(op): 创建一个空的使用op作为排序法则的set或multiset容器</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">set c1(c2): 创建一个已存在的set或multiset容器的复制品，容器的类型和所有元素一同复制</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">set c(beg, end): 创建一个set或multiset容器，并且以[beg, end)范围中的元素进行初始化</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">set c(beg, end, op): 创建一个使用op作为排序法则的set或multiset容器，并且以[beg, end)范围中的元素进行初始化</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.~set(): 容器的析构函数，销毁所有的元素，释放所有的分配内存</span></li>
</ul>
<span style="font-size: medium;">上面的set可以是下面几种形式：</span></div>
<ul style="margin-top: 0px; margin-bottom: 0px;">
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">set&lt;type&gt;: 以less&lt;&gt;为排序法则的set</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">set&lt;type, op&gt;: 以op为排序法则的set</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">multiset&lt;type&gt;: 以less&lt;&gt;为排序法则的multiset</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">multiset&lt;type, op&gt;: 以op为排序法则的multiset</span></li>
</ul>
<span style="font-size: medium;">从上面我们可以看到，可以从两个地方来指定排序法则：</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">（1）作为模板参数</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">例如：std::set&lt;int, greater&lt;int&gt; &gt; col1;</span></div>
<span style="font-size: medium;">这种情况下，排序法则本身作为容器类型的一部分。对于一个set或者multiset容器，只有当元素类型和排序法则类型都相同时，他们的类型才被认为相同，否则就是不同类型的容器。<br />
<br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">（2）作为构造函数参数<br />
例如：std::set&lt;int&gt; col1(greater&lt;int&gt;);</span></div>
<span style="font-size: medium;">这种情况下指定的排序法则不作为容器类型的一部分，你可以为相同类型的容器指定不同的排序规则。这通常应用于要求相同的容器类型，但排序规则可以不同的场合。<br />
<br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><strong><span style="font-size: medium;">Size and Comparing</span></strong><span style="font-size: medium;"><br />
set
和multiset容器同样提供size(), empty(), max_size()三个关于查询元素数目的接口，提供==, !=, &lt;,
&lt;=, &gt;, &gt;=等比较操作符。但值得注意的是比较操作符只针对相同类型的容器，元素类型和排序法则类型都必须相同。<br />
<br />
</span><strong><span style="font-size: medium;">Special Search Operations</span></strong><span style="font-size: medium;"><br />
set和multiset容器的内部结构对于元素的查找提供了优化空间，所以它们提供了一些特殊的查找接口，这些查找操作通常要比同名的通用算法高效，所以在相同的条件下应该优先使用这些接口。</span></div>
<ul style="margin-top: 0px; margin-bottom: 0px;">
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">count(val): 返回容器中值等于val的元素数目。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">find(val): 返回容器中值等于val的第一个元素的iterator位置；如果没有匹配元素，则返回end()位置。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">lower_bound(val): 返回容器中第一个值大于或等于val的元素的iterator位置。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">upper_bound(val): 返回容器中第一个值大于val的元素的iterator位置。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">equal_range(val): 返回容器中值等于val的所有元素的范围[beg, end)组成的pair&lt;beg, end&gt; 。</span></li>
</ul>
<span style="font-size: medium;">下面我们看一个使用lower_bound(), upper_bound和equal_range(val)例子，以加深对它们的理解：<br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">#include &lt;iostream&gt;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">#include &lt;set&gt;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">#include "print.hpp"</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">using namespace std;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">int main()</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;multiset&lt;int&gt; col1;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(2);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(5);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(4);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(6);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(1);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(5);</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;PRINT_ELEMENTS(col1, "col1: ");</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; endl;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;multiset&lt;int&gt;::const_iterator pos;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;pair&lt;multiset&lt;int&gt;::iterator, multiset&lt;int&gt;::iterator&gt; range;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "lower_bound(3): " &lt;&lt; *col1.lower_bound(3) &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "upper_bound(3): " &lt;&lt; *col1.upper_bound(3) &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;range = col1.equal_range(3);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "equal_range(3): " &lt;&lt; *range.first &lt;&lt; " " &lt;&lt; *range.second &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "elements with value(3): ";</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;for (pos = range.first; pos != range.second; ++pos)</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;cout &lt;&lt; *pos &lt;&lt; " ";</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;}</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; endl;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "lower_bound(5): " &lt;&lt; *col1.lower_bound(5) &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "upper_bound(5): " &lt;&lt; *col1.upper_bound(5) &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;range = col1.equal_range(5);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "equal_range(5): " &lt;&lt; *range.first &lt;&lt; " " &lt;&lt; *range.second &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; "elements with value(5): ";</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;for (pos = range.first; pos != range.second; ++pos)</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;cout &lt;&lt; *pos &lt;&lt; " ";</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;}</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;cout &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">}</span></div>
<span style="font-size: medium;">执行结果如下：<br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">col1: 1 2 4 5 5 6&nbsp;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">lower_bound(3): 4</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">upper_bound(3): 4</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">equal_range(3): 4 4</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">elements with value(3):&nbsp;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">lower_bound(5): 5</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">upper_bound(5): 6</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">equal_range(5): 5 6</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">elements with value(5): 5 5&nbsp;</span></div>
<span style="font-size: medium;"><br />
</span><strong><span style="font-size: medium;">Assignment</span></strong><span style="font-size: medium;"><br />
set和multiset容器只提供最基本的赋值操作：<br />
</span>
<ul style="margin-top: 0px; margin-bottom: 0px;">
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c1 = c2: 把c2的所有元素复制到c1中，同时c1原有的元素被销毁。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c1.swap(c2): 交换c1和c2的元素。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">swap(c1, c2): 同上，只不过这是一个通用算法。</span></li>
</ul>
<span style="font-size: medium;">需要注意的是两个容器的类型要一致（包括元素类型和排序法则类型）。<br />
<br />
</span><strong><span style="font-size: medium;">Inserting and Removing Elements</span></strong><span style="font-size: medium;"><br />
set和multiset容器的插入和删除元素接口跟其他容器也非常类似，但在细节上却存在差别。<br />
</span>
<ul style="margin-top: 0px; margin-bottom: 0px;">
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.insert(elem): 在容器中插入元素elem的一份拷贝，并返回新元素的iterator位置；如果是set容器，同时还返回是否插入成功的标志。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.insert(pos, elem): 在容器中插入元素elem的一份拷贝，并返回新元素的iterator位置；因为set和multiset容器的元素是自动排序的，所以pos位置只是插入位置的一个提示，设置恰当的话，可以提高插入元素的效率。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.insert(beg, end): 在容器中插入[beg, end)范围中所有元素的拷贝，没有返回值。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.erase(val): 删除容器中所有值为val的元素，返回删除元素的数目。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.erase(pos): 删除容器中位置pos处的元素，没有返回值。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.erase(beg, end): 删除容器中[ben, end)范围内所有的元素，没有返回值。</span></li>
    <li style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">c.clear(): 删除容器中所有元素，使容器成为空容器。</span></li>
</ul>
<span style="font-size: medium;"><br />
其中我们重点说一下c.insert(elem)接口。</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">对于set容器，它的定义如下：</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">pair&lt;iterator, bool&gt; insert(const TYPE&amp; val);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">而对于multiset容器，它的定义如下：</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">iterator insert(const TYPE&amp; val);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">它
们的不同就是set容器的insert接口返回的是一个pair&lt;iterator,
bool&gt;，而multiset容器的insert接口直接返回一个iterator。这是因为set容器中不允许有重复的元素，如果容器中已经存
在一个跟插入值相同的元素，那么插入操作就会失败，而pair中的bool值就是标识插入是否成功的。而multiset不存在这个问题。<br />
<br />
3 set和multiset容器的异常处理</span></div>
<span style="font-size: medium;">因为set和multiset容器的独特内部结构，当发生异常时，也可以把影响减到最小。也就是说，跟list容器一样，set和multiset容器的操作要么成功，要么对原有容器没有影响。<br />
<br />
</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">4 运行时指定排序法则</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">通常情况下，我们是在定义容器时指定排序法则，就像下面形式：</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">std::set&lt;int, greater&lt;int&gt; &gt; col1;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">或者</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">std::set&lt;int&gt; col1;&nbsp;&nbsp; &nbsp;//use default sorting criterion less&lt;&gt;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">然而，如果你需要在运行时动态指定容器的排序法则，或者你希望对于相同的容器类型却有着不同的排序法则，那么就要做一些特殊处理。下面我们看一个例子：</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">#include &lt;iostream&gt;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">#include &lt;set&gt;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">#include "print.hpp"</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">using namespace std;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">template &lt;typename T&gt;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">class RuntimeCmp&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;public:</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;enum cmp_mode {normal, reverse};</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;private:</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;cmp_mode mode;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;public:</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;RuntimeCmp(cmp_mode m = normal) : mode(m) {}</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;bool operator() (const T&amp; t1, const T&amp; t2)</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return mode == normal ? t1 &lt; t2 : t1 &gt; t2;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;bool operator== (const T&amp; rhv)&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return mode == rhv.mode;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">};</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">typedef set&lt;int, RuntimeCmp&lt;int&gt; &gt; IntSet;</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">//pre-declare</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">void fill(IntSet&amp; col1);</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">int main()</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;IntSet col1;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;fill(col1);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;PRINT_ELEMENTS(col1, "col1: ");</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;RuntimeCmp&lt;int&gt; reverse_cmp(RuntimeCmp&lt;int&gt;::reverse);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;IntSet col2(reverse_cmp);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;fill(col2);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;PRINT_ELEMENTS(col2, "col2: ");</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;if (col1 == col2)&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;cout &lt;&lt; "col1 and col2 is equal" &lt;&lt;endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;}</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;else</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if (col1 &lt; col2)&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cout &lt;&lt; "col1 is less than col2" &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;else&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cout &lt;&lt; "col1 is greater than col2" &lt;&lt; endl;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;}</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;return 0;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">}</span></div>
<span style="font-size: medium;"><br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">void fill(IntSet&amp; col1)&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">{</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(2);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(3);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(6);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(5);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(1);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">&nbsp;&nbsp; &nbsp;col1.insert(4);</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">}</span></div>
<span style="font-size: medium;">运行结果如下：<br />
</span>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">col1 1 2 3 4 5 6&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">col2 6 5 4 3 2 1&nbsp;</span></div>
<div style="margin-top: 0px; margin-bottom: 0px;"><span style="font-size: medium;">col1 is less than col2</span></div>
<span style="font-size: medium;"><br />
这里例子中，col1和col2有着相同的类型：set&lt;int,
RuntimeCmp&lt;int&gt;
&gt;，但是它们的排序法则却不相同，一个升序，一个降序。这都是通过自定义的函数对象来实现的，所以函数对象比普通函数有着更加灵活与强大的控制，可
以满足一些特殊的需求。</span></span></p>
</div>
</fieldset>
<img src ="http://www.blogjava.net/tourer/aggbug/336481.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-10-29 13:51 <a href="http://www.blogjava.net/tourer/archive/2010/10/29/336481.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Linux动态库搜索路径</title><link>http://www.blogjava.net/tourer/archive/2010/09/14/331952.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Tue, 14 Sep 2010 03:03:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/09/14/331952.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/331952.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/09/14/331952.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/331952.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/331952.html</trackback:ping><description><![CDATA[&nbsp; 众所周知，<span style="font-weight: bold;">Linux动态库的默认搜索路径是<span style="color: #ff0102;">/lib</span>和<span style="color: #ff0102;">/usr/lib</span></span>。动态库被创建后，一般都复制到这两个目录中。当程序执行时需要某动态库，并且该动态库还未加载到内存中，则系统会自动到这两个默认搜索路径中去查找相应的动态库文件，然后加载该文件到内存中，这样程序就可以使用该动态库中的函数，以及该动态库的其它资源了。在Linux
中，动态库的搜索路径除了默认的搜索路径外，还可以通过以下三种方法来指定。
<p style="color: #0001ff; text-indent: 20pt;"><span><span style="font-weight: bold;">方法一：在配置文件<span style="color: #ff0102;">/etc/ld.so.conf</span>中指定动态库搜索路径。</span> </span></p>
<p style="text-indent: 20pt;">可以通过编辑配置文件/etc/ld.so.conf来指定动态库的搜索路径，该文件中每行为一个动态库搜索路径。每次编辑完该文件后，都必须运行命令ldconfig使修改后的配置生效。我们通过例1来说明该方法。
</p>
<p style="text-indent: 20pt;">例1： </p>
<p style="text-indent: 20pt;">我们通过以下命令用源程序pos_conf.c（见程序1）来创建动态库
libpos.so，详细创建过程请参考文[1]。</p>
<p style="text-indent: 35pt;"># gcc -c pos_conf.c<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # gcc -shared -fPCI -o
libpos.so pos_conf.o<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 35pt;">#include &lt;stdio.h&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void
pos()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; printf("/root/test/conf/lib\n");</p>
<p style="text-indent: 35pt;">}<br />
</p>
<div style="text-align: center;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 程序1: pos_conf.c<br />
</div>
<p style="text-indent: 20pt;">接着通过以下命令编译main.c（见程序2）生成目标程序pos。 </p>
<p style="text-indent: 35pt;"># gcc -o pos main.c -L. -lpos<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 35pt;">void pos();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int main()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; pos();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return 0;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</p>
<p style="text-indent: 35pt; text-align: center;">程序2: main.c<br />
</p>
<p style="text-indent: 20pt;">然后把库文件移动到目录/root/test/conf/lib中。 </p>
<p style="text-indent: 35pt;"># mkdir -p /root/test/conf/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # mv
libpos.so /root/test/conf/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 20pt;">最后编辑配置文件/etc/ld.so.conf，在该文件中追加一行"/root/test/conf/lib"。
</p>
<p style="text-indent: 20pt;">运行程序pos试试。 </p>
<p style="text-indent: 35pt;"># ./pos<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ./pos: error while loading
shared libraries: libpos.so: cannot open shared object file: No such file or
directory<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #</p>
<p style="text-indent: 20pt;">出错了，系统未找到动态库libpos.so。找找原因，原来在编辑完配置文件/etc/ld.so.conf后，没有运行命令ldconfig，所以刚才的修改还未生效。我们运行ldconfig后再试试。</p>
<p style="text-indent: 35pt;"># ldconfig<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ./pos&nbsp;&nbsp;&nbsp;&nbsp; /root/test/conf/lib
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
<br />
</p>
<p style="text-indent: 20pt;">程序pos运行成功，并且打印出正确结果。 </p>
<p style="font-weight: bold; text-indent: 20pt;"><span><span style="color: #0001ff;">方法二：通过环境变量<span style="color: #ff0102;">LD_LIBRARY_PATH</span>指定动态库搜索路径（！）。</span>
</span></p>
<p style="text-indent: 20pt;">通过设定环境变量LD_LIBRARY_PATH也可以指定动态库搜索路径。当通过该环境变量指定多个动态库搜索路径时，路径之间用冒号"："分隔。</p>
<font size="+0"><font size="+0"><font class="f14" id="zoom"><font color="#000000">&nbsp;&nbsp;&nbsp;
不过LD_LIBRARY_PATH的设定作用是全局的，过多的使用可能会影响到其他应用程序的运行，所以多用在调试。（LD_LIBRARY_PATH的缺陷和使用准则，可以参考《Why
LD_LIBRARY_PATH is
bad》）。通常情况下推荐还是使用gcc的-R或-rpath选项来在编译时就指定库的查找路径，并且该库的路径信息保存在可执行文件中，运行时它会直接到该路径查找库，避免了使用LD_LIBRARY_PATH环境变量查找。</font></font></font></font>
<p style="text-indent: 20pt;">下面通过例2来说明本方法。 </p>
<p style="text-indent: 20pt;">例2： </p>
<p style="text-indent: 20pt;">我们通过以下命令用源程序pos_env.c（见程序3）来创建动态库libpos.so。 </p>
<p style="text-indent: 35pt;"># gcc -c pos_env.c<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # gcc -shared -fPCI -o
libpos.so pos_env.o<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 35pt;">#include &lt;stdio.h&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void
pos()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
printf("/root/test/env/lib\n");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 程序3: pos_env.c<br />
</p>
<p style="text-indent: 20pt;">测试用的可执行文件pos可以使用例1中的得到的目标程序pos，不需要再次编译。因为pos_conf.c中的函数pos和pos_env.c中的函数pos
函数原型一致，且动态库名相同，这就好比修改动态库pos后重新创建该库一样。这也是使用动态库的优点之一。 </p>
<p style="text-indent: 20pt;">然后把动态库libpos.so移动到目录/root/test/conf/lib中。 </p>
<p style="text-indent: 35pt;"># mkdir -p /root/test/env/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # mv
libpos.so /root/test/env/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 20pt;">我们可以使用export来设置该环境变量，在设置该环境变量后所有的命令中，该环境变量都有效。 </p>
<p style="text-indent: 20pt;">例如： </p>
<p style="text-indent: 35pt;"># export
LD_LIBRARY_PATH=/root/test/env/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #</p>
<p style="text-indent: 20pt;">但本文为了举例方便，使用另一种设置环境变量的方法，既在命令前加环境变量设置，该环境变量只对该命令有效，当该命令执行完成后，该环境变量就无效了。如下述命令：</p>
<p style="text-indent: 35pt;"># LD_LIBRARY_PATH=/root/test/env/lib ./pos&nbsp;
/root/test/env/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #</p>
<p style="text-indent: 20pt;">程序pos运行成功，并且打印的结果是"/root/test/env/lib"，正是程序pos_env.c中的函数pos的运行结果。因此程序pos搜索到的动态库是/root/test/env/lib/libpos.so。
</p>
<p style="font-weight: bold; text-indent: 20pt;"><span><span style="color: #0001ff;">方法三：在编译目标代码时指定该程序的动态库搜索路径。</span> </span></p>
<p style="text-indent: 20pt;">还可以在编译目标代码时指定程序的动态库搜索路径。这是通过gcc 的参数"<span style="font-weight: bold; color: #ff0102;">-Wl,-rpath,</span>"指定（如例3所示）。当指定多个动态库搜索路径时，路径之间用冒号"："分隔。
</p>
<p style="text-indent: 20pt;">例3： </p>
<p style="text-indent: 20pt;">我们通过以下命令用源程序pos.c（见程序4）来创建动态库libpos.so。 </p>
<p style="text-indent: 35pt;"># gcc -c pos.c<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # gcc -shared -fPCI -o
libpos.so pos.o<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 35pt;">#include &lt;stdio.h&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void
pos()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("./\n");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
</p>
<div style="text-align: center;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 程序4: pos.c</div>
<p style="text-indent: 20pt;">因为我们需要在编译目标代码时指定可执行文件的动态库搜索路径，所以需要用gcc命令重新编译源程序main.c(见程序2)来生成可执行文件pos。</p>
<p style="text-indent: 35pt;"># gcc -o pos main.c -L. -lpos
-Wl,-rpath,./<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #</p>
<p style="text-indent: 20pt;">再运行程序pos试试。</p>
<p style="text-indent: 35pt;"># ./pos&nbsp;&nbsp; ./<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #</p>
<p style="text-indent: 20pt;">程序pos运行成功，输出的结果正是pos.c中的函数pos的运行结果。因此程序pos搜索到的动态库是./libpos.so。
</p>
<p style="text-indent: 20pt;">以上介绍了三种指定动态库搜索路径的方法，加上默认的动态库搜索路径/lib和/usr/lib，共五种动态库的搜索路径，那么它们搜索的先后顺序是什么呢？
</p>
<p style="text-indent: 20pt;">在 介绍上述三种方法时，分别创建了动态库./libpos.so、
/root/test/env/lib/libpos.so和/root/test/conf/lib/libpos.so。我们再用源程序
pos_lib.c（见程序5）来创建动态库/lib/libpos.so，用源程序pos_usrlib.c（见程序6）来创建动态库
/usr/lib/libpos.so。 </p>
<p style="text-indent: 35pt;">#include &lt;stdio.h&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void
pos()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("/lib\n");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
</p>
<div style="text-align: center;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 程序5: pos_lib.c<br />
</div>
<p style="text-indent: 35pt;">#include &lt;stdio.h&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; void
pos()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("/usr/lib\n");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
</p>
<div style="text-align: center;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 程序6: pos_usrlib.c<br />
</div>
<p style="text-indent: 20pt;">这样我们得到五个动态库libpos.so，这些动态库的名字相同，且都包含相同函数原型的公用函数pos。但存储的位置不同和公用函数pos
打印的结果不同。每个动态库中的公用函数pos都输出该动态库所存放的位置。这样我们可以通过执行例3中的可执行文件pos得到的结果不同获知其搜索到了哪个动态库，从而获得第1个动态库搜索顺序，然后删除该动态库，再执行程序pos，获得第2个动态库搜索路径，再删除第2个被搜索到的动态库，如此往复，将可得到Linux搜索动态库的先后顺序。程序pos执行的输出结果和搜索到的动态库的对应关系如表1所示：
</p>
<center>
<table border="1">
    <tbody>
        <tr>
            <th>程序pos输出结果</th>
            <th>使用的动态库</th>
            <th>对应的动态库搜索路径指定方式</th>
        </tr>
        <tr>
            <td>./</td>
            <td>./libpos.so</td>
            <td>编译目标代码时指定的动态库搜索路径</td>
        </tr>
        <tr>
            <td>/root/test/env/lib</td>
            <td>/root/test/env/lib/libpos.so</td>
            <td>环境变量LD_LIBRARY_PATH指定的动态库搜索路径</td>
        </tr>
        <tr>
            <td>/root/test/conf/lib</td>
            <td>/root/test/conf/lib/libpos.so</td>
            <td>配置文件/etc/ld.so.conf中指定的动态库搜索路径</td>
        </tr>
        <tr>
            <td>/lib</td>
            <td>/lib/libpos.so</td>
            <td>默认的动态库搜索路径/lib</td>
        </tr>
        <tr>
            <td>/usr/lib</td>
            <td>/usr/lib/libpos.so</td>
            <td>默认的动态库搜索路径/usr/lib</td>
        </tr>
    </tbody>
</table>
表1: 程序pos输出结果和动态库的对应关系 </center>
<p style="text-indent: 20pt;">创建各个动态库，并放置在相应的目录中。测试环境就准备好了。执行程序pos，并在该命令行中设置环境变量LD_LIBRARY_PATH。
</p>
<p style="text-indent: 35pt;"># LD_LIBRARY_PATH=/root/test/env/lib ./pos&nbsp;
./<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 20pt;">根据程序pos的输出结果可知，最先搜索的是编译目标代码时指定的动态库搜索路径。然后我们把动态库./libpos.so删除了，再运行上述命令试试。<br />
</p>
<p style="text-indent: 35pt;"># rm libpos.so<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rm: remove regular file
`libpos.so'? y<br />
&nbsp;&nbsp; &nbsp;&nbsp; # LD_LIBRARY_PATH=/root/test/env/lib ./pos
/root/test/env/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 20pt;">根据程序pos的输出结果可知，第2个动态库搜索的路径是环境变量LD_LIBRARY_PATH指定的。我们再把/root/test/env/lib/libpos.so删除，运行上述命令。<br />
</p>
<p style="text-indent: 35pt;"># rm /root/test/env/lib/libpos.so<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rm:
remove regular file `/root/test/env/lib/libpos.so'? y<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #
LD_LIBRARY_PATH=/root/test/env/lib ./pos&nbsp; /root/test/conf/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #</p>
<p style="text-indent: 20pt;">第3个动态库的搜索路径是配置文件/etc/ld.so.conf指定的路径。删除动态库/root/test/conf/lib/libpos.so后再运行上述命令。<br />
</p>
<p style="text-indent: 35pt;"># rm /root/test/conf/lib/libpos.so<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rm:
remove regular file `/root/test/conf/lib/libpos.so'? y<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #
LD_LIBRARY_PATH=/root/test/env/lib ./pos&nbsp; /lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 20pt;">第4个动态库的搜索路径是默认搜索路径/lib。我们再删除动态库/lib/libpos.so，运行上述命令。<br />
</p>
<p style="text-indent: 35pt;"># rm /lib/libpos.so<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; rm: remove regular
file `/lib/libpos.so'? y<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # LD_LIBRARY_PATH=/root/test/env/lib ./pos&nbsp;
/usr/lib<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #<br />
</p>
<p style="text-indent: 20pt;">最后的动态库搜索路径是默认搜索路径/usr/lib。 </p>
<p style="text-indent: 20pt;">综合以上结果可知，动态库的搜索路径搜索的先后顺序是： </p>
<p style="font-weight: bold; text-indent: 20pt;">1.编译目标代码时指定的动态库搜索路径； </p>
<p style="font-weight: bold; text-indent: 20pt;">2.环境变量LD_LIBRARY_PATH指定的动态库搜索路径；
</p>
<p style="font-weight: bold; text-indent: 20pt;">3.配置文件/etc/ld.so.conf中指定的动态库搜索路径；
</p>
<p style="font-weight: bold; text-indent: 20pt;">4.默认的动态库搜索路径/lib； </p>
<p style="text-indent: 20pt;"><span style="font-weight: bold;">5.默认的动态库搜索路径/usr/lib。</span> </p>
<p style="text-indent: 20pt;">在上述1、2、3指定动态库搜索路径时，都可指定多个动态库搜索路径，其搜索的先后顺序是按指定路径的先后顺序搜索的。对此本文不再举例说明，有兴趣的读者可以参照本文的方法验证。</p>
<img src ="http://www.blogjava.net/tourer/aggbug/331952.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-09-14 11:03 <a href="http://www.blogjava.net/tourer/archive/2010/09/14/331952.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>用C++进行简单的文件I/O操作</title><link>http://www.blogjava.net/tourer/archive/2010/08/08/328247.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Sun, 08 Aug 2010 09:37:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/08/08/328247.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/328247.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/08/08/328247.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/328247.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/328247.html</trackback:ping><description><![CDATA[<p><strong>序论</strong><br />
我曾发表过文件输入输出的文章，现在觉得有必要再写一点。文件 I/O 在C++中比烤蛋糕简单多了。 在这篇文章里，我会详细解释ASCII和二进制文件的输入输出的每个细节，值得注意的是，所有这些都是用C++完成的。</p>
<p>一、ASCII 输出<br />
为了使用下面的方法,
你必须包含头文件&lt;fstream.h&gt;(译者注：在标准C++中，已经使用&lt;fstream&gt;取
代&lt;fstream.h&gt;，所有的C++标准头文件都是无后缀的。)。这是 &lt;iostream.h&gt;的一个扩展集,
提供有缓冲的文件输入输出操作. 事实上, &lt;iostream.h&gt; 已经被&lt;fstream.h&gt;包含了,
所以你不必包含所有这两个文件, 如果你想显式包含他们，那随便你。我们从文件操作类的设计开始, 我会讲解如何进行ASCII I/O操作。
如果你猜是"fstream," 恭喜你答对了！ 但这篇文章介绍的方法,我们分别使用"ifstream"?和 "ofstream" 来作输入输出。<br />
如果你用过标准控制台流"cin"?和 "cout," 那现在的事情对你来说很简单。 我们现在开始讲输出部分，首先声明一个类对象。</p>
<pre>ofstream fout; </pre>
<p>这就可以了，不过你要打开一个文件的话, 必须像这样调用ofstream::open()。</p>
<pre>fout.open("output.txt"); </pre>
<p>你也可以把文件名作为构造参数来打开一个文件.</p>
<pre>ofstream fout("output.txt");</pre>
<p>　　这是我们使用的方法, 因为这样创建和打开一个文件看起来更简单. 顺便说一句, 如果你要打开的文件不存在，它会为你创建一个,
所以不用担心文件创建的问题. 现在就输出到文件，看起来和"cout"的操作很像。 对不了解控制台输出"cout"的人, 这里有个例子。</p>
<pre>int num = 150;char name[] = "John Doe";fout &lt;&lt; "Here is a number: " &lt;&lt; num &lt;&lt; "\n";fout &lt;&lt; "Now here is a string: " &lt;&lt; name &lt;&lt; "\n";</pre>
<p>　　现在保存文件，你必须关闭文件，或者回写文件缓冲. 文件关闭之后就不能再操作了,
所以只有在你不再操作这个文件的时候才调用它，它会自动保存文件。 回写缓冲区会在保持文件打开的情况下保存文件, 所以只要有必要就使用它。
回写看起来像另一次输出, 然后调用方法关闭。像这样：</p>
<pre>fout &lt;&lt; flush; fout.close(); </pre>
<p>现在你用文本编辑器打开文件，内容看起来是这样：</p>
<pre>Here is a number: 150 Now here is a string: John Doe </pre>
<p>　　很简单吧! 现在继续文件输入, 需要一点技巧, 所以先确认你已经明白了流操作，对 "&lt;&lt;" 和"&gt;&gt;" 比较熟悉了, 因为你接下来还要用到他们。继续&#8230;</p>
<p>二、ASCII 输入<br />
输入和"cin" 流很像. 和刚刚讨论的输出流很像, 但你要考虑几件事情。在我们开始复杂的内容之前, 先看一个文本：</p>
<pre>12 GameDev 15.45 L This is really awesome! </pre>
<p>为了打开这个文件，你必须创建一个in-stream对象,?像这样。</p>
<pre>ifstream fin("input.txt"); </pre>
<p>　　现在读入前四行. 你还记得怎么用"&lt;&lt;" 操作符往流里插入变量和符号吧？好,?在 "&lt;&lt;" (插入)?操作符之后，是"&gt;&gt;" (提取) 操作符. 使用方法是一样的. 看这个代码片段.</p>
<pre>int number; float real; char letter, word[8]; fin &gt;&gt; number; fin &gt;&gt; word; fin &gt;&gt; real; fin &gt;&gt; letter; </pre>
<p>也可以把这四行读取文件的代码写为更简单的一行。</p>
<pre>fin &gt;&gt; number &gt;&gt; word &gt;&gt; real &gt;&gt; letter; </pre>
<p>　　它是如何运作的呢? 文件的每个空白之后, "&gt;&gt;" 操作符会停止读取内容, 直到遇到另一个&gt;&gt;操作符.
因为我们读取的每一行都被换行符分割开(是空白字符), "&gt;&gt;"
操作符只把这一行的内容读入变量。这就是这个代码也能正常工作的原因。但是，可别忘了文件的最后一行。</p>
<pre>This is really awesome! </pre>
<p>　　如果你想把整行读入一个char数组, 我们没办法用"&gt;&gt;"?操作符，因为每个单词之间的空格（空白字符）会中止文件的读取。为了验证：</p>
<pre>char sentence[101]; fin &gt;&gt; sentence; </pre>
<p>　　我们想包含整个句子, "This is really awesome!" 但是因为空白, 现在它只包含了"This". 很明显, 肯定有读取整行的方法, 它就是getline()。这就是我们要做的。</p>
<pre>fin.getline(sentence, 100); </pre>
<p>　　这是函数参数. 第一个参数显然是用来接受的char数组. 第二个参数是在遇到换行符之前，数组允许接受的最大元素数量. 现在我们得到了想要的结果：&#8220;This is really awesome!&#8221;。<br />
你应该已经知道如何读取和写入ASCII文件了。但我们还不能罢休，因为二进制文件还在等着我们。</p>
<p><strong>三、二进制 输入输出</strong><br />
二进制文件会复杂一点, 但还是很简单的。
首先你要注意我们不再使用插入和提取操作符(译者注：&lt;&lt; 和 &gt;&gt; 操作符).
你可以这么做，但它不会用二进制方式读写。你必须使用read() 和write() 方法读取和写入二进制文件. 创建一个二进制文件, 看下一行。</p>
<pre>ofstream fout("file.dat", ios::binary); </pre>
<p>　　这会以二进制方式打开文件, 而不是默认的ASCII模式。首先从写入文件开始。函数write() 有两个参数。 第一个是指向对象的char类型的指针, 第二个是对象的大小（译者注：字节数）。 为了说明，看例子。</p>
<pre>int number = 30; fout.write((char *)(&amp;number), sizeof(number)); </pre>
<p>　　第一个参数写做"(char *)(&amp;number)". 这是把一个整型变量转为char
*指针。如果你不理解，可以立刻翻阅C++的书籍，如果有必要的话。第二个参数写作"sizeof(number)". sizeof()
返回对象大小的字节数. 就是这样!<br />
二进制文件最好的地方是可以在一行把一个结构写入文件。 如果说，你的结构有12个不同的成员。 用ASCII?文件，你不得不每次一条的写入所有成员。 但二进制文件替你做好了。 看这个。</p>
<pre>struct OBJECT { int number; char letter; } obj; obj.number = 15;obj.letter = &#8216;M&#8217;; fout.write((char *)(&amp;obj), sizeof(obj)); </pre>
<p>　　这样就写入了整个结构! 接下来是输入. 输入也很简单，因为read()?函数的参数和 write()是完全一样的, 使用方法也相同。</p>
<pre>ifstream fin("file.dat", ios::binary); fin.read((char *)(&amp;obj), sizeof(obj)); </pre>
<p>　　我不多解释用法, 因为它和write()是完全相同的。二进制文件比ASCII文件简单, 但有个缺点是无法用文本编辑器编辑。 接着, 我解释一下ifstream 和ofstream 对象的其他一些方法作为结束.</p>
<p><strong>四、更多方法</strong><br />
我已经解释了ASCII文件和二进制文件, 这里是一些没有提及的底层方法。<br />
<em><br />
检查文件</em><br />
你已经学会了open() 和close() 方法, 不过这里还有其它你可能用到的方法。<br />
方法good() 返回一个布尔值，表示文件打开是否正确。<br />
类似的，bad() 返回一个布尔值表示文件打开是否错误。 如果出错，就不要继续进一步的操作了。<br />
最后一个检查的方法是fail(), 和bad()有点相似, 但没那么严重。</p>
<p><em>读文件</em><br />
方法get() 每次返回一个字符。<br />
方法ignore(int,char) 跳过一定数量的某个字符, 但你必须传给它两个参数。第一个是需要跳过的字符数。 第二个是一个字符, 当遇到的时候就会停止。 例子,</p>
<pre>fin.ignore(100, &#8216;\n&#8217;); </pre>
<p>会跳过100个字符，或者不足100的时候，跳过所有之前的字符，包括 &#8216;\n&#8217;。<br />
方法peek() 返回文件中的下一个字符, 但并不实际读取它。所以如果你用peek() 查看下一个字符, 用get() 在peek()之后读取，会得到同一个字符, 然后移动文件计数器。<br />
方法putback(char) 输入字符, 一次一个, 到流中。我没有见到过它的使用，但这个函数确实存在。</p>
<p><em>写文件</em><br />
只有一个你可能会关注的方法.?那就是 put(char), 它每次向输出流中写入一个字符。</p>
<p><em>打开文件</em><br />
当我们用这样的语法打开二进制文件:</p>
<pre>ofstream fout("file.dat", ios::binary); </pre>
<p>　　"ios::binary"是你提供的打开选项的额外标志. 默认的, 文件以ASCII方式打开, 不存在则创建, 存在就覆盖. 这里有些额外的标志用来改变选项。</p>
<table id="table1" border="0" cellpadding="0" cellspacing="0">
    <tbody>
        <tr valign="top">
            <td class="code">ios::app</td>
            <td>添加到文件尾</td>
        </tr>
        <tr valign="top">
            <td class="code">ios::ate</td>
            <td>把文件标志放在末尾而非起始。</td>
        </tr>
        <tr valign="top">
            <td class="code">ios::trunc</td>
            <td>默认. 截断并覆写文件。</td>
        </tr>
        <tr valign="top">
            <td class="code">ios::nocreate</td>
            <td>文件不存在也不创建。</td>
        </tr>
        <tr valign="top">
            <td class="code">ios::noreplace&nbsp;&nbsp;&nbsp;</td>
            <td>文件存在则失败。</td>
        </tr>
    </tbody>
</table>
<p><em>文件状态</em><br />
我用过的唯一一个状态函数是eof(), 它返回是否标志已经到了文件末尾。 我主要用在循环中。 例如, 这个代码断统计小写&#8216;e&#8217; 在文件中出现的次数。</p>
<pre>ifstream fin("file.txt"); char ch; int counter; while (!fin.eof()) {      ch = fin.get();       if (ch == &#8216;e&#8217;) counter++; }fin.close(); </pre>
<p>　　我从未用过这里没有提到的其他方法。 还有很多方法，但是他们很少被使用。参考C++书籍或者文件流的帮助文档来了解其他的方法。</p>
<img src ="http://www.blogjava.net/tourer/aggbug/328247.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-08-08 17:37 <a href="http://www.blogjava.net/tourer/archive/2010/08/08/328247.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Linux下Socket编程</title><link>http://www.blogjava.net/tourer/archive/2010/03/21/316097.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Sun, 21 Mar 2010 13:01:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/03/21/316097.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/316097.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/03/21/316097.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/316097.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/316097.html</trackback:ping><description><![CDATA[<meta http-equiv="content-type" content="text/html; charset=utf-8" /><span  style="font-family: arial, sans-serif, 宋体; line-height: 22px; font-size: 14px; ">
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; "><strong style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">什么是Socket</strong><br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Socket接口是TCP/IP网络的API，Socket接口定义了许多函数或例程，程序员可以用它们来开发TCP/IP网络上的应用程序。要学Internet上的TCP/IP网络编程，必须理解Socket接口。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Socket接口设计者最先是将接口放在Unix操作系统里面的。如果了解Unix系统的输入和输出的话，就很容易了解Socket了。网络的 Socket数据传输是一种特殊的I/O，Socket也是一种文件描述符。Socket也具有一个类似于打开文件的函数调用Socket()，该函数返 回一个整型的Socket描述符，随后的连接建立、数据传输等操作都是通过该Socket实现的。常用的Socket类型有两种：流式Socket （SOCK_STREAM）和数据报式Socket（SOCK_DGRAM）。流式是一种面向连接的Socket，针对于面向连接的TCP服务应用；数据 报式Socket是一种无连接的Socket，对应于无连接的UDP服务应用。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; "><strong style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">Socket建立</strong><br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
为了建立Socket，程序可以调用Socket函数，该函数返回一个类似于文件描述符的句柄。socket函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int socket(int domain, int type, int protocol);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
domain指明所使用的协议族，通常为PF_INET，表示互联网协议族（TCP/IP协议族）；type参数指定socket的类型： SOCK_STREAM 或SOCK_DGRAM，Socket接口还定义了原始Socket（SOCK_RAW），允许程序使用低层协议；protocol通常赋值"0"。 Socket()调用返回一个整型socket描述符，你可以在后面的调用使用它。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Socket描述符是一个指向内部数据结构的指针，它指向描述符表入口。调用Socket函数时，socket执行体将建立一个Socket，实际上"建立一个Socket"意味着为一个Socket数据结构分配存储空间。Socket执行体为你管理描述符表。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
两个网络程序之间的一个网络连接包括五种信息：通信协议、本地协议地址、本地主机端口、远端主机地址和远端协议端口。Socket数据结构中包含这五种信息。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; "><strong style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">Socket配置</strong><br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
通过socket调用返回一个socket描述符后，在使用socket进行网络传输以前，必须配置该socket。面向连接的socket客户端通过 调用Connect函数在socket数据结构中保存本地和远端信息。无连接socket的客户端和服务端以及面向连接socket的服务端通过调用 bind函数来配置本地信息。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Bind函数将socket与本机上的一个端口相关联，随后你就可以在该端口监听服务请求。Bind函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int bind(int sockfd,struct sockaddr *my_addr, int addrlen);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Sockfd是调用socket函数返回的socket描述符,my_addr是一个指向包含有本机IP地址及端口号等信息的sockaddr类型的指针；addrlen常被设置为sizeof(struct sockaddr)。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct sockaddr结构类型是用来保存socket信息的：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct sockaddr {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
unsigned short sa_family; /* 地址族， AF_xxx */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char sa_data[14]; /* 14 字节的协议地址 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
};<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
sa_family一般为AF_INET，代表Internet（TCP/IP）地址族；sa_data则包含该socket的IP地址和端口号。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
另外还有一种结构类型：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct sockaddr_in {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
short int sin_family; /* 地址族 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
unsigned short int sin_port; /* 端口号 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct in_addr sin_addr; /* IP地址 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
unsigned char sin_zero[8]; /* 填充0 以保持与struct sockaddr同样大小 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
};<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
这个结构更方便使用。sin_zero用来将sockaddr_in结构填充到与struct sockaddr同样的长度，可以用bzero()或memset()函数将其置为零。指向sockaddr_in 的指针和指向sockaddr的指针可以相互转换，这意味着如果一个函数所需参数类型是sockaddr时，你可以在函数调用的时候将一个指向 sockaddr_in的指针转换为指向sockaddr的指针；或者相反。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
使用bind函数时，可以用下面的赋值实现自动获得本机IP地址和随机获取一个没有被占用的端口号：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
my_addr.sin_port = 0; /* 系统随机选择一个未被使用的端口号 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
my_addr.sin_addr.s_addr = INADDR_ANY; /* 填入本机IP地址 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
通过将my_addr.sin_port置为0，函数会自动为你选择一个未占用的端口来使用。同样，通过将my_addr.sin_addr.s_addr置为INADDR_ANY，系统会自动填入本机IP地址。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
注意在使用bind函数是需要将sin_port和sin_addr转换成为网络字节优先顺序；而sin_addr则不需要转换。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
计算机数据存储有两种字节优先顺序：高位字节优先和低位字节优先。Internet上数据以高位字节优先顺序在网络上传输，所以对于在内部是以低位字节优先方式存储数据的机器，在Internet上传输数据时就需要进行转换，否则就会出现数据不一致。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
下面是几个字节顺序转换函数：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;htonl()：把32位值从主机字节序转换成网络字节序<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;htons()：把16位值从主机字节序转换成网络字节序<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;ntohl()：把32位值从网络字节序转换成主机字节序<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;ntohs()：把16位值从网络字节序转换成主机字节序<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Bind()函数在成功被调用时返回0；出现错误时返回"-1"并将errno置为相应的错误号。需要注意的是，在调用bind函数时一般不要将端口号置为小于1024的值，因为1到1024是保留端口号，你可以选择大于1024中的任何一个没有被占用的端口号。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; "><strong style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">连接建立</strong><br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
面向连接的客户程序使用Connect函数来配置socket并与远端服务器建立一个TCP连接，其函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int connect(int sockfd, struct sockaddr *serv_addr,int addrlen);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Sockfd 是socket函数返回的socket描述符；serv_addr是包含远端主机IP地址和端口号的指针；addrlen是远端地质结构的长度。 Connect函数在出现错误时返回-1，并且设置errno为相应的错误码。进行客户端程序设计无须调用bind()，因为这种情况下只需知道目的机器 的IP地址，而客户通过哪个端口与服务器建立连接并不需要关心，socket执行体为你的程序自动选择一个未被占用的端口，并通知你的程序数据什么时候到 打断口。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Connect函数启动和远端主机的直接连接。只有面向连接的客户程序使用socket时才需要将此socket与远端主机相连。无连接协议从不建立直接连接。面向连接的服务器也从不启动一个连接，它只是被动的在协议端口监听客户的请求。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Listen函数使socket处于被动的监听模式，并为该socket建立一个输入数据队列，将到达的服务请求保存在此队列中，直到程序处理它们。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int listen(int sockfd， int backlog);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Sockfd 是Socket系统调用返回的socket 描述符；backlog指定在请求队列中允许的最大请求数，进入的连接请求将在队列中等待accept()它们（参考下文）。Backlog对队列中等待 服务的请求的数目进行了限制，大多数系统缺省值为20。如果一个服务请求到来时，输入队列已满，该socket将拒绝连接请求，客户将收到一个出错信息。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
当出现错误时listen函数返回-1，并置相应的errno错误码。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
accept()函数让服务器接收客户的连接请求。在建立好输入队列后，服务器就调用accept函数，然后睡眠并等待客户的连接请求。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int accept(int sockfd, void *addr, int *addrlen);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
sockfd是被监听的socket描述符，addr通常是一个指向sockaddr_in变量的指针，该变量用来存放提出连接请求服务的主机的信息（某 台主机从某个端口发出该请求）；addrten通常为一个指向值为sizeof(struct sockaddr_in)的整型指针变量。出现错误时accept函数返回-1并置相应的errno值。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
首先，当accept函数监视的 socket收到连接请求时，socket执行体将建立一个新的socket，执行体将这个新socket和请求连接进程的地址联系起来，收到服务请求的 初始socket仍可以继续在以前的 socket上监听，同时可以在新的socket描述符上进行数据传输操作。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; "><strong style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">数据传输</strong><br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Send()和recv()这两个函数用于面向连接的socket上进行数据传输。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Send()函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int send(int sockfd, const void *msg, int len, int flags);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Sockfd是你想用来传输数据的socket描述符；msg是一个指向要发送数据的指针；Len是以字节为单位的数据的长度；flags一般情况下置为0（关于该参数的用法可参照man手册）。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Send()函数返回实际上发送出的字节数，可能会少于你希望发送的数据。在程序中应该将send()的返回值与欲发送的字节数进行比较。当send()返回值与len不匹配时，应该对这种情况进行处理。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char *msg = "Hello!";<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int len, bytes_sent;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#8230;&#8230;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
len = strlen(msg);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
bytes_sent = send(sockfd, msg,len,0);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#8230;&#8230;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
recv()函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int recv(int sockfd,void *buf,int len,unsigned int flags);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Sockfd是接受数据的socket描述符；buf 是存放接收数据的缓冲区；len是缓冲的长度。Flags也被置为0。Recv()返回实际上接收的字节数，当出现错误时，返回-1并置相应的errno值。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Sendto()和recvfrom()用于在无连接的数据报socket方式下进行数据传输。由于本地socket并没有与远端机器建立连接，所以在发送数据时应指明目的地址。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
sendto()函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int sendto(int sockfd, const void *msg,int len,unsigned int flags,const struct sockaddr *to, int tolen);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
该函数比send()函数多了两个参数，to表示目地机的IP地址和端口号信息，而tolen常常被赋值为sizeof (struct sockaddr)。Sendto 函数也返回实际发送的数据字节长度或在出现发送错误时返回-1。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Recvfrom()函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int recvfrom(int sockfd,void *buf,int len,unsigned int flags,struct sockaddr *from,int *fromlen);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
from是一个struct sockaddr类型的变量，该变量保存源机的IP地址及端口号。fromlen常置为sizeof (struct sockaddr)。当recvfrom()返回时，fromlen包含实际存入from中的数据字节数。Recvfrom()函数返回接收到的字节数或 当出现错误时返回-1，并置相应的errno。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
如果你对数据报socket调用了connect()函数时，你也可以利用send()和recv()进行数据传输，但该socket仍然是数据报socket，并且利用传输层的UDP服务。但在发送或接收数据报时，内核会自动为之加上目地和源地址信息。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; "><strong style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">结束传输</strong><br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
当所有的数据操作结束以后，你可以调用close()函数来释放该socket，从而停止在该socket上的任何数据操作：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
close(sockfd);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
你也可以调用shutdown()函数来关闭该socket。该函数允许你只停止在某个方向上的数据传输，而一个方向上的数据传输继续进行。如你可以关闭某socket的写操作而允许继续在该socket上接受数据，直至读入所有数据。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int shutdown(int sockfd,int how);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Sockfd是需要关闭的socket的描述符。参数 how允许为shutdown操作选择以下几种方式：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;0-------不允许继续接收数据<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;1-------不允许继续发送数据<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;2-------不允许继续发送和接收数据，<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#183;均为允许则调用close ()<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
shutdown在操作成功时返回0，在出现错误时返回-1并置相应errno。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; "><strong style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">Socket编程实例</strong><br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
代码实例中的服务器通过socket连接向客户端发送字符串"Hello, you are connected!"。只要在服务器上运行该服务器软件，在客户端运行客户软件，客户端就会收到该字符串。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
该服务器软件代码如下：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;stdio.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;stdlib.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;errno.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;string.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;sys/types.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;netinet/in.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;sys/socket.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;sys/wait.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#define SERVPORT 3333 /*服务器监听端口号 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#define BACKLOG 10 /* 最大同时连接请求数 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
main()<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
{<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int sockfd,client_fd; /*sock_fd：监听socket；client_fd：数据传输socket */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct sockaddr_in my_addr; /* 本机地址信息 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct sockaddr_in remote_addr; /* 客户端地址信息 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("socket创建出错！"); exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
my_addr.sin_family=AF_INET;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
my_addr.sin_port=htons(SERVPORT);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
my_addr.sin_addr.s_addr = INADDR_ANY;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
bzero(&amp;(my_addr.sin_zero),8);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if (bind(sockfd, (struct sockaddr *)&amp;my_addr, sizeof(struct sockaddr)) == -1) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("bind出错！");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if (listen(sockfd, BACKLOG) == -1) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("listen出错！");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
while(1) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
sin_size = sizeof(struct sockaddr_in);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if ((client_fd = accept(sockfd, (struct sockaddr *)&amp;remote_addr, &amp;sin_size)) == -1) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("accept出错");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
continue;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if (!fork()) { /* 子进程代码段 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("send出错！");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
close(client_fd);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(0);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
close(client_fd);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
服务器的工作流程是这样的：首先调用socket函数创建一个Socket，然后调用bind函数将其与本机地址以及一个本地端口号绑定，然后调用 listen在相应的socket上监听，当accpet接收到一个连接服务请求时，将生成一个新的socket。服务器显示该客户机的IP地址，并通过 新的socket向客户端发送字符串"Hello，you are connected!"。最后关闭该socket。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
代码实例中的fork()函数生成一个子进程来处理数据传输部分，fork()语句对于子进程返回的值为0。所以包含fork函数的if语句是子进程代码部分，它与if语句后面的父进程代码部分是并发执行的。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">客户端程序代码如下：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include&lt;stdio.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;stdlib.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;errno.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;string.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;netdb.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;sys/types.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;netinet/in.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;sys/socket.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#define SERVPORT 3333<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#define MAXDATASIZE 100 /*每次最大数据传输量 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
main(int argc, char *argv[]){<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int sockfd, recvbytes;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char buf[MAXDATASIZE];<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct hostent *host;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct sockaddr_in serv_addr;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if (argc &lt; 2) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
fprintf(stderr,"Please enter the server's hostname!\n");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if((host=gethostbyname(argv[1]))==NULL) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
herror("gethostbyname出错！");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("socket创建出错！");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
serv_addr.sin_family=AF_INET;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
serv_addr.sin_port=htons(SERVPORT);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
serv_addr.sin_addr = *((struct in_addr *)host-&gt;h_addr);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
bzero(&amp;(serv_addr.sin_zero),8);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if (connect(sockfd, (struct sockaddr *)&amp;serv_addr, \<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
sizeof(struct sockaddr)) == -1) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("connect出错！");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if ((recvbytes=recv(sockfd, buf, MAXDATASIZE, 0)) ==-1) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("recv出错！");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
buf[recvbytes] = '\0';<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
printf("Received: %s",buf);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
close(sockfd);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
客户端程序首先通过服务器域名获得服务器的IP地址，然后创建一个socket，调用connect函数与服务器建立连接，连接成功之后接收从服务器发送过来的数据，最后关闭socket。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
函数gethostbyname()是完成域名转换的。由于IP地址难以记忆和读写，所以为了方便，人们常常用域名来表示主机，这就需要进行域名和IP地址的转换。函数原型为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct hostent *gethostbyname(const char *name);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
函数返回为hosten的结构类型，它的定义如下：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct hostent {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char *h_name; /* 主机的官方域名 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char **h_aliases; /* 一个以NULL结尾的主机别名数组 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int h_addrtype; /* 返回的地址类型，在Internet环境下为AF-INET */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int h_length; /* 地址的字节长度 */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char **h_addr_list; /* 一个以0结尾的数组，包含该主机的所有地址*/<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
};<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#define h_addr h_addr_list[0] /*在h-addr-list中的第一个地址*/<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
当 gethostname()调用成功时，返回指向struct hosten的指针，当调用失败时返回-1。当调用gethostbyname时，你不能使用perror()函数来输出错误信息，而应该使用herror()函数来输出。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">　　无连接的客户/服务器程序的在原理上和连接的客户/服务器是一样的，两者的区别在于无连接的客户/服务器中的客户一般不需要建立连接，而且在发送接收数据时，需要指定远端机的地址。</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">阻塞和非阻塞<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
阻塞函数在完成其指定的任务以前不允许程序调用另一个函数。例如，程序执行一个读数据的函数调用时，在此函数完成读操作以前将不会执行下一程序语句。当 服务器运行到accept语句时，而没有客户连接服务请求到来，服务器就会停止在accept语句上等待连接服务请求的到来。这种情况称为阻塞 （blocking）。而非阻塞操作则可以立即完成。比如，如果你希望服务器仅仅注意检查是否有客户在等待连接，有就接受连接，否则就继续做其他事情，则 可以通过将Socket设置为非阻塞方式来实现。非阻塞socket在没有客户在等待时就使accept调用立即返回。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;unistd.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;fcntl.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#8230;&#8230;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
sockfd = socket(AF_INET,SOCK_STREAM,0);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
fcntl(sockfd,F_SETFL,O_NONBLOCK)；<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
&#8230;&#8230;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
通过设置socket为非阻塞方式，可以实现"轮询"若干Socket。当企图从一个没有数据等待处理的非阻塞Socket读入数据时，函数将立即返 回，返回值为-1，并置errno值为EWOULDBLOCK。但是这种"轮询"会使CPU处于忙等待方式，从而降低性能，浪费系统资源。而调用 select()会有效地解决这个问题，它允许你把进程本身挂起来，而同时使系统内核监听所要求的一组文件描述符的任何活动，只要确认在任何被监控的文件 描述符上出现活动，select()调用将返回指示该文件描述符已准备好的信息，从而实现了为进程选出随机的变化，而不必由进程本身对输入进行测试而浪费 CPU开销。Select函数原型为:<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int select(int numfds,fd_set *readfds,fd_set *writefds，<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
fd_set *exceptfds,struct timeval *timeout);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
其中readfds、writefds、exceptfds分别是被select()监视的读、写和异常处理的文件描述符集合。如果你希望确定是否可以 从标准输入和某个socket描述符读取数据，你只需要将标准输入的文件描述符0和相应的sockdtfd加入到readfds集合中；numfds的值 是需要检查的号码最高的文件描述符加1，这个例子中numfds的值应为sockfd+1；当select返回时，readfds将被修改，指示某个文件 描述符已经准备被读取，你可以通过FD_ISSSET()来测试。为了实现fd_set中对应的文件描述符的设置、复位和测试，它提供了一组宏：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
FD_ZERO(fd_set *set)----清除一个文件描述符集；<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
FD_SET(int fd,fd_set *set)----将一个文件描述符加入文件描述符集中；<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
FD_CLR(int fd,fd_set *set)----将一个文件描述符从文件描述符集中清除；<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
FD_ISSET(int fd,fd_set *set)----试判断是否文件描述符被置位。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
Timeout参数是一个指向struct timeval类型的指针，它可以使select()在等待timeout长时间后没有文件描述符准备好即返回。struct timeval数据结构为：<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct timeval {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int tv_sec; /* seconds */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int tv_usec; /* microseconds */<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
};</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">POP3客户端实例<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
下面的代码实例基于POP3的客户协议，与邮件服务器连接并取回指定用户帐号的邮件。与邮件服务器交互的命令存储在字符串数组POPMessage中，程序通过一个do-while循环依次发送这些命令。<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include&lt;stdio.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;stdlib.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;errno.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;string.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;netdb.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;sys/types.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;netinet/in.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#include &lt;sys/socket.h&gt;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#define POP3SERVPORT 110<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
#define MAXDATASIZE 4096</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">main(int argc, char *argv[]){<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int sockfd;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct hostent *host;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
struct sockaddr_in serv_addr;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char *POPMessage[]={<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
"USER userid\r\n",<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
"PASS password\r\n",<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
"STAT\r\n",<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
"LIST\r\n",<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
"RETR 1\r\n",<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
"DELE 1\r\n",<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
"QUIT\r\n",<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
NULL<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
};<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int iLength;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int iMsg=0;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
int iEnd=0;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
char buf[MAXDATASIZE];</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">if((host=gethostbyname("your.server"))==NULL) {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("gethostbyname error");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("socket error");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
serv_addr.sin_family=AF_INET;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
serv_addr.sin_port=htons(POP3SERVPORT);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
serv_addr.sin_addr = *((struct in_addr *)host-&gt;h_addr);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
bzero(&amp;(serv_addr.sin_zero),8);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
if (connect(sockfd, (struct sockaddr *)&amp;serv_addr,sizeof(struct sockaddr))==-1){<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
perror("connect error");<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
exit(1);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">do {<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
send(sockfd,POPMessage[iMsg],strlen(POPMessage[iMsg]),0);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
printf("have sent: %s",POPMessage[iMsg]);</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">iLength=recv(sockfd,buf+iEnd,sizeof(buf)-iEnd,0);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
iEnd+=iLength;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
buf[iEnd]='\0';<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
printf("received: %s,%d\n",buf,iMsg);</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">iMsg++;<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
} while (POPMessage[iMsg]);</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">close(sockfd);<br style="font-family: arial, sans-serif, 宋体; line-height: 22px; " />
}</p>
<p style="font-family: arial, sans-serif, 宋体; line-height: 22px; ">来自：Li</p>
</span>
<img src ="http://www.blogjava.net/tourer/aggbug/316097.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-03-21 21:01 <a href="http://www.blogjava.net/tourer/archive/2010/03/21/316097.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Eclipse 打包jar</title><link>http://www.blogjava.net/tourer/archive/2010/03/13/315338.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Sat, 13 Mar 2010 10:06:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/03/13/315338.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/315338.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/03/13/315338.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/315338.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/315338.html</trackback:ping><description><![CDATA[总体思路是先打成jar再把jar打成exe。主要看1.3和2.3里的内容就可以了。
<br />
<br />
<br />
1．将项目打成jar:
<br />
<br />
<br />
1.1
要将项目打包成jar文件，方法很多，可以用Eclipse自带的打包工具Ant打包，也可以用Eclipse的Export生成jar。经过尝试后，我
不推荐用Ant打包，因为要自己编写xml脚本语言，还要增加一些外部的jar，所以我打了好几次都没打成。
<br />
<br />
<br />
1.2
在这里介绍两种方法生成jar，第一种是用Eclpise的Export功能。在要打包的项目上击右键，选择Export，在窗口中选择Java里的
JAR file。Next后的窗口中已经自动选好了要打包的项目，用户可以点击加号查看项目里被打包的内容。在下面的JAR
file里设置你打包生成jar文件的输出目录，下一步在出现的窗口中选择Use existing manifest from
workspace，在下面的Main
class后面直接点Browse，它会自动列出你项目中有主函数main的类。选择主类后点Finish即可生成jar文件。在此说明一下，这种打包方
法不能把项目中的外部的jar包打进来，因该是也要编写一些脚本语言，没往深研究。所以生成后的jar有些是不能执行的。
<br />
<br />
<br />
1.3 第二种方法是利用Eclipse的一个第三方插件fatjar生成jar文件，也是本人觉得最简单最方便的一种生成方式。先从网上下载些
插件，解压后是一个plugins的文件夹，里面只有一个文件夹，我的是&#8220;net.sf.fjep.fatjar_0.0.24&#8221;将它copy到
Eclipser plugins文件夹下，此插件就安装成功了，重启Eclipse在项目上右击就会看到多出一个&#8220;Build Fat
Jar&#8221;在前面有个绿色的&#8220;+&#8221;号，这时你就可以用此插件打包你的项目了。进去后第一个界面Jar-Name里增入要生成的jar文件名，我的是
&#8220;CAMP_fat.jar&#8221;。在Main-Class后点Browse像Export一样它也会列出你项目中的主类，选择后其它默认即可，Next后会
列出你要打包的所有内容，这个插件的优势就是可以将你项目中的外部jar也打进来，有三个先项，其中Export
ANT是生成build.xml脚本文件，方便用户以后修改脚本，其它两个按钮没用。在这里什么都不点，直接点Ｆinish就可以生成jar文件。
<br />
<br />
<br />
2.将jar打成.exe文件：
<br />
<br />
<br />
2.1
虽然此时的jar文件已经可以执行了。生成.exe的文件我也是用两种方法实现的，用到的打包工具是j2ewiz和exe4j，它们的不同会在我下面的介
绍中体现出来。
<br />
<br />
<br />
2.2 首先是j2ewiz，这个软件是绿色的，不用安装，解压后可以直接运行，但这个软件生成的
.exe文件不是跨平台的。运行此程序首先就是输入要打包的jar文件，我们浏览JAR选择我们之前用fatjar生成的&#8220;CAMP_fat.jar&#8221;项
目文件（详见1.3），下面那个选项是提示用户最低要求的JRE版本，一般选1.3。下一步，因为我们的寝室管理系统是图形界面，所以在这里选
&#8220;Ｗindows窗口程序&#8221;下一步它也是自动生成要执行的主类，你只要选择就可以。下面的选框可以选择你启动程序显示的图片。下一步后这个窗可按个人喜好
选择。下一步，如果你的程序还有什么依赖的外部jar文件，可以从这里加上，但因为之前的fatjar以经将我们项目所用的那三个连数据库的外部类打进
CAMP_fat.jar包里了，所以这里不用再添加。如果你之前是用Ｅxport打的jar
包，那么这里就需要再把那个三个数据库的包加进来了（详见1.2）。下一步是添入要生成的.exe文件名，再选一个程序图标就可以了，下一步后生
成.exe文件，点完成。双击生成的.exe文件就能看到运行效果了，这种exe文件还没有脱离JDK环境，还不能跨平台使用，只能用于小组成员测试使
用。
<br />
<br />
<br />
2.3
下面进入最关键的，如何打包跨平台的.exe文件。用到的软件是exe4j,我用的是V4.0版的，此软件需要破解。安装后运行左窗窗口标有十步，其实打
包过程也非常简单。第一步完全略过，直接点Next第二步我们选择&#8220;JAR in EXE mode&#8221;
就是选择我们已经有制作好的jar文件。第3步上面是项目名称，可随便填写，下面一个写出你想要将打包后的exe文件输出的目录我的是&#8220;桌
面\project\&#8221;。第4步，由于我的演示程序是图形的，所以选第一个，如果你的程序是控制台的，则选择第二个，Executable
name写你将要生成的.exe文件的名字，Icon
File可以选择生成文件的图标。第5步，先别管上面的，先在下面单击绿色的&#8220;+&#8221;号，在弹出的窗口中点Archive，然后找到起初已经做好的
CAMP_fat.jar（详见1.3）文件，"OK"后返回，在下面的Class Path里就出现jar文件路径后，再在上面Main
Class栏内点击找到main所在的类。第6步，你系统的JRE版本，一般是填个1.3，下面填1.6在这里单击advanced
options，选择search
sequence。选这个就是因为我们要把JDK环境也打包进来，好让程序能跨平台使用。首先要从你系统的JDK下的JRE目录copy到你.exe文件
的输出目录下&#8220;桌面\project\JRE&#8221;，然后回到exe4j中在弹出窗口删除列表中的所有项。我的是三项，一个注册表的，一个JAVA环境变量
的，一个JDK环境变量的，都不要。然后单击绿&#8220;+&#8221;，选择directory并选择JRE的根目录，我的是&#8220;桌面\project\JRE&#8221;就是
copy后的目录，选完后exe4j弹出窗口中的Directory里会显示&#8220;.\JRE&#8221;。点OK关闭该窗口，返回exe4j的主窗口，你就可以看到刚
加的路径。再从主窗口左侧窗口中单击advanced options，并选择preferred VM，在弹出的窗口中选择client
hostspot VM，单击next按钮继续。7、8步是一些个性设置默认即可。第9步编译完后第10步你点那个&#8220;Click Here to
Start the Application&#8221;按钮就可以看到程序运行效果了，然后再点&#8221;Seave
as&#8221;保存一个exe4j生成的一个文件，随便存哪里都行，和我们的.exe程序无关。全部制作过程就完工了。
<img src ="http://www.blogjava.net/tourer/aggbug/315338.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-03-13 18:06 <a href="http://www.blogjava.net/tourer/archive/2010/03/13/315338.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Linux 硬链接与软链接 </title><link>http://www.blogjava.net/tourer/archive/2010/03/11/315187.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Thu, 11 Mar 2010 08:07:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/03/11/315187.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/315187.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/03/11/315187.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/315187.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/315187.html</trackback:ping><description><![CDATA[首先要弄清楚,在Linux系统中,内核为每一个新创建的文件分配一个Inode(索引结点),每个文件都有一个惟一的inode号。文件属性保存在索引结点里，在访问文件时，索引结点被复制到内存在，从而实现文件的快速访问。
<br />
<br />
链接是一种在共享文件和访问它的用户的若干目录项之间建立联系的一种方法。Linux中包括两种链接：硬链接(Hard Link)和软链接(Soft Link),软链接又称为符号链接（Symbolic link）。
<br />
<br />
一、软链接（符号链接）
<br />
<br />
软链接克服了硬链接的不足，没有任何文件系统的限制，任何用户可以创建指向目录的符号链接。因而现在更为广泛使用，它具有更大的灵活性，甚至可以跨越不同机器、不同网络对文件进行链接。
<br />
<br />
建立软链接，只要在ln后面加上选项 &#8211;s。
<br />
<br />
<br />
<br />
二、硬链接
<br />
<br />
硬链接说白了是一个指针，指向文件索引节点，系统并不为它重新分配inode。可以用:ln命令来建立硬链接。语法
<br />
<br />
ln [options] existingfile newfile
<br />
ln[options] existingfile-list directory
<br />
<br />
用法:
第一种:为&#8221;existingfile&#8221;创建硬链接,文件名为&#8221;newfile&#8221;。第二种:在&#8221;directory&#8221;目录中,
为&#8221;existingfile-list&#8221;中包含的所有文件创建一个同名的硬链接。常用可选[options] &#8211;f
无论&#8221;newfile&#8221;存在与否,都创建链接。-n 如果&#8221;newfile&#8221;已存在,就不创建链接。&nbsp;
<img src ="http://www.blogjava.net/tourer/aggbug/315187.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-03-11 16:07 <a href="http://www.blogjava.net/tourer/archive/2010/03/11/315187.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>JDK和JRE到区别</title><link>http://www.blogjava.net/tourer/archive/2010/03/11/315165.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Thu, 11 Mar 2010 04:27:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/03/11/315165.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/315165.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/03/11/315165.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/315165.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/315165.html</trackback:ping><description><![CDATA[(1)Jre 是java runtime environment,
是java程序的运行环境。既然是运行，当然要包含jvm，也就是大家熟悉的虚拟机啦，
还有所有java类库的class文件，都在lib目录下打包成了jar。大家可以自己验证。至于在windows上的虚拟机是哪个文件呢？
学过MFC的都知道什么是dll文件吧，那么大家看看jre/bin/client里面是不是有一个jvm.dll呢？那就是虚拟机。
<br />
<br />
(2)Jdk 是java development kit，是java的开发工具包，里面包含了各种类库和工具。当然也包括了另外一个Jre.
那么为什么要包括另外一个Jre呢？而且jdk/jre/bin同时有client和server两个文件夹下都包含一个jvm.dll。
说明是有两个虚拟机的。这一点不知道大家是否注意到了呢？
<br />
&nbsp; 相信大家都知道jdk的bin下有各种java程序需要用到的命令，与jre的bin目录最明显的区别就是jdk下才有javac，这一点很好理解，因为
jre只是一个运行环境而已。与开发无关，正因为如此，具备开发功能的jdk自己的jre下才会同时有client性质的jvm和server性质的jvm， 而仅仅作为运行环境的jre下只需要client性质的jvm.dll就够了。
<br />
<br />
(3)记得在环境变量path中设置jdk/bin路径麽？这应该是大家学习Java的第一步吧，
老师会告诉大家不设置的话javac和java是用不了的。确实jdk/bin目录下包含了所有的命令。可是有没有人想过我们用的java命令并不是
jdk/bin目录下的而是jre/bin目录下的呢？不信可以做一个实验，大家可以把jdk/bin目录下的java.exe剪切到别的地方再运行
java程序，发现了什么？一切OK！
<br />
&nbsp; 那么有人会问了？我明明没有设置jre/bin目录到环境变量中啊？
<br />
试想一下如果java为了提供给大多数人使用，他们是不需要jdk做开发的，只需要jre能让java程序跑起来就可以了，那么每个客户还需要手
动去设置环境变量多麻烦啊？所以安装jre的时候安装程序自动帮你把jre的java.exe添加到了系统变量中，验证的方法很简单，大家看到了系统环境
变量的
path最前面有&#8220;%SystemRoot%\system32;%SystemRoot%;&#8221;这样的配置，那么再去Windows/system32下
面去看看吧，发现了什么？有一个java.exe。
<br />
&nbsp; 如果强行能够把jdk/bin挪到system32变量前面，当然也可以迫使使用jdk/jre里面的java，不过除非有必要，我不建议大家这么做。使用单独的jre跑java程序也算是客户环境下的一种测试。&nbsp;
<img src ="http://www.blogjava.net/tourer/aggbug/315165.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-03-11 12:27 <a href="http://www.blogjava.net/tourer/archive/2010/03/11/315165.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>关于2009年12月全国大学英语四、六级考试成绩发布时间的通知</title><link>http://www.blogjava.net/tourer/archive/2010/03/03/314339.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Tue, 02 Mar 2010 16:50:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2010/03/03/314339.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/314339.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2010/03/03/314339.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/314339.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/314339.html</trackback:ping><description><![CDATA[<div id="content">
<h3 style="margin-top: 10px; margin-bottom: 20px; font-size: 16px; color: #6296f9;">
关于2009年12月全国大学英语四、六级考试成绩发布时间的通知:</h3>
<p style="font-weight: bold;">2009年12月全国大学英语四、六级考试成绩将于
2010年3月3日上午9点发布。</p>
<p>成绩查询方式</p>
<p>网上免费查分：</p>
<p style="text-indent: 2em;">网址： cet.99sushe.com</p>
<p style="text-indent: 2em;">运营商： 99宿舍网</p>
<p style="text-indent: 2em;">客服电话： 010-58699163转867</p>
<p>收费短信查分（2010年3月3日上午9点开始）：</p>
<p style="text-indent: 2em;">中国移动、联通、电信手机用户：</p>
<p style="text-indent: 2em;">发送A 加 15位准考证号到 1066335577</p>
<p style="text-indent: 2em;">如A123456789012345到
1066335577查询成绩（1元/条，不含通信费）</p>
<p>特别注意：</p>
<p style="text-indent: 2em;">河北省的中国移动手机用户：发送 8 加
15位准考证号到 10661660</p>
<p style="text-indent: 2em;">如8123456789012345到 10661660
查询成绩（1元/条，不含通信费）</p>
<p style="text-indent: 2em;">运营商： 空中网 </p>
<p style="text-indent: 2em;">客服电话： 010-68083018</p>
<p>注：2009年12月网考成绩发布方式和日期另行通知。</p>
<p class="right" style="text-align: right;">
全国大学英语四、六级考试委员会办公室</p>
<p class="right" style="margin-bottom: 20px; text-align: right;">
2010年2月24日</p>
</div>
<img src ="http://www.blogjava.net/tourer/aggbug/314339.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2010-03-03 00:50 <a href="http://www.blogjava.net/tourer/archive/2010/03/03/314339.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>SWT可交互式Browser控件</title><link>http://www.blogjava.net/tourer/archive/2009/12/29/307649.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Tue, 29 Dec 2009 08:28:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2009/12/29/307649.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/307649.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2009/12/29/307649.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/307649.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/307649.html</trackback:ping><description><![CDATA[在许多<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%C6%BD%CC%A8">平台</span>中，Browser<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%BF%D8%BC%FE">控件</span>皆被做为一个必需的控件给出，并提供了DOM接口，用于<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%B7%C3%CE%CA">访问</span>Browser的内容，相对来说SWT中的Browser控件就比较薄弱，没有提供DOM的可控制接口，那么，如何和控件所加载的<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%D2%B3%C3%E6">页面</span>进行交互呢？比如需要在集成web<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%D3%A6%D3%C3">应用</span>的<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%BB%B7%BE%B3">环境</span>中实现模仿登陆、<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%D7%D4%B6%AF">自动</span>填表等<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%B9%A6%C4%DC">功能</span>。 <br />
SWT中对Browser有不同的实现，目前实现的有IE和Mozilla。在Browser的构造<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%BA%AF%CA%FD">函数</span>中根据不同的平台和不同的style<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%C9%E8%D6%C3">设置</span>类决定使用哪个类的实现。 <br />
<br />
org.eclipse.swt.browser.Mozilla org.eclipse.swt.browser.IE 是已经实现的，而其他的
org.eclipse.swt.browser.Safari org.eclipse.swt.browser.Voyager <br />
<span>
来源:<a linkindex="22" href="http://www.va1314.com/bc" class="smarterwiki-linkify">www.va1314.com/bc</a></span><br />
则没有实现。 <br />
<br />
<br />
public Browser (Composite parent, int style) { <br />
<br />
super (checkParent (parent), checkStyle (style)); <br />
<br />
String platform = SWT.getPlatform (); <br />
<br />
Display display = parent.getDisplay (); <br />
<br />
if ("gtk".equals (platform)) display.setData (NO_INPUT_METHOD, null); //$NON-NLS-1$ <br />
<br />
String className = null; <br />
<br />
if ((style &amp; SWT.MOZILLA) != 0) { <br />
<br />
className = "org.eclipse.swt.browser.Mozilla"; //$NON-NLS-1$ <br />
<br />
} else { <br />
<br />
if ("win32".equals (platform) || "wpf".equals (platform)) { //$NON-NLS-1$ $NON-NLS-2$ <br />
<br />
className = "org.eclipse.swt.browser.IE"; //$NON-NLS-1$ <br />
<br />
} else if ("motif".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Mozilla"; //$NON-NLS-1$ <br />
<br />
} else if ("gtk".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Mozilla"; //$NON-NLS-1$ <br />
<br />
} else if ("carbon".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Safari"; //$NON-NLS-1$ <br />
<br />
} else if ("photon".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Voyager"; //$NON-NLS-1$ <br />
<br />
} else { <br />
<br />
dispose (); <br />
<br />
SWT.error (SWT.ERROR_NO_HANDLES); <br />
<br />
} <br />
<br />
} <br />
<br />
<br />
<br />
try { <br />
<br />
Class clazz = Class.forName (className); <br />
<br />
webBrowser = (<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=Web">Web</span>Browser)clazz.newInstance (); <br />
<br />
} catch (ClassNotFoundException e) { <br />
<br />
} catch (Illegal<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=Access">Access</span>Exception e) { <br />
<br />
} catch (InstantiationException e) { <br />
<br />
} <br />
<br />
if (webBrowser == null) { <br />
<br />
dispose (); <br />
<br />
SWT.error (SWT.ERROR_NO_HANDLES); <br />
<br />
} <br />
<br />
<br />
<br />
webBrowser.setBrowser (this); <br />
<br />
webBrowser.create (parent, style); <br />
<br />
} <br />
<br />
public Browser (Composite parent, int style) { <br />
<br />
super (checkParent (parent), checkStyle (style)); <br />
<br />
String platform = SWT.getPlatform (); <br />
<br />
Display display = parent.getDisplay (); <br />
<br />
if ("gtk".equals (platform)) display.setData (NO_INPUT_METHOD, null); //$NON-NLS-1$ <br />
<br />
String className = null; <br />
<br />
if ((style &amp; SWT.MOZILLA) != 0) { <br />
<br />
className = "org.eclipse.swt.browser.Mozilla"; //$NON-NLS-1$ <br />
<br />
} else { <br />
<br />
if ("win32".equals (platform) || "wpf".equals (platform)) { //$NON-NLS-1$ $NON-NLS-2$ <br />
<br />
className = "org.eclipse.swt.browser.IE"; //$NON-NLS-1$ <br />
<br />
} else if ("motif".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Mozilla"; //$NON-NLS-1$ <br />
<br />
} else if ("gtk".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Mozilla"; //$NON-NLS-1$ <br />
<br />
} else if ("carbon".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Safari"; //$NON-NLS-1$ <br />
<br />
} else if ("photon".equals (platform)) { //$NON-NLS-1$ <br />
<br />
className = "org.eclipse.swt.browser.Voyager"; //$NON-NLS-1$ <br />
<br />
} else { <br />
<br />
dispose (); <br />
<br />
SWT.error (SWT.ERROR_NO_HANDLES); <br />
<br />
} <br />
<br />
} <br />
<br />
<br />
<br />
try { <br />
<br />
Class clazz = Class.forName (className); <br />
<br />
webBrowser = (WebBrowser)clazz.newInstance (); <br />
<br />
} catch (ClassNotFoundException e) { <br />
<br />
} catch (IllegalAccessException e) { <br />
<br />
} catch (InstantiationException e) { <br />
<br />
} <br />
<br />
if (webBrowser == null) { <br />
<br />
dispose (); <br />
<br />
SWT.error (SWT.ERROR_NO_HANDLES); <br />
<br />
} <br />
<br />
<br />
<br />
webBrowser.setBrowser (this); <br />
<br />
webBrowser.create (parent, style); <br />
<br />
} <br />
<br />
其中对IE的实现主要是采用调用IE的Activex控件，间接加载IE，对Mozilla由于<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%B4%FA%C2%EB">代码</span>过多，本人没有具体研究，其本身开源，有兴趣能够参看。 <br />
<br />
那么回归主题，如何实现与Browser控件的交互呢？ 其实仔细看Browser控件的API，能够发觉一个execute()方法，这个方法适用于在web文档加载完毕时能够<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%D4%CB%D0%D0">运行</span>javascript
code的。这样的话，交互就变得简单了，因为javascript是提供dom的支持的，既然能够调用javascript，那么就能够调用web页面
中的每个节点了。控制的问题处理了，可是另外的问题来了。 如何从javascript的code里边前往<span class="t_tag" href="http://hi.baidu.com/annleecn/blog/item/tag.php?name=%CA%FD%BE%DD">数据</span>呢？
比如我需要将一个&lt;input type=text id=textid /&gt;的值前往到java
code中。其实采用的方法是很投机的，因为execute()方法前往的结果是true or
false，那么对它做文章是没有用的，我们看其他的api，能够发觉：addStatusTextListener()方法。
这个方法能够监听web页面对于statusbar文本改变的值，并反映在java
code里面，那么我们只需通过javascript把前往的值写到window.status，那么就能够在javacode里取到了。
具体代码请参考下面，对于Browser的承继重写，通过getValue能够取得指定id的html 控件的值，通过setValue能够设置值。
view plaincopy to clipboardprint? <br />
<br />
import org.eclipse.swt.browser.Browser; <br />
<br />
import org.eclipse.swt.browser.StatusTextEvent; <br />
<br />
import org.eclipse.swt.browser.StatusTextListener; <br />
<br />
import org.eclipse.swt.widgets.Composite; <br />
<br />
<br />
<br />
public class CoolBrowser extends Browser implements StatusTextListener { <br />
<br />
<br />
<br />
private final String DATA = "Browser_Data"; <br />
<br />
<br />
<br />
public CoolBrowser(Composite parent, int style) { <br />
<br />
super(parent, style); <br />
<br />
addStatusTextListener(this); <br />
<br />
} <br />
<br />
<br />
<br />
@Override <br />
<br />
protected void checkSubclass() { <br />
<br />
} <br />
<br />
<br />
<br />
/** <br />
<br />
* Get the value of one input control in the web <br />
<br />
* @param id <br />
<br />
* @return <br />
<br />
*/ <br />
<br />
public String getValue(String id) { <br />
<br />
if (execute("var obj = document.getElementById('" + id + "');" <br />
<br />
+ "if( obj != null ) window.status=obj.value;")) { <br />
<br />
return (String) getData(DATA); <br />
<br />
} <br />
<br />
return null; <br />
<br />
} <br />
<br />
<br />
<br />
/** <br />
<br />
* Set the value of the input control <br />
<br />
* @param id <br />
<br />
* @param value <br />
<br />
*/ <br />
<br />
public void setValue( String id, Object value ){ <br />
<br />
if (execute("var obj = document.getElementById('" + id + "');" <br />
<br />
+ "if( obj != null ) obj.value='" + value + "';")) { <br />
<br />
} <br />
<br />
} <br />
<br />
<br />
<br />
@Override <br />
<br />
public void changed(StatusTextEvent event) { <br />
<br />
setData(DATA, event.text); <br />
<br />
} <br />
<br />
<br />
<br />
}
<img src ="http://www.blogjava.net/tourer/aggbug/307649.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2009-12-29 16:28 <a href="http://www.blogjava.net/tourer/archive/2009/12/29/307649.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Windows7 简体中文旗舰版下载 (MSDN官方发布正式版原版镜像)(转)</title><link>http://www.blogjava.net/tourer/archive/2009/12/20/306738.html</link><dc:creator>xiaoxinchen</dc:creator><author>xiaoxinchen</author><pubDate>Sun, 20 Dec 2009 12:14:00 GMT</pubDate><guid>http://www.blogjava.net/tourer/archive/2009/12/20/306738.html</guid><wfw:comment>http://www.blogjava.net/tourer/comments/306738.html</wfw:comment><comments>http://www.blogjava.net/tourer/archive/2009/12/20/306738.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/tourer/comments/commentRss/306738.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/tourer/services/trackbacks/306738.html</trackback:ping><description><![CDATA[下载地址：http://www.iplaysoft.com/windows7-msdn-iso.html<br />
<img src ="http://www.blogjava.net/tourer/aggbug/306738.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/tourer/" target="_blank">xiaoxinchen</a> 2009-12-20 20:14 <a href="http://www.blogjava.net/tourer/archive/2009/12/20/306738.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>