使用Mysql-bind实现mysql管理bind配置

bind默认都是用文件来管理zone的信息,通过mysql与bind的结合,可以使用mysql来进行管理,这样变更,添加将更加方便。

http://mysql-bind.sourceforge.net/docs.php

一、 安装Mysql
        因为后面需要使用mysql的头文件和库文件,所以我这边使用源码安装,当然,如果单独安装Headers and libraries应该也是可以的。
        1、下载mysql
        2、安装mysql,这个直接看INSTALL-SOURCE安装知道就可以了

 

     shell> groupadd mysql
     shell> useradd -g mysql mysql
     shell> gunzip < mysql-VERSION.tar.gz | tar -xvf -
     shell> cd mysql-VERSION
     shell> ./configure --prefix=/usr/local/mysql
     shell> make
     shell> make install
     shell> cp support-files/my-medium.cnf /etc/my.cnf
     shell> cd /usr/local/mysql
     shell> bin/mysql_install_db --user=mysql
     shell> chown -R root  .
     shell> chown -R mysql var
     shell> chgrp -R mysql .
     shell> bin/mysqld_safe --user=mysql &

        3、注意,这样安装好以后,我们的头文件和库文件分别在:
        /usr/local/mysql/include/mysql/        和         /usr/local/mysql/lib/mysql

二、安装bind和mysql-bind
        1、分别下载bindmysql-bind ,并解压
        2、mysql-bind里面主要有mysqldb.c和mysqldb.h两个文件,分别拷贝到bind源文件的bin/named和bin/named/include/named/目录
        3、编辑bind源文件目录的bin/named/Makefile.in文件,修改如下几个字段:

 

DBDRIVER_OBJS = mysqldb.@O @
DBDRIVER_SRCS = mysqldb.c
DBDRIVER_INCLUDES = -I'/usr/local/mysql/include/mysql/'
DBDRIVER_LIBS = -L'/usr/local/mysql/lib/mysql' -lmysqlclient -lz -lcrypt -lnsl -lm -lc -lnss_files -lnss_dns -lresolv -lc -lnss_files -lnss_dns -lresolv

        4、编辑bind源文件bin/named/main.c
                4.1、包含mysqldb.h,#include <named/mysqldb.h>
                4.2、在函数setup(void)里面ns_server_create()的前面添加mysqldb_init(),如

 

        /*
         * Add calls to register sdb drivers here.
         */
        /* xxdb_init(); */
        mysqldb_init();
        ns_server_create(ns_g_mctx, &ns_g_server);

                 4.3、在函数cleanup(void)里面ns_server_destroy()的后面添加mysqldb_clear(),如

 

        ns_server_destroy(&ns_g_server);
        mysqldb_clear();
        /*
         * Add calls to unregister sdb drivers here.
         */
        /* xxdb_clear(); */

        5、编译安装bind 

 

./configure
make
make install

三、配置
        1、启动named,第一次运行它提示找不到libmysqlclient.so.15,但是在mysql编译安装的时候已经生成了这个文件,于是手动拷贝他到/usr/lib/libmysqlclient.so.15,启动正常,可以解析所有域名。
        2、配置数据库
                2.1、创建数据库:create database test1;
                2.2、创建表:

 

CREATE TABLE mydomain (
  name varchar(255) default NULL,
  ttl int(11) default NULL,
  rdtype varchar(255) default NULL,
  rdata varchar(255) default NULL
) TYPE=MyISAM;

                2.3、添加测试数据

 

INSERT INTO mydomain VALUES ('mydomain.com', 259200, 'SOA', 'mydomain.com. www.mydomain.com . 200309181 28800 7200 86400 28800');
INSERT INTO mydomain VALUES ('mydomain.com', 259200, 'NS', 'ns0.mydomain.com.');
INSERT INTO mydomain VALUES ('mydomain.com', 259200, 'NS', 'ns1.mydomain.com.');
INSERT INTO mydomain VALUES ('mydomain.com', 259200, 'MX', '10 mail.mydomain.com.');
INSERT INTO mydomain VALUES ('w0.mydomain.com', 259200, 'A', '192.168.1.1');
INSERT INTO mydomain VALUES ('w1.mydomain.com', 259200, 'A', '192.168.1.2');
INSERT INTO mydomain VALUES ('mydomain.com', 259200, 'Cname', 'w0.mydomain.com.');
INSERT INTO mydomain VALUES ('mail.mydomain.com', 259200, 'Cname', 'w0.mydomain.com.');
INSERT INTO mydomain VALUES ('ns0.mydomain.com', 259200, 'Cname', 'w0.mydomain.com.');
INSERT INTO mydomain VALUES ('ns1.mydomain.com', 259200, 'Cname', 'w1.mydomain.com.');
INSERT INTO mydomain VALUES ('www.mydomain.com', 259200, 'Cname', 'w0.mydomain.com.');
INSERT INTO mydomain VALUES ('ftp.mydomain.com', 259200, 'Cname', 'w0.mydomain.com.');

        3、配置bind,其中dbname是数据库名,tablename是表名,hostname是mysql主机,然后就是用户名和密码

 

zone "mydomain.com" {
  type master;
  notify no;
  database "mysqldb dbname tablename hostname user password";
};

        4、重新启动bind,运行正常

四、用数据库管理bind,有一个很大的优点就是主域名CNAME功能,也就是空主机头别名问题。数据库的管理提供了一个松散的语法检查格式,我们配置了什么,就能解析出什么,一方面容易出错,另外一方面也带来了灵活性

发表在 article | 标签为 , , | 使用Mysql-bind实现mysql管理bind配置已关闭评论

lighttpd 安装

编译安装
      ./configure --prefix=/usr/local/lighttpd
      make
      make install
    2,编译后配置
      cp doc/sysconfig.lighttpd /etc/sysconfig/lighttpd
      mkdir /etc/lighttpd
      cp doc/lighttpd.conf /etc/lighttpd/lighttpd.conf
 
      如果你的Linux是RedHat/CentOS,那么:
      cp doc/rc.lighttpd.redhat /etc/init.d/lighttpd
      如果你的Linux是SuSE,那么:
      cp doc/rc.lighttpd /etc/init.d/lighttpd
      其他Linux发行版本可以自行参考该文件内容进行修改。
      然后修改/etc/init.d/lighttpd,把
      LIGHTTPD_BIN=/usr/sbin/lighttpd
      改为
      LIGHTTPD_BIN=/usr/local/lighttpd/sbin/lighttpd
 
      此脚本用来控制lighttpd的启动关闭和重起:
      /etc/init.d/lighttpd start
      /etc/init.d/lighttpd stop
      /etc/init.d/lighttpd restart
    3,配置
      修改/etc/lighttpd/lighttpd.conf
      1)server.modules
      取消需要用到模块的注释,mod_rewrite,mod_access,mod_fastcgi,mod_simple_vhost,mod_cgi,      mod_compress,mod_accesslog是一般需要用到的。
 
      2)server.document-root, server.error-log,accesslog.filename需要指定相应的目录
         server.document-root        = "/www/phc/html/"

 

 

-----------auto run---

chkconfig --add lighttpd

chkconfig --level 35 lighttpd on

 

-------------------------------------

lighttpd虚拟目录的配置

命令为alias.url,使用时只需要在lighttpd.conf的虚拟主机段加上

alias.url = ( "/img/" => "/path/to/img/" )

即可完成配置,启动时如果出现错误类似

unknown config-key: alias.url

则需要在lighttpd.conf的server.modules段设置加载mod_alias模块

server.modules = ("mod_rewrite", "mod_redirect")

加入

server.modules = ("mod_alias", "mod_rewrite", "mod_redirect")

--------------------------------------------------------

 

 

因為 lighttpd
已經用的蠻久了,所以都會有一份制式的 lighttpd.conf (精簡到「會動」而已) 拿來用,今天拿這個版本丟檔案的時候想用 Squid
當 reverse proxy 放在前面,結果發現永遠都是 TCP_MISS,看 HTTP Header 後發現 lighttpd 沒送 Last-Modified 欄位,應該是這樣造成 Squid 不會存下來。

lighttpd 不送 Last-Modified 的原因後來查出是因為沒有指定 MIME Type。這是一個 feature,而不是 bug (所以不會修正),所以我除了把線上得版本加上以外,在公版的 lighttpd.conf 裡也把 mimetype.assign 加上,這樣就正常了

-------------------------------------------------------------------------------------------

优化配置

server.chroot
使用chroot提高安全性时,web服务器的root目录。建议使用。

server.username = "..." server.groupname = "..."
放弃root权限。

dir-listing.activate
如果没有找到index文件就列出目录。建议disable。

server.event-handler
设置时间处理方式。Default: "poll"。Bsd上默认就可以,使用kqueue反而影响了效率。原因不明。以下是各种操作系统对应的方式:
OS Method Config-Value
all select select
Unix poll poll
Linux 2.4+ rt-signals linux-rtsig
Linux 2.6+ epoll linux-sysepoll
Solaris /dev/poll solaris-devpoll
FreeBSD, ... kqueue freebsd-kqueue
server.max-request-size
maximum size in kbytes of the request (header + body)
Default:

server.max-worker
lighttpd默认只启动一个进程工作,但也支持apache那样启动多个进程,我的实验显示启动多个进程同时工作时并不能提高性能。

server.max-keep-alive-requests
这一条比较关键,对性能的影响比较大。在一个keep-alive会话终止连接前能接受处理的最大请求数。Default: 128,对一个高负载的应用来说是不够的。我用了4000。

server.max-keep-alive-idle
一个空闲keep-alive连接被丢弃前,存在的的最大秒数。Default: 30。

server.error-handler-404
页面找不到时候的处理,对性能没什么影响,指出来一下,例如:
server.error-handler-404 = "/error-404.php"

server.max-fds
因为lighttpd是一个单线程(single-threaded)服务器,它的主要资源限制是文件描述符数目,默认值是1024。如果在一个高负载的站点上,可能你需要通过下面的设定增加这个限定值
server.max-fds = 2048 但这个限定只有在lighttpd做为root身份运行时才能生效。

connection.kbytes-per-second,server.kbytes-per-second
还有值得一提的时lighttpd可以限制每个连接或则特定虚拟机的流量。

compress.cache-dir,compress.filetype
如果文本稍微大点可以考虑使用压缩算法,减少带宽同时也能提高效率。例如:
compress.cache-dir = "/var/www/cache/"
compress.filetype = ("text/plain", "text/html")

server.stat-cache-engine = "fam"
这一条能明显提升性能,stat() cache。一个stat调用代价可能是昂贵的。为它设一个cache能省时间又避免上下文切换。替代每次都stat()来确定文件的存在,它只stat()一次,然后会监视目录,如果目录不变,他里面的文件也就没有变化。我们的内存文件系统中有没必要保留,依情况而定。
server.stat-cache-engine = "fam"   # either fam, simple or disabled

//使用sendfile发送文件

server.network-backend = "linux-sendfile"

--------------------------------------------------------------------------------------------------

Lighttpd与PHP

Lighttpd和PHP的搭配现在越来越常见了。但是老实说,如非必要,我还是推荐你使用Apache和PHP的搭配方式,毕竟LAMP构架的成熟度和稳定度都是经过时间考验的。

那么什么时候Lighttpd和PHP的搭配更值得选择呢?可以从以下几点考虑:如果访问量比较大,硬件资源吃紧,那么Lighttpd适合你;如果和稳定相比,你倾向速度多一些,那么Lighttpd适合你。

题外话:NginX
大有赶超Lighttpd
的态势。

Lighttpd的安装,本文就不多说了,大家自己搜索一下就能找到大把大把的教程。这里我们着重讨论一下Lighttpd的配置。

安装好Lighttpd+PHP后,你的配置很可能是类似下面的代码:

fastcgi.server = ( ".php" =>
 



 



 



(( "socket" => "/tmp/php-fastcgi.socket",
 



 



 



 



 



 



 



"bin-path" => "/usr/bin/php-cgi",
 



 



 



 



 



 



 



"max-procs" => 10,
 



 



 



 



 



 



 



"bin-environment" => (
 



 



 



 



 



 



 



 



 



 



 



"PHP_FCGI_CHILDREN" => "16",
 



 



 



 



 



 



 



 



 



 



 



"PHP_FCGI_MAX_REQUESTS" => "1000"
 



 



 



 



 



 



 



),
 



 



 



 



 



 



 



"broken-scriptfilename" => "enable"
 



 



 



))
)

其中,PHP_FCGI_MAX_REQUESTS的作用是在一个子进程工作一定次数后就干掉它,以免可能出现的问题连累系统,主进程会再创建一个相应的子进程来替补,保证子进程数一直是PHP_FCGI_CHILDREN个。

另外还有两个设置选项至关重要,分别是max-procs和PHP_FCGI_CHILDREN。如上所示的配置,系统将创建170个PHP-cgi的进程,它的计算公式如下:

num-procs = max-procs * ( 1 + PHP_FCGI_CHILDREN )

如果一个php-cgi进程占用十几兆内存的话,那么总计大约就要占用2G左右的内存。

我们先来看看max-procs的意思:从字面意思看,它似乎指得是最大进程数。实际它指的是Lighttpd一开始spawn多少个进程。

至于PHP_FCGI_CHILDREN的意思,和字面意思相同,指的就是每个主进程里产生多少个PHPFCGI子进程。

如果你的Lighttpd已经启动,你可以尝试执行一下命令:ps aux | grep php-cgi,将会看到大量的php-cgi进程:

nobody 10939 0.0 0.1 15556 4820 ? Ss 16:24 0:00 /usr/local/bin/php-cgi
nobody 11380 0.0 0.1 15452 5588 ? S 16:24 0:00 /usr/local/bin/php-cgi

仔细观察,你会发现这些php-cgi的状态不尽相同,有的是Ss,有的是S,通过man ps你能找到这些状态的含义:

S Interruptible sleep (waiting for an event to complete)
s is a session leader

也就是说,Ss状态的进程都是主进程(max-procs代表的那些进程),而S状态的进程都是子进程(PHP_FCGI_CHILDREN代表的那些进程)。如果不相信,你可以使用命令核实一下数量:

ps aux | grep php-cgi | grep Ss | grep -v grep | wc -l

确认了这些,我们再仔细看ps aux | grep php-cgi的结果,你还会发现主进程的内存占用(4840)和子进程的内存占用(5588)是不同的。这是因为主进程不处理实际的PHP请求,它唯一的工作就是看管好自己手下的子进程。而实际的PHP请求都是由子进程来完成的,所以子进程占用的内存要稍大一些。

如此,我们对max-procs和PHP_FCGI_CHILDREN的含义应该理解了吧,别急,还有一个问题:既然php-cgi的总进程数可以由上面的公式算出来,那么以下几个配置选项哪个好?

"max-procs" => 1,
"PHP_FCGI_CHILDREN" => "169",

"max-procs" => 2,
"PHP_FCGI_CHILDREN" => "84",

"max-procs" => 10,
"PHP_FCGI_CHILDREN" => "16",

以上三种配置产生的总进程数一样(都是170),我们如何判断配置的好坏呢?

如果使用了eAccelerator之类的PHP优化器,那么eAccelerator会为每一个主进程创建一个独立的缓存空间,这个时候如果你的max-procs是2的话,就会建立两个独立的缓存空间。一方面这浪费了一些内存,另一方面如果你的一个主进程挂了(它下面的子进程就失控了),至少你还有一个主进程可以保持正常运转。

总体来说,max-procs不宜为较小,否则没有容错性,在有PHP优化器的时候也不宜过大,否则会浪费很多内存做缓存空间,即便没有装PHP优化器,max-procs也不宜过大,因为主进程是不处理PHP请求的,过多的主进程自然就是一种浪费。确定了max-procs的值,剩下PHP_FCGI_CHILDREN的值就好说了。

另外:通过命令netstat -anp | grep php-cgi | wc -l可以得知当前有多少php-cgi处于连接状态,如果接近php-cgi的总进程数,就说明应该加大进程数了。
--------------------------------------------------------------------------------------------------------------------------------

lighttpd(lighty) 性能优化

对服务器而言最重要的就是优化了.
apache的优化文章,相信你也见过不少了.
这里稍微摘出lighttpd的几个优化参数看一看.

本文主要为跑php(fastcgi)的lighttpd设置.
如果需要跑静态页面,可以忽略本文 keep-alive 部分(并调大常连接数)

1 最大连接数

默认是1024
修改 server.max-fds,大流量网站推荐2048.

因为lighttpd基于线程,而apache(MPM-prefork)基于子进程,
所以apache需要设置startservers,maxclients等,这里不需要
 

2 stat() 缓存

stat() 这样的系统调用,开销也是相当明显的.
缓存能够节约时间和环境切换次数(context switches)

一句话,lighttpd.conf加上
server.stat-cache-engine = “fam”

lighttpd还另外提供simple(缓存1秒内的stat()),disabled选项.
相信没人会选disabled吧.

3 常连接(HTTP Keep-Alive)

一般来说,一个系统能够打开的文件个数是有限制的(文件描述符限制)
常连接占用文件描述符,对非并发的访问没有什么意义.

(文件描述符的数量和许多原因有关,比如日志文件数量,并发数目等)

这是lighttpd在keep-alive方面的默认值.
server.max-keep-alive-requests = 128
server.max-keep-alive-idle = 30

换言之,lighttpd最多可以同时承受30秒长的常连接,每个连接最多请求128个文件.
但这个默认值确实不适合非并发这种多数情况.

lighttpd.conf 中减小
server.max-keep-alive-requests
server.max-keep-alive-idle
两个值,可以减缓这种现象.

甚至可以关闭lighttpd keep-alive.
server.max-keep-alive-requests = 0

4 事件处理

对于linux kernel 2.6来说,没有别的可说
lighttpd.conf中加上这一句足矣
server.event-handler = “linux-sysepoll”

另外,
linux 2.4 使用 linux-rtsig
solaris: solaris-devpoll
freebsd 使用 freebsd-kqueue
unix 使用 poll

5 网络处理

lighttpd 大量使用了 sendfile() 这样一个高效的系统调用.
减少了从应用程序到网卡间的距离.
(同时也减少了lighttpd对cpu的占用,这部分占用转嫁到内核身上了)

根据平台,可以设置不同的参数.
(linux) server.network-backend = “linux-sendfile”
solaris: solaris-sendfilev
freebsd: freebsd-sendfile
unix: writev

如果有兴趣的话,也可以看看lighttpd在async io(aio)上的实现,仅限 lighttpd 1.5
(linux-aio-sendfile, posix-aio, gthread-aio)

此外,网络方面,核心的参数也需要适当进行修改,
这里就不需要详细说明了.

6 本文涉及 lighttpd.conf 参数总结

以下适合linux 2.6,php-fastcgi

var.author="fcicq"
server.stat-cache-engine = "fam"
server.network-backend = "linux-sendfile"
server.event-handler = "linux-sysepoll"
server.max-keep-alive-requests = 0
 

ps:
注意到不对劲了没有?

------------------------------------------------------------------------

Lighttpd(4) 功能特性
  # 配置超期
  expire.url = ( "/www/" => "access 2 hours")
  expire.url = ( "/www/mp3/" => "access 2 hours")
  
  #
  
  
  # 压缩
   compress.cache-dir = "/var/www/cache/"
  
   # 或者针对虚拟站点指定临时目录
   $HTTP["host"] == "docs.example.org" {
   compress.cache-dir = "/var/www/cache/docs.example.org/"
   }
  
   压缩文件类型
   compress.filetype = ("text/plain", "text/html")
  
  
  # 重定向
  
   # 重定向到指定网址
   url.redirect = ("^/" => "http://www.tianya.cn/index.asp")
  
   # 变量传递
   url.redirect = ("^/([0-9]+)$" => "http://cache.tianya.cn/publicforum/Content/house/1/$1.shtml")
   url.redirect = ( "^/show/([0-9]+)/([0-9]+)$" => "http://www.example.org/show.php?isdn=$1&page$2")
  
   # 面向虚拟主机的重定向
   $HTTP["host"] =~ "^www\.(.*)" {
   url.redirect = ( "^/(.*)" => "http://%1/$1" )
   }
  
  # 重写
  
  
  # 代理
   使用proxy-module模块。
  
   # 两个选项:
   1)proxy.debug
   2)proxy.balance:hash(同一请求发送到同一主机)、round-robin(循环)、fair(缺省)
  
   # 范例,
   $HTTP["host"] == "www.example.org" {
   proxy.balance = "hash"
   proxy.server = ( "" => ( ( "host" => "10.0.0.10" ),
   ( "host" => "10.0.0.11" ),
   ( "host" => "10.0.0.12" ),
   ( "host" => "10.0.0.13" ),
   ( "host" => "10.0.0.14" ),
   ( "host" => "10.0.0.15" ),
   ( "host" => "10.0.0.16" ),
   ( "host" => "10.0.0.17" ) ) )
   }
  
   当一主机down机时,该机的请求被平等移动到其它服务器。使用Microsoft CARP算法。
  
  
  # 流量修整
   1)每个连接每秒流量限制(k)
   connection.kbytes-per-second = 0
  
   2)服务每秒流量限制
   server.kbytes-per-second
   # 在虚拟主机中限制
   $HTTP["host"] == "www.example.org" {
   server.kbytes-per-second = 128
   }
  
  
  # 目录列表
   # 激活
   dir-listing.activate = "enable"
  
   # 控制在物理目录中
   $HTTP["url"] =~ "^/download($|/)" {
   dir-listing.activate = "enable"
   }
  
   dir-listing.hide-dotfiles = "enable" # 不显示隐藏文件
   dir-listing.external-css = "" # 目录css风格显示的css文件路径
   dir-listing.exclude = "" # 正则表达式,排队不显示的文件
   dir-listing.encoding = "utf-8"
  
  # 禁止googelbot机器人访问
  $HTTP["useragent"] =~ "Google" {
   url.access-deny = ( "" )
  }
  
  
  # 禁止所有图像盗链 (anti-hotlinking for images)
  $HTTP["referer"] !~ "^($|http://www\.example\.org)" {
   url.access-deny = ( ".jpg", ".jpeg", ".png" )
  }
  
  # 禁止非10.0.0.0/8的IP访问www.example.org
  $HTTP["host"] == "www.example.org" {
   $HTTP["remoteip"] != "10.0.0.0/8" {
   url.access-deny = ( "" )
   }
  }
  
  # 允许200.19.1.5和210.45.2.7访问www.example.org/admin/
  $HTTP["host"] == "www.example.org" {
   #!~ is a perl style regular expression not match
   $HTTP["remoteip"] !~ "200.19.1.5|210.45.2.7" {
   $HTTP["url"] =~ "^/admin/" {
   url.access-deny = ( "" )
   }
   }
  }
  
  # 配置虚拟主机
  
  启动模块mod_simple_vhost
  
  $HTTP["host"] == "cache.tianya.cn" {
   server.document-root = "/www/"
   index-file.names = ( "index.shtml", "index.html",
   "index.htm", "default.htm" )
  }
  
  $HTTP["host"] == "sample.tianya.cn" {
   server.document-root = "/www/sample/"
   index-file.names = ( "index.shtml", "index.html",
   "index.htm", "default.htm" )
  }

发表在 article | 标签为 | lighttpd 安装已关闭评论

Mysql日期和时间函数

对于每个类型拥有的值范围以及并且指定日期何时间值的有效格式的描述见7.3.6 日期和时间类型。 

这里是一个使用日期函数的例子。下面的查询选择了所有记录,其date_col的值是在最后30天以内: 

mysql> SELECT something FROM table 
WHERE TO_DAYS(NOW()) - TO_DAYS(date_col) <= 30; 

DAYOFWEEK(date) 
返回日期date的星期索引(1=星期天,2=星期一, ……7=星期六)。这些索引值对应于ODBC标准。 
mysql> select DAYOFWEEK('1998-02-03'); 
-> 3 

WEEKDAY(date) 
返回date的星期索引(0=星期一,1=星期二, ……6= 星期天)。 
mysql> select WEEKDAY('1997-10-04 22:23:00'); 
-> 5 
mysql> select WEEKDAY('1997-11-05'); 
-> 2 

DAYOFMONTH(date) 
返回date的月份中日期,在1到31范围内。 
mysql> select DAYOFMONTH('1998-02-03'); 
-> 3 

DAYOFYEAR(date) 
返回date在一年中的日数, 在1到366范围内。 
mysql> select DAYOFYEAR('1998-02-03'); 
-> 34 

MONTH(date) 
返回date的月份,范围1到12。 
mysql> select MONTH('1998-02-03'); 
-> 2 

DAYNAME(date) 
返回date的星期名字。 
mysql> select DAYNAME("1998-02-05"); 
-> 'Thursday' 

MONTHNAME(date) 
返回date的月份名字。 
mysql> select MONTHNAME("1998-02-05"); 
-> 'February' 

QUARTER(date) 
返回date一年中的季度,范围1到4。 
mysql> select QUARTER('98-04-01'); 
-> 2 

WEEK(date) 
  
WEEK(date,first) 
对于星期天是一周的第一天的地方,有一个单个参数,返回date的周数,范围在0到52。2个参数形式WEEK()允许
你指定星期是否开始于星期天或星期一。如果第二个参数是0,星期从星期天开始,如果第二个参数是1,
从星期一开始。 
mysql> select WEEK('1998-02-20'); 
-> 7 
mysql> select WEEK('1998-02-20',0); 
-> 7 
mysql> select WEEK('1998-02-20',1); 
-> 8 

YEAR(date) 
返回date的年份,范围在1000到9999。 
mysql> select YEAR('98-02-03'); 
-> 1998 

HOUR(time) 
返回time的小时,范围是0到23。 
mysql> select HOUR('10:05:03'); 
-> 10 

MINUTE(time) 
返回time的分钟,范围是0到59。 
mysql> select MINUTE('98-02-03 10:05:03'); 
-> 5 

SECOND(time) 
回来time的秒数,范围是0到59。 
mysql> select SECOND('10:05:03'); 
-> 3 

PERIOD_ADD(P,N) 
增加N个月到阶段P(以格式YYMM或YYYYMM)。以格式YYYYMM返回值。注意阶段参数P不是日期值。 
mysql> select PERIOD_ADD(9801,2); 
-> 199803 

PERIOD_DIFF(P1,P2) 
返回在时期P1和P2之间月数,P1和P2应该以格式YYMM或YYYYMM。注意,时期参数P1和P2不是日期值。 
mysql> select PERIOD_DIFF(9802,199703); 
-> 11 

DATE_ADD(date,INTERVAL expr type) 
  
DATE_SUB(date,INTERVAL expr type) 
  
ADDDATE(date,INTERVAL expr type) 
  
SUBDATE(date,INTERVAL expr type) 
这些功能执行日期运算。对于MySQL 3.22,他们是新的。ADDDATE()和SUBDATE()是DATE_ADD()和DATE_SUB()的同义词。
在MySQL 3.23中,你可以使用+和-而不是DATE_ADD()和DATE_SUB()。(见例子)date是一个指定开始日期的
DATETIME或DATE值,expr是指定加到开始日期或从开始日期减去的间隔值一个表达式,expr是一个字符串;它可以以
一个“-”开始表示负间隔。type是一个关键词,指明表达式应该如何被解释。EXTRACT(type FROM date)函数从日期
中返回“type”间隔。下表显示了type和expr参数怎样被关联: type值 含义 期望的expr格式 
SECOND 秒 SECONDS 
MINUTE 分钟 MINUTES 
HOUR 时间 HOURS 
DAY 天 DAYS 
MONTH 月 MONTHS 
YEAR 年 YEARS 
MINUTE_SECOND 分钟和秒 "MINUTES:SECONDS" 
HOUR_MINUTE 小时和分钟 "HOURS:MINUTES" 
DAY_HOUR 天和小时 "DAYS HOURS" 
YEAR_MONTH 年和月 "YEARS-MONTHS" 
HOUR_SECOND 小时, 分钟, "HOURS:MINUTES:SECONDS" 
DAY_MINUTE 天, 小时, 分钟 "DAYS HOURS:MINUTES" 
DAY_SECOND 天, 小时, 分钟, 秒 "DAYS HOURS:MINUTES:SECONDS" 

MySQL在expr格式中允许任何标点分隔符。表示显示的是建议的分隔符。如果date参数是一个DATE值并且你的计算仅仅
包含YEAR、MONTH和DAY部分(即,没有时间部分),结果是一个DATE值。否则结果是一个DATETIME值。 

mysql> SELECT "1997-12-31 23:59:59" + INTERVAL 1 SECOND; 
-> 1998-01-01 00:00:00 
mysql> SELECT INTERVAL 1 DAY + "1997-12-31"; 
-> 1998-01-01 
mysql> SELECT "1998-01-01" - INTERVAL 1 SECOND; 
-> 1997-12-31 23:59:59 
mysql> SELECT DATE_ADD("1997-12-31 23:59:59", 
INTERVAL 1 SECOND); 
-> 1998-01-01 00:00:00 
mysql> SELECT DATE_ADD("1997-12-31 23:59:59", 
INTERVAL 1 DAY); 
-> 1998-01-01 23:59:59 
mysql> SELECT DATE_ADD("1997-12-31 23:59:59", 
INTERVAL "1:1" MINUTE_SECOND); 
-> 1998-01-01 00:01:00 
mysql> SELECT DATE_SUB("1998-01-01 00:00:00", 
INTERVAL "1 1:1:1" DAY_SECOND); 
-> 1997-12-30 22:58:59 
mysql> SELECT DATE_ADD("1998-01-01 00:00:00", 
INTERVAL "-1 10" DAY_HOUR); 
-> 1997-12-30 14:00:00 
mysql> SELECT DATE_SUB("1998-01-02", INTERVAL 31 DAY); 
-> 1997-12-02 
mysql> SELECT EXTRACT(YEAR FROM "1999-07-02"); 
-> 1999 
mysql> SELECT EXTRACT(YEAR_MONTH FROM "1999-07-02 01:02:03"); 
-> 199907 
mysql> SELECT EXTRACT(DAY_MINUTE FROM "1999-07-02 01:02:03"); 
-> 20102 

如果你指定太短的间隔值(不包括type关键词期望的间隔部分),MySQL假设你省掉了间隔值的最左面部分。例如,
如果你指定一个type是DAY_SECOND,值expr被希望有天、小时、分钟和秒部分。如果你象"1:10"这样指定值,
MySQL假设日子和小时部分是丢失的并且值代表分钟和秒。换句话说,"1:10" DAY_SECOND以它等价于"1:10" MINUTE_SECOND
的方式解释,这对那MySQL解释TIME值表示经过的时间而非作为一天的时间的方式有二义性。如果你使用确实不正确的日期,
结果是NULL。如果你增加MONTH、YEAR_MONTH或YEAR并且结果日期大于新月份的最大值天数,日子在新月用最大的天调整。 

mysql> select DATE_ADD('1998-01-30', Interval 1 month); 
-> 1998-02-28 

注意,从前面的例子中词INTERVAL和type关键词不是区分大小写的。 
TO_DAYS(date) 
给出一个日期date,返回一个天数(从0年的天数)。 
mysql> select TO_DAYS(950501); 
-> 728779 
mysql> select TO_DAYS('1997-10-07'); 
-> 729669 

TO_DAYS()不打算用于使用格列高里历(1582)出现前的值。 

FROM_DAYS(N) 
给出一个天数N,返回一个DATE值。 
mysql> select FROM_DAYS(729669); 
-> '1997-10-07' 

TO_DAYS()不打算用于使用格列高里历(1582)出现前的值。 

DATE_FORMAT(date,format) 
根据format字符串格式化date值。下列修饰符可以被用在format字符串中: %M 月名字(January……December) 
%W 星期名字(Sunday……Saturday) 
%D 有英语前缀的月份的日期(1st, 2nd, 3rd, 等等。) 
%Y 年, 数字, 4 位 
%y 年, 数字, 2 位 
%a 缩写的星期名字(Sun……Sat) 
%d 月份中的天数, 数字(00……31) 
%e 月份中的天数, 数字(0……31) 
%m 月, 数字(01……12) 
%c 月, 数字(1……12) 
%b 缩写的月份名字(Jan……Dec) 
%j 一年中的天数(001……366) 
%H 小时(00……23) 
%k 小时(0……23) 
%h 小时(01……12) 
%I 小时(01……12) 
%l 小时(1……12) 
%i 分钟, 数字(00……59) 
%r 时间,12 小时(hh:mm:ss [AP]M) 
%T 时间,24 小时(hh:mm:ss) 
%S 秒(00……59) 
%s 秒(00……59) 
%p AM或PM 
%w 一个星期中的天数(0=Sunday ……6=Saturday ) 
%U 星期(0……52), 这里星期天是星期的第一天 
%u 星期(0……52), 这里星期一是星期的第一天 
%% 一个文字“%”。 

所有的其他字符不做解释被复制到结果中。 

mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y'); 
-> 'Saturday October 1997' 
mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%H:%i:%s'); 
-> '22:23:00' 
mysql> select DATE_FORMAT('1997-10-04 22:23:00', 
'%D %y %a %d %m %b %j'); 
-> '4th 97 Sat 04 10 Oct 277' 
mysql> select DATE_FORMAT('1997-10-04 22:23:00', 
'%H %k %I %r %T %S %w'); 
-> '22 22 10 10:23:00 PM 22:23:00 00 6' 
MySQL3.23中,在格式修饰符字符前需要%。在MySQL更早的版本中,%是可选的。 

TIME_FORMAT(time,format) 
这象上面的DATE_FORMAT()函数一样使用,但是format字符串只能包含处理小时、分钟和秒的那些格式修饰符。
其他修饰符产生一个NULL值或0。 
CURDATE() 
  
CURRENT_DATE 
以'YYYY-MM-DD'或YYYYMMDD格式返回今天日期值,取决于函数是在一个字符串还是数字上下文被使用。 
mysql> select CURDATE(); 
-> '1997-12-15' 
mysql> select CURDATE() + 0; 
-> 19971215 

CURTIME() 
  
CURRENT_TIME 
以'HH:MM:SS'或HHMMSS格式返回当前时间值,取决于函数是在一个字符串还是在数字的上下文被使用。 
mysql> select CURTIME(); 
-> '23:50:26' 
mysql> select CURTIME() + 0; 
-> 235026 

NOW() 
  
SYSDATE() 
  
CURRENT_TIMESTAMP 
以'YYYY-MM-DD HH:MM:SS'或YYYYMMDDHHMMSS格式返回当前的日期和时间,取决于函数是在一个字符串还是在数字的
上下文被使用。 
mysql> select NOW(); 
-> '1997-12-15 23:50:26' 
mysql> select NOW() + 0; 
-> 19971215235026 

UNIX_TIMESTAMP() 
  
UNIX_TIMESTAMP(date) 
如果没有参数调用,返回一个Unix时间戳记(从'1970-01-01 00:00:00'GMT开始的秒数)。如果UNIX_TIMESTAMP()用一
个date参数被调用,它返回从'1970-01-01 00:00:00' GMT开始的秒数值。date可以是一个DATE字符串、一个DATETIME
字符串、一个TIMESTAMP或以YYMMDD或YYYYMMDD格式的本地时间的一个数字。 
mysql> select UNIX_TIMESTAMP(); 
-> 882226357 
mysql> select UNIX_TIMESTAMP('1997-10-04 22:23:00'); 
-> 875996580 

当UNIX_TIMESTAMP被用于一个TIMESTAMP列,函数将直接接受值,没有隐含的“string-to-unix-timestamp”变换。 

FROM_UNIXTIME(unix_timestamp) 
以'YYYY-MM-DD HH:MM:SS'或YYYYMMDDHHMMSS格式返回unix_timestamp参数所表示的值,取决于函数是在一个字符串
还是或数字上下文中被使用。 
mysql> select FROM_UNIXTIME(875996580); 
-> '1997-10-04 22:23:00' 
mysql> select FROM_UNIXTIME(875996580) + 0; 
-> 19971004222300 

FROM_UNIXTIME(unix_timestamp,format) 
返回表示 Unix 时间标记的一个字符串,根据format字符串格式化。format可以包含与DATE_FORMAT()函数列出的条
目同样的修饰符。 
mysql> select FROM_UNIXTIME(UNIX_TIMESTAMP(), 
'%Y %D %M %h:%i:%s %x'); 
-> '1997 23rd December 03:43:30 x' 

SEC_TO_TIME(seconds) 
返回seconds参数,变换成小时、分钟和秒,值以'HH:MM:SS'或HHMMSS格式化,取决于函数是在一个字符串还是在数字
上下文中被使用。 
mysql> select SEC_TO_TIME(2378); 
-> '00:39:38' 
mysql> select SEC_TO_TIME(2378) + 0; 
-> 3938 

TIME_TO_SEC(time) 
返回time参数,转换成秒。 
mysql> select TIME_TO_SEC('22:23:00'); 
-> 80580 
mysql> select TIME_TO_SEC('00:39:38'); 
-> 2378
 

发表在 article | 标签为 , | 184条评论

Fedora Core 6 服务详解

认识服务(services)

请先阅读 Fedora 服务管理指南
。了解什么是服务/后台进程(services/daemons),什么是运行级别(runlevels)以及各种用于管理服务(sevices)的工具。

你可以在命令行下使用 chkonfig 或 ntsysv 命令来管理服务(services),或者使用具有图形用户界面的 system-config-services 命令。GNOME 用户:系统-》管理-》服务器设置-》Services。


单个服务介绍

现在我们介绍 Fedora Core 6 中所包含的各种服务(services)的功能,并提供使用建议。这不是一份详尽的清单。小心:不要关闭你不确定或不知道的服务(services)。

 

不要关闭以下服务(除非你有充足的理由):

acpid, haldaemon, messagebus, klogd, network, syslogd

请确定修改的是运行级别 3 和 5。

 


 

NetworkManager, NetworkManagerDispatcher

NetworkManager 是一个自动切换网络连接的后台进程。很多笔记本用户都需要启用该功能,它让你能够在无线网络和有线网络之间切换。大多数台式机用户应该关闭该服务。一些 DHCP 用户可能需要开启它。

acpid

ACPI(全称 Advanced Configuration and Power Interface)服务是电源管理接口。建议所有的笔记本用户开启它。一些服务器可能不需要 acpi。支持的通用操作有:“电源开关“,”电池监视“,”笔记本 Lid 开关“,“笔记本显示屏亮度“,“休眠”, “挂机”,等等。

anacron, atd, cron

这几个调度程序有很小的差别。 建议开启 cron,如果你的电脑将长时间运行,那就更应该开启它。对于服务器,应该更深入了解以确定应该开启哪个调度程序。大多数情况下,笔记本/台式机应该关闭 atd 和 anacron。注意:一些任务的执行需要 anacron,比如:清理 /tmp 或 /var。

apmd

一些笔记本和旧的硬件使用 apmd。如果你的电脑支持 acpi,就应该关闭 apmd。如果支持 acpi,那么 apmd 的工作将会由 acpi 来完成。

autofs

该服务在需要时自动挂载可移动存储器(比如 USB 硬盘)。如果你使用移动介质,建议启用这个服务。Autofs 与 Mount/Umount 的不同之处在于,它是一种看守程序。如果它检测到用户正试图访问一个尚未挂接的文件系统,它就会自动检测该文件系统,如果存在,那么 Autofs 会自动将其挂接。另一方面,如果它检测到某个已挂接的文件系统在一段时间内没有被使用,那么 Autofs 会自动将其卸载。因此一旦运行了 Autofs 后,用户就不再需要手动完成文件系统的挂接和卸载。

avahi-daemon, avahi-dnsconfd

Avahi 是 zeroconf 协议的实现。它可以在没有 DNS 服务的局域网里发现基于 zeroconf 协议的设备和服务。它跟 mDNS 一样。除非你有兼容的设备或使用 zeroconf 协议的服务,否则应该关闭它。我把它关闭。

bluetooth, hcid, hidd, sdpd, dund, pand

蓝牙(Bluetooth)是给无线便携设备使用的(非 wifi, 802.11)。很多笔记本提供蓝牙支持。有蓝牙鼠标,蓝牙耳机和支持蓝牙的手机。很多人都没有蓝牙设备或蓝牙相关的服务,所以应该关闭它。其他蓝牙相关的服务有:hcid 管理所有可见的蓝牙设备,hidd 对输入设备(键盘,鼠标)提供支持, dund 支持通过蓝牙拨号连接网络,pand 允许你通过蓝牙连接以太网。

capi

仅仅对使用 ISDN 设备的用户有用。大多数用户应该关闭它。

cpuspeed

该服务可以在运行时动态调节 CPU 的频率来节约能源(省电)。许多笔记本的 CPU 支持该特性,现在,越来越多的台式机也支持这个特性了。如果你的 CPU 是:Petium-M,Centrino,AMD PowerNow, Transmetta,Intel SpeedStep,Athlon-64,Athlon-X2,Intel Core 2 中的一款,就应该开启它。如果你想让你的 CPU 以固定频率运行的话就关闭它。

cron

参见 anacron。

cupsd, cups-config-daemon

打印机相关。如果你有能在 Fedora 中驱动的 CUPS 兼容的打印机,你应该开启它。

dc_client, dc_server

磁盘缓存(Distcache)用于分布式的会话缓存。主要用在 SSL/TLS 服务器。它可以被 Apache 使用。大多数的台式机应该关闭它。

dhcdbd

这是一个让 DBUS 系统控制 DHCP 的接口。可以保留默认的关闭状态。

diskdump, netdump

磁盘转储(Diskdump)用来帮助调试内核崩溃。内核崩溃后它将保存一个 “dump“ 文件以供分析之用。网络转储(Netdump)的功能跟 Diskdump 差不多,只不过它可以通过网络来存储。除非你在诊断内核相关的问题,它们应该被关闭。

dund

参见 bluetooth。

firstboot

该服务是 Fedora 安装过程特有的。它执行在安装之后的第一次启动时仅仅需要执行一次的特定任务。它可以被关闭。

gpm

终端鼠标指针支持(无图形界面)。如果你不使用文本终端(CTRL-ALT-F1, F2..),那就关闭它。不过,我在运行级别 3 开启它,在运行级别 5 关闭它。

hidd

参见 bluetooth。

hplip, hpiod, hpssd

HPLIP 服务在 Linux 系统上实现 HP 打印机支持,包括 Inkjet,DeskJet,OfficeJet,Photosmart,Business InkJet 和一部分 LaserJet 打印机。这是 HP 赞助的惠普 Linux 打印项目(HP Linux Printing Project)的产物。如果你有相兼容的打印机,那就启用它。

iptables

它是 Linux 标准的防火墙(软件防火墙)。如果你直接连接到互联网(如,cable,DSL,T1),建议开启它。如果你使用硬件防火墙(比如:D-Link,Netgear,Linksys 等等),可以关闭它。强烈建议开启它。

ip6tables

如果你不知道你是否在使用 IPv6,大部分情况下说明你没有使用。该服务是用于 IPv6 的软件防火墙。大多数用户都应该关闭它。阅读这里了解如何关闭 Fedora 的 IPv6 支持

irda, irattach

IrDA 提供红外线设备(笔记本,PDA's,手机,计算器等等)间的通讯支持。大多数用户应该关闭它。

irqbalance

在多处理器系统中,启用该服务可以提高系统性能。大多数人不使用多处理器系统,所以关闭它。但是我不知道它作用于多核 CPU's 或 超线程 CPU's 系统的效果。在单 CPU 系统中关闭它应该不会出现问题。

isdn

这是一种互联网的接入方式。除非你使用 ISDN 猫来上网,否则你应该关闭它。

kudzu

该服务进行硬件探测,并进行配置。如果更换硬件或需要探测硬件更动,开启它。但是绝大部分的台式机和服务器都可以关闭它,仅仅在需要时启动。

lm_sensors

该服务可以探测主板感应器件的值或者特定硬件的状态(一般用于笔记本电脑)。你可以通过它来查看电脑的实时状态,了解电脑的健康状况。它在 GKrellM
用户中比较流行。查看 lm_sensors
的主页获得更多信息。如果没有特殊理由,建议关闭它。

mctrans

如果你使用 SELinux 就开启它。默认情况下 Fedora Core 开启 SELinux。

mdmonitor

该服务用来监测 Software RAID 或 LVM 的信息。它不是一个关键性的服务,可以关闭它。

mdmpd

该服务用来监测 Multi-Path 设备(该类型的存储设备能被一种以上的控制器或方法访问)。它应该被关闭。

messagebus

这是 Linux 的 IPC(Interprocess Communication,进程间通讯)服务。确切地说,它与 DBUS 交互,是重要的系统服务。强烈建议开启它。

netdump

参见 diskdump。

netplugd

Netplugd 用于监测网络接口并在接口状态改变时执行指定命令。建议保留它的默认关闭状态。

netfs

该服务用于在系统启动时自动挂载网络中的共享文件空间,比如:NFS,Samba 等等。如果你连接到局域网中的其它服务器并进行文件共享,就开启它。大多数台式机和笔记本用户应该关闭它。

nfs, nfslock

这是用于 Unix/Linux/BSD 系列操作系统的标准文件共享方式。除非你需要以这种方式共享数据,否则关闭它。

ntpd

该服务通过互联网自动更新系统时间。如果你能永久保持互联网连接,建议开启它,但不是必须的。

pand

参见 bluetooth。

pcscd

该服务提供智能卡(和嵌入在信用卡,识别卡里的小芯片一样大小)和智能卡读卡器支持。如果你没有读卡器设备,就关闭它。

portmap

该服务是 NFS(文件共享)和 NIS(验证)的补充。除非你使用 NFS 或 NIS 服务,否则关闭它。

readahead_early, readahead_later

该服务通过预先加载特定的应用程序到内存中以提供性能。如果你想程序启动更快,就开启它。

restorecond

用于给 SELinux 监测和重新加载正确的文件上下文(file contexts)。它不是必须的,但如果你使用 SELinux 的话强烈建议开启它。

rpcgssd, rpcidmapd, rpcsvcgssd

用于 NFS v4。除非你需要或使用 NFS v4,否则关闭它。

sendmail

除非你管理一个邮件服务器或你想在局域网内传递或支持一个共享的 IMAP 或 POP3 服务。大多数人不需要一个邮件传输代理。如果你通过网页(hotmail/yahoo/gmail)或使用邮件收发程序(比如:Thunderbird,Kmail,Evolution 等等)收发邮件。你应该关闭它。

smartd

SMART Disk Monitoring 服务用于监测并预测磁盘失败或磁盘问题(前提:磁盘必须支持 SMART)。大多数的桌面用户不需要该服务,但建议开启它,特别是服务器。

smb

SAMBA 服务是在 Linux 和 Windows 之间共享文件必须的服务。如果有 Windows 用户需要访问 Linux 上的文件,就启用它。查看如何在 Fedora Core 6 下配置 Samba

sshd

SSH 允许其他用户登录到你的系统并执行程序,该用户可以和你同一网络,也可以是远程用户。开启它存在潜在的安全隐患。如果你不需要从其它机器或不需要从远程登录,就应该关闭它。

xinetd

(该服务默认可能不被安装)它是一个特殊的服务。它可以根据特定端口收到的请求启动多个服务。比如:典型的 telnet 程序连接到 23 号端口。如果有 telent 请求在 23 号端口被 xinetd 探测到,那 xinetd 将启动 telnetd 服务来响应该请求。为了使用方便,可以开启它。运行 chkconfig --list, 通过检查 xinetd 相关的输出可以知道有哪些服务被 xinetd 管理。

发表在 article | 标签为 | 35条评论

Win32 API与.NET Framework的对应表

Atom Functions

Win32 function Description .NET Framework API
AddAtom Adds a character string to the local atom table. System.String.Intern

Note   String is not exactly an atom.

FindAtom Searches the local atom table for the specified character string. System.String.IsInterned

Note   String is not exactly an atom.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Bitmap Functions

Win32 function Description .NET Framework API
AlphaBlend Displays a bitmap with transparent or semitransparent pixels. System.Drawing.Graphics.DrawImage
BitBlt Performs a bit-block transfer. System.Drawing.Graphics.DrawImage
CreateBitmap Creates a bitmap. System.Drawing.Bitmap constructor

Note   Creates a DIB, not a DDB.

GetBitmapDimensionEx Gets the dimensions of a bitmap. System.Drawing.Bitmap.Size
GetDIBColorTable Retrieves RGB color values from a DIB section bitmap. System.Drawing.Bitmap.Palette
GetDIBits Copies a bitmap into a buffer. System.Drawing.Bitmap.LockBits
GetPixel Gets the RGB color value of the pixel at a given coordinate. System.Drawing.Bitmap.GetPixel
GradientFill Fills rectangle and triangle structures. System.Drawing.Graphics.FillRectangle(Drawing2D.LinearGradiantBrush, Rectangle)
LoadBitmap Loads a bitmap from a module's executable file. System.Drawing.Bitmap.Bitmap(Type, String)
SetPixel Sets the color for a pixel. System.Drawing.Bitmap.SetPixel
SetPixelV Sets a pixel to the best approximation of a color. System.Drawing.Bitmap.SetPixel(…, Graphics.GetNearestColor(Color))
StretchBlt Copies a bitmap and stretches or compresses it. System.Drawing.Graphics.DrawImage

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Brush Functions

Win32 function Description .NET Framework API
CreateBrushIndirect Creates a brush with a specified style, color, and pattern. Any of the following:
System.Drawing.Brushes
System.Drawing.SolidBrush
System.Drawing.TextureBrush
System.Drawing.Drawing2D.HatchBrush
System.Drawing.Drawing2D.LinearGradientBrush
System.Drawing.Drawing2D.PathGradientBrush
CreateHatchBrush Creates a brush with a hatch pattern and color. System.Drawing.Drawing2D.HatchBrush constructor
CreatePatternBrush Creates a brush with a bitmap pattern. System.Drawing.TextureBrush constructor
CreateSolidBrush Creates a brush with a solid color. System.Drawing.SolidBrush constructor
GetSysColorBrush Gets a handle for a brush that corresponds to a color index. System.Drawing.Brushes class

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Button Functions

Win32 function Description .NET Framework API
CheckDlgButton Changes the check state of a button control. System.Windows.Forms.CheckBox.Checked
CheckRadioButton Adds a check mark to a specified radio button in a group and removes a check mark from all other radio buttons in the group. System.Windows.Forms.RadioButton.Checked
IsDlgButtonChecked Determines whether a button control has a check mark next to it or whether a three-state button control is grayed, checked, or neither. System.Windows.Forms.CheckBox.CheckState

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Clipboard Functions

Win32 function Description .NET Framework API
CountClipboardFormats Retrieves the number of different data formats currently on the clipboard. System.Windows.Forms.DataObject.GetFormats
EnumClipboardFormats Enumerates the data formats currently available on the clipboard. System.Windows.Forms.DataObject.GetFormats
GetClipboardData Retrieves data from the clipboard in a specified format. System.Windows.Forms.ClipBoard.GetDataObject
IsClipboardFormatAvailable Determines whether the clipboard contains data in the specified format. System.Windows.Forms.DataObject.GetDataPresent
RegisterClipboardFormat Registers a new clipboard format. System.Windows.Forms.DataFormats.GetFormat
SetClipboardData Places data on the clipboard in a specified clipboard format. System.Windows.Forms.ClipBoard.SetDataObject

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Clipping Functions

Win32 function Description .NET Framework API
ExcludeClipRect Creates a new clipping region that consists of the existing clipping region minus the specified rectangle. System.Drawing.Graphics.ExcludeClip
ExtSelectClipRgn Combines the specified region with the current clipping region using the specified mode. System.Drawing.Graphics.SetClip
GetClipBox Retrieves the dimensions of the tightest bounding rectangle that can be drawn around the current visible area on the device. System.Drawing.Graphics.VisibleClipBounds
GetClipRgn Retrieves a handle identifying the current application-defined clipping region for the specified device context. System.Drawing.Graphics.Clip
IntersectClipRect Creates a new clipping region from the intersection of the current clipping region and the specified rectangle. System.Drawing.Graphics.IntersectClip
OffsetClipRgn Moves the clipping region of a device context by the specified offsets. System.Drawing.Graphics.TranslateClip
PtVisible Determines whether the specified point is within the clipping region of a device context. System.Drawing.Graphics.IsVisible
RectVisible Determines whether any part of the specified rectangle lies within the clipping region of a device context. System.Drawing.Graphics.IsVisible
SelectClipPath Selects the current path as a clipping region for a device context, combining the new region with any existing clipping region by using the specified mode. System.Drawing.Graphics.SetClip
SelectClipRgn Selects a region as the current clipping region for the specified device context. System.Drawing.Graphics.Clip

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Color Functions

Win32 function Description .NET Framework API
CreateHalftonePalette Creates a halftone palette for the specified device context. System.Drawing.Graphics.GetHalftonePalette
CreatePalette Creates a logical palette. System.Drawing.Image.Palette
GetNearestColor Retrieves a color value identifying a color from the system palette that will be displayed when the specified color value is used. System.Drawing.Graphics.GetNearestColor
GetPaletteEntries Retrieves a specified range of palette entries from the given logical palette. System.Drawing.Image.Palette.Entries

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Combo Box Functions

Win32 function Description .NET Framework API
DlgDirListComboBox Replaces the contents of a combo box with the names of specified subdirectories and files. System.Windows.Forms.ComboBox.Items.AddRange(System.IO.Directory.GetFileSystemEntries)
DlgDirSelectComboBoxEx Retrieves the current selection from a combo box filled by using DlgDirListComboBox. System.Windows.Forms.ComboBox.SelectedItem
GetComboBoxInfo Retrieves information about a specified combo box. System.Windows.Forms.ComboBox properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Common Dialog Box Functions

Win32 function Description .NET Framework API
ChooseColor Creates a Color dialog box that enables the user to select a color. System.Windows.Forms.ColorDialog constructor

Note   Dialog cannot be modified through a hook.

ChooseFont Creates a Font dialog box that enables the user to choose attributes for a logical font. System.Windows.Forms.FontDialog constructor

Note   Dialog cannot be modified through a hook.

GetFileTitle Retrieves the name of the specified file. System.IO.FileInfo.Name

Note   Does not take user preferences into account.

GetOpenFileName Creates an Open dialog box that lets the user specify the drive, directory, and name of a file or set of files to open. System.Windows.Forms.OpenFileDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

GetSaveFileName Creates a Save dialog box that lets the user specify the drive, directory, and name of a file to save. System.Windows.Forms.SaveFileDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

PageSetupDlg Creates a Page Setup dialog box that enables the user to specify the attributes of a printed page. System.Windows.Forms.PageSetupDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

PrintDlg Displays a Print dialog box. System.Windows.Forms.PrintDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Console Functions

Win32 function Description .NET Framework API
GetStdHandle Retrieves a handle for the standard input, standard output, or standard error device. System.Console.OpenStandardIn
System.Console.OpenStandardOut
System.Console.OpenStandardError
ReadConsole Reads character input from the console input buffer and removes it from the buffer. System.Console.Read
SetStdHandle Sets the handle for the standard input, standard output, or standard error device. System.Console.SetIn
System.Console.SetOut
System.Console.SetError
WriteConsole Writes a character string to a console screen buffer beginning at the current cursor location. System.Console.Write

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Coordinate Functions

Win32 function Description .NET Framework API
ClientToScreen Converts the client-area coordinates of a specified point to screen coordinates. System.Windows.Forms.Form.PointToScreen
CombineTransform Concatenates two world-space to page-space transformations. System.Drawing.Drawing2D.Matrix.Multiply
DPtoLP Converts device coordinates into logical coordinates. System.Drawing.Graphics.TransformPoints
GetMapMode Retrieves the current mapping mode. System.Drawing.Graphics.PageUnit
GetWindowExtEx Retrieves the x-extent and y-extent of the window for the specified device context. System.Drawing.Graphics.PageScale
GetWindowOrgEx Retrieves the x-coordinates and y-coordinates of the window origin for the specified device context. System.Drawing.Graphics.Transform.OffsetX
System.Drawing.Graphics.Transform.OffsetY
GetWorldTransform Retrieves the current world-space to page-space transformation. System.Drawing.Graphics.Transform
LPtoDP Converts logical coordinates into device coordinates. System.Drawing.Graphics.TransformPoints
ModifyWorldTransform Changes the world transformation for a device context using the specified mode. System.Drawing.Graphics.Transform
OffsetViewportOrgEx Modifies the viewport origin for a device context using the specified horizontal and vertical offsets. System.Drawing.Graphics.TranslateTransform
OffsetWindowOrgEx Modifies the window origin for a device context using the specified horizontal and vertical offsets. System.Drawing.Graphics.TranslateTransform
ScreenToClient Converts the screen coordinates of a specified point on the screen-to-client coordinates. System.Windows.Forms.Form.PointToClient
SetMapMode Sets the mapping mode of the specified device context. System.Drawing.Graphics.PageUnit
SetWindowExtEx Sets the horizontal and vertical extents of the window for a device context by using the specified values. System.Drawing.Graphics.PageScale
Drawing.Graphics.ScaleTransform
SetWindowOrgEx Specifies which window point maps to the viewport origin (0,0). System.Drawing.Graphics.TranslateTransform
SetWorldTransform Sets a two-dimensional linear transformation between world space and page space for the specified device context. System.Drawing.Graphics.Transform

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Cursor Functions

Win32 function Description .NET Framework API
ClipCursor Confines the cursor to a rectangular area on the screen. System.Windows.Forms.Cursor.Clip
CopyCursor Copies the specified cursor. System.Windows.Forms.Cursor.CopyHandle
CreateCursor Creates a cursor having the specified size, bit patterns, and hot spot. System.Windows.Forms.Cursor constructor
System.Windows.Forms.Cursor.Size
System.Windows.Forms.Cursor.Position
DestroyCursor Destroys a cursor. System.Windows.Forms.Cursor.Dispose
GetClipCursor Retrieves the screen coordinates of the rectangular area to which the cursor is confined. System.Windows.Forms.Cursor.Clip
GetCursor Retrieves a handle to the current cursor. System.Windows.Forms.Cursor.Handle
GetCursorInfo Retrieves information about the global cursor. System.Windows.Forms.Cursor.Position
System.Windows.Forms.SystemInformation.CursorSize
GetCursorPos Retrieves the cursor's position. System.Windows.Forms.Control.MousePosition
System.Windows.Forms.Cursor.Position
LoadCursor Loads a cursor resource from an executable file. System.Windows.Forms.Cursor constructor
LoadCursorFromFile Creates a cursor based on data contained in a file. System.Windows.Forms.Cursor constructor
SetCursor Sets the cursor shape. System.Windows.Forms.Cursor.Current
SetCursorPos Moves the cursor to the specified screen coordinates. System.Windows.Forms.Cursor.Position
ShowCursor Displays or hides the cursor. System.Windows.Forms.Cursor.Show
Windows.Forms.Cursor.Hide

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Debugging Functions

Win32 function Description .NET Framework API
DebugActiveProcess Enables a debugger to attach to an active process and debug it. System.Diagnostics.Debugger.Launch
DebugBreak Causes a breakpoint exception to occur in the current process. System.Diagnostics.Debugger.Break
IsDebuggerPresent Determines whether the calling process is running under the context of a debugger. System.Diagnostics.Debugger.IsAttached
OutputDebugString Sends a string to the debugger for display. System.Diagnostics.Debugger.Log

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Device Context Functions

Win32 function Description .NET Framework API
ChangeDisplaySettings Changes the settings of the default display device to the specified graphics mode. System.Management.ManagementClass("Win32_VideoController")
ChangeDisplaySettingsEx Changes the settings of the specified display device to the specified graphics mode. System.Management.ManagementClass("Win32_VideoController")
DeviceCapabilities Retrieves the capabilities of a printer device driver. System.Drawing.Printing.PageSettings
System.Drawing.Printing.PrinterSettings
EnumDisplayDevices Retrieves information about the display devices in a system. System.Management.ManagementClass("Win32_DesktopMonitor")
EnumDisplaySettings Retrieves information about one of the graphics modes for a display device. System.Management.ManagementClass("CIM_VideoControllerResolution")
GetDC Retrieves a handle to a display device context for the client area of a specified window or for the entire screen. To retrieve a Graphics object, use any of the following:
System.Drawing.Graphics.FromHwnd(Windows.Forms.Control.Handle)
System.Drawing.Printing.PrintPageEventArgs.Graphics
System.Windows.Forms.PaintEventArgs.Graphics

To explicitly retrieve a handle, use the following:
System.Drawing.Graphics.GetHdc

GetDCEx Retrieves a handle to a display device context for the client area of a specified window or for the entire screen. To retrieve a Graphics object, use any of the following:
System.Drawing.Graphics.FromHwnd(Windows.Forms.Control.Handle)
System.Drawing.Printing.PrintPageEventArgs.Graphics
System.Windows.Forms.PaintEventArgs.Graphics

To explicitly retrieve a handle, use the following:
System.Drawing.Graphics.GetHdc

GetDeviceCaps Retrieves device-specific information for the specified device. System.Drawing.Graphics properties
System.Drawing.Printing.PrinterSettings
System.Management classes
GetLayout Retrieves the layout of a device context. System.Windows.Forms.Control.RightToLeft
GetObject Retrieves information for the specified graphics object. System.Drawing.Bitmap properties
System.Drawing.Brush properties
System.Drawing.Font properties
System.Drawing.Pen properties
GetObjectType Retrieves the type of the specified object. System.Object.GetType
GetStockObject Retrieves a handle to one of the stock pens, brushes, fonts, or palettes. System.Drawing.Brushes
System.Drawing.Pens
ReleaseDC Releases a device context, freeing it for use by other applications. System.Drawing.Graphics.ReleaseHdc
SetLayout Sets the layout for a device context. System.Windows.Forms.Control.RightToLeft = System.Windows.Forms.RightToLeft.Yes

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Dialog Box Functions

Win32 function Description .NET Framework API
CreateDialog Creates a modeless dialog box from a dialog box template resource. System.Windows.Forms.Form constructor
System.Windows.Forms.Form properties
CreateDialogIndirect Creates a modeless dialog box from a dialog box template in memory. System.Windows.Forms.Form constructor
System.Windows.Forms.Form properties
DefDlgProc Calls the default dialog box window procedure to provide default processing for any window messages that a dialog box with a private window class does not process. System.Windows.Forms.Form.DefWndProc
DialogBox Creates a modal dialog box from a dialog box template resource. System.Windows.Forms.Form constructor
System.Windows.Forms.Form.ShowDialog
DialogBoxIndirect Creates a modal dialog box from a dialog box template in memory. System.Windows.Forms.Form constructor
System.Windows.Forms.Form.ShowDialog
DialogProc An application-defined callback function used with the CreateDialog and DialogBox families of functions. System.Windows.Forms.Form.WndProc
EndDialog Destroys a modal dialog box. System.Windows.Forms.Form.Close
GetDlgCtrlID Retrieves the identifier of the specified control. System.Windows.Forms.Form.Controls.IndexOf
GetDlgItem Retrieves a handle to a control in the specified dialog box. System.Windows.Forms.Form.Controls.Item
GetDlgItemInt Translates the text of a specified control in a dialog box into an integer value. System.Int32.Parse(Form.Text)
System.UInt32.Parse(Form.Text)
GetDlgItemText Retrieves the title or text associated with a control in a dialog box. System.Windows.Forms.Form.Controls.Item[].Text
GetNextDlgGroupItem Retrieves a handle to the first control in a group of controls that precedes (or follows) the specified control. Iterate through the controls:
System.Windows.Forms.Form.Controls.Item

Remember to determine whether the control is active by referencing the Enabled and Visible properties of the control.

Note   The order that the controls are presented in might not be the same order in which GetNextDlgGroupItem presents the controls.

GetNextDlgTabItem Retrieves a handle to the first control that has the WS_TABSTOP style that precedes (or follows) the specified control. Iterate through the controls:
System.Windows.Forms.Form.Controls.Item

Remember to determine whether the control is active by referencing the Enabled, Visible, and TabStop properties of the control.

Note   The order that the controls are presented in might not be the same order in which GetNextDlgGroupItem presents the controls.

MessageBox Creates, displays, and operates a message box. System.Windows.Forms.MessageBox.Show
MessageBoxEx Creates, displays, and operates a message box. System.Windows.Forms.MessageBox.Show
MessageBoxIndirect Creates, displays, and operates a message box. System.Windows.Forms.MessageBox.Show
SendDlgItemMessage Sends a message to the specified control in a dialog box. System.Windows.Forms.Form.WndProc(System.Windows.Forms.Message)
SetDlgItemInt Sets the text of a control in a dialog box to the string representation of a specified integer value. System.Windows.Forms.Control.Text = System.Int32.ToString
SetDlgItemText Sets the title or text of a control in a dialog box. System.Windows.Forms.Control.Text

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Dynamic-Link Library Functions

Win32 function Description .NET Framework API
GetModuleFileName Retrieves the full path and file name for the file containing the specified module. System.Reflection.Module.FullyQualifiedName
GetModuleHandle Retrieves a module handle for the specified module. System.Runtime.InteropServices.Marshal.GetHINSTANCE
LoadLibrary Maps the specified executable module into the address space of the calling process. Any of the following:
System.Reflection.Assembly.Load
System.Reflection.Assembly.LoadFrom
System.Reflection.Assembly.LoadWithPartialName
LoadLibraryEx Maps the specified executable module into the address space of the calling process. Any of the following:
System.Reflection.Assembly.Load
System.Reflection.Assembly.LoadFrom
System.Reflection.Assembly.LoadWithPartialName

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Error Handling Functions

Win32 function Description .NET Framework API
FatalAppExit Displays a message box and terminates the application when the message box is closed. System.Windows.Forms.MessageBox.Show
System.Diagnostics.Process.Kill
GetLastError Retrieves the calling thread's last-error code value. System.Runtime.InteropServices.Marshall.GetLastWin32Error

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Event Logging Functions

Win32 function Description .NET Framework API
ClearEventLog Clears the specified event log, and optionally saves the current copy of the log file to a backup file. System.Diagnostics.EventLog.Clear
CloseEventLog Closes a read handle to the specified event log. System.Diagnostics.EventLog.Close
DeregisterEventSource Closes a write handle to the specified event log. System.Diagnostics.EventLog.DeleteEventSource
GetNumberOfEventLogRecords Retrieves the number of records in the specified event log. System.Diagnostics.EventLog.Entries.Count
GetOldestEventLogRecord Retrieves the absolute record number of the oldest record in the specified event log. System.Diagnostics.EventLogEntryCollection[0]
System.Diagnostics.EventLogEntry.TimeWritten
NotifyChangeEventLog Enables an application to receive notification when an event is written to the specified event log file. System.Diagnostics.EventLog.EnableRaisingEvents
OpenBackupEventLog Opens a handle to a backup event log. System.Diagnostics.EventLog constructor
OpenEventLog Opens a handle to an event log. System.Diagnostics.EventLog constructor
ReadEventLog Reads a whole number of entries from the specified event log. System.Diagnostics.EventLogEntryCollection.CopyTo
RegisterEventSource Retrieves a registered handle to an event log. System.Diagnostics.EventLog.CreateEventSource
ReportEvent Writes an entry at the end of the specified event log. System.Diagnostics.EventLog.WriteEntry

Alphabetical Win32 Category List
Hierarchical Win32 Category List

File I/O Functions

Win32 function Description .NET Framework API
CopyFile Copies an existing file to a new file. Either of the following:
System.IO.File.Copy
IO.FileInfo.CopyTo
CreateDirectory Creates a new directory. Any of the following:
System.IO.Directory.CreateDirectory
System.IO.Directory.CreateSubdirectory
System.IO.DirectoryInfo.Create
CreateFile Creates or opens a file object. System.IO.File class and System.IO.FileInfo class
DeleteFile Deletes an existing file. Any of the following:
System.IO.Directory.Delete
System.IO.DirectoryInfo.Delete
System.IO.File.Delete
System.IO.FileInfo.Delete
FileIOCompletionRoutine An application-defined callback function used with ReadFileEx and WriteFileEx. User defined.
FindClose Closes the specified search handle. See FindFirstFile and FindNextFile
FindCloseChangeNotification Stops change notification handle monitoring. System.IO.FileSystemWatcher.EnableRaisingEvents
FindFirstChangeNotification Creates a change notification handle. System.IO.FileSystemWatcher class
FindFirstFile Searches a directory for a file whose name matches the specified file name. Any of the following:
System.IO.Directory.Exists
System.IO.Directory.GetDirectories
System.IO.Directory.GetFileSystemEntries
System.IO.Directory.GetFiles
System.IO.DirectoryInfo.Exists
System.IO.DirectoryInfo.GetDirectories
System.IO.DirectoryInfo.GetFileSystemInfos
System.IO.DirectoryInfo.GetFiles
System.IO.File.Exists
System.IO.FileInfo.Exists
FindFirstFileEx Searches a directory for a file whose name and attributes match the specified file name. Same as FindFirstFile
FindNextChangeNotification Requests that the operating system signal a change notification handle the next time it detects an appropriate change. System.IO.FileSystemWatcher class
FindNextFile Continues a file search. Any of the following:
System.IO.Directory.GetDirectories
System.IO.Directory.GetFileSystemEntries
System.IO.Directory.GetFiles
System.IO.DirectoryInfo.GetDirectories
System.IO.DirectoryInfo.GetFileSystemInfos
System.IO.DirectoryInfo.GetFiles
FlushFileBuffers Clears the buffers for the specified file and causes all buffered data to be written to the file. System.IO.FileStream.Flush
GetBinaryType Determines whether a file is executable. System.IO.FileSystemInfo.Extension

Note   Only manipulates strings; does not do a file-system check.

GetCurrentDirectory Retrieves the current directory for the current process. System.IO.Directory.GetCurrentDirectory
GetDriveType Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive. System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"").Get
System.Management.ManagementObject.Properties
System.IO.DriveInfo.DriveType
GetFileAttributes Retrieves attributes for a specified file or directory. Any of the following:
System.IO.Directory.GetAttributes
System.IO.File.GetAttributes
System.IO.FileSystemInfo.Attributes
GetFileAttributesEx Retrieves attributes for a specified file or directory. Any of the following:
System.IO.Directory.GetAttributes
System.IO.File.GetAttributes
System.IO.FileSystemInfo.Attributes
GetFileInformationByHandle Retrieves file information for a specified file. System.IO.FileInfo properties
GetFileSize Retrieves the size of a specified file. Either of the following:
System.IO.FileInfo.Length
System.IO.FileStream.Length
GetFileSizeEx Retrieves the size of a specified file. Either of the following:
System.IO.FileInfo.Length
System.IO.FileStream.Length
GetFullPathName Retrieves the full path and file name of a specified file. Either of the following:
System.IO.FileSystemInfo.FullName
System.IO.Path.GetFullPath
GetTempFileName Creates a name for a temporary file. System.IO.Path.GetTempFileName
GetTempPath Retrieves the path of the directory designated for temporary files. System.IO.Path.GetTempPath
LockFile Locks a region in an open file. System.IO.FileStream.Lock
LockFileEx Locks a region in an open file for shared or exclusive access. System.IO.FileStream.Lock
MoveFile Moves an existing file or a directory. Any of the following:
System.IO.Directory.Move
System.IO.DirectoryInfo.MoveTo
System.IO.File.Move
System.IO.FileInfo.MoveTo
ReadDirectoryChangesW Retrieves information describing the changes occurring within a directory. System.IO.FileSystemWatcher class
ReadFile Reads data from a file, starting at the specified position. Any of the following:
System.IO.FileStream.BeginRead/EndRead
System.IO.FileStream.Read
System.IO.FileStream.ReadByte
ReadFileEx Reads data from a file asynchronously. System.IO.FileStream.BeginRead/EndRead
RemoveDirectory Deletes an existing empty directory. Either of the following:
System.IO.Directory.Delete
System.IO.DirectoryInfo.Delete
SearchPath Searches for the specified file. Any of the following:
System.IO.Directory.Exists
System.IO.Directory.GetDirectories
System.IO.Directory.GetFileSystemEntries
System.IO.Directory.GetFiles
System.IO.DirectoryInfo.Exists
System.IO.DirectoryInfo.GetDirectories
System.IO.DirectoryInfo.GetFileSystemInfos
System.IO.DirectoryInfo.GetFiles
System.IO.File.Exists
System.IO.FileInfo.Exists
SetCurrentDirectory Changes the current directory for the current process. System.IO.Directory.SetCurrentDirectory
SetEndOfFile Moves the end-of-file position for the specified file. System.IO.FileStream.SetLength
SetFileAttributes Sets the attributes for a file. System.IO.File.SetAttributes
SetFilePointer Moves the file pointer of an open file. Either of the following:
System.IO.FileStream.Position
System.IO.FileStream.Seek
SetFilePointerEx Moves the file pointer of an open file. Either of the following:
System.IO.FileStream.Position
System.IO.FileStream.Seek
UnlockFile Unlocks a previously locked region in an open file. System.IO.FileStream.Unlock
UnlockFileEx Unlocks a previously locked region in an open file. System.IO.FileStream.Unlock
WriteFile Writes data to a file. Any of the following:
System.IO.FileStream.BeginWrite and EndWrite
System.IO.FileStream.Write
System.IO.FileStream.WriteByte
System.IO.BinaryWriter.Write
WriteFileEx Writes data to a file asynchronously. System.IO.FileStream.BeginWrite and EndWrite

Alphabetical Win32 Category List
Hierarchical Win32 Category List

File System Functions

Used with file systems:

Win32 function Description .NET Framework API
GetDiskFreeSpace Retrieves information about the specified disk, including the amount of free space on the disk. System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"").Get
System.Management.ManagementObject.Properties
GetDiskFreeSpaceEx Retrieves information about the specified disk, including the amount of free space on the disk. System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"").Get
System.Management.ManagementObject.Properties
GetLogicalDriveStrings Fills a buffer with strings that specify valid drives in the system. Either of the following:
System.Environment.GetLogicalDrives
System.IO.Directory.GetLogicalDrives

Used with an encrypted file system:

Win32 function Description .NET Framework API
DecryptFile Decrypts an encrypted file or directory. System.Security.Cryptography.CryptoStream.Read
EncryptFile Encrypts a file or directory. System.Security.Cryptography.CryptoStream.Write
FileEncryptionStatus Retrieves the encryption status of the specified file. System.IO.FileSystemInfo.Attributes

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Filled Shape Functions

Win32 function Description .NET Framework API
Chord Draws an area bounded by an ellipse and a line segment. System.Drawing.Graphics.DrawArc
System.Drawing.Graphics.DrawLine
Ellipse Draws an ellipse. System.Drawing.Graphics.DrawEllipse
System.Drawing.Graphics.FillEllipse
FillRect Fills a rectangle using a brush. System.Drawing.Graphics.FillRectangle
InvertRect Inverts the color values of the pixels in a rectangle. System.Windows.Forms.ControlPaint.DrawReversibleFrame
System.Windows.Forms.ControlPaint.DrawReversibleLine
Pie Draws a pie-shaped wedge bounded by an ellipse and two radials. System.Drawing.Graphics.DrawPie
System.Drawing.Graphics.FillPie
Polygon Draws a polygon. System.Drawing.Graphics.DrawPolygon
System.Drawing.Graphics.FillPolygon
Rectangle Draws a rectangle. System.Drawing.Graphics.DrawRectangle
System.Drawing.Graphics.FillRectangle
RoundRect Draws a rectangle with rounded corners. System.Drawing.Drawing2D.GraphicsPath.AddLines
System.Drawing.Pen.LineJoin = System.Drawing.Pen.LineJoin.Round
System.Drawing.Graphics.DrawPath
System.Drawing.Graphics.FillPath

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Font and Text Functions

Win32 function Description .NET Framework API
AddFontMemResourceEx Adds an embedded font to the system font table. System.Drawing.Text.PrivateFontCollection.AddMemoryFont
AddFontResourceEx Adds a private or non-enumerable font to the system font table. System.Drawing.Text.PrivateFontCollection.AddFontFile
CreateFont Creates a logical font. System.Drawing.Font constructor
DrawText Draws formatted text in a rectangle. System.Drawing.Graphics.DrawString
DrawTextEx Draws formatted text in a rectangle. System.Drawing.Graphics.DrawString
EnumFontFamExProc An application-defined callback function used with EnumFontFamiliesEx to process fonts. System.Drawing.Text.InstalledFontCollection.Families
EnumFontFamiliesEx Enumerates all fonts in the system with certain characteristics. System.Drawing.Text.InstalledFontCollection.Families
ExtTextOut Draws a character string. System.Drawing.Graphics.DrawString
GetCharABCWidths Gets the widths of consecutive characters from the TrueType font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Rectangle.Round(Region.GetBounds).Width

GetCharABCWidthsFloat Gets the widths of consecutive characters from the current font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Region.GetBounds.Width

GetCharWidth32 Gets the widths of consecutive characters from the current font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Rectangle.Round(Region.GetBounds).Width

GetCharWidthFloat Gets the fractional widths of consecutive characters from the current font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Region.GetBounds.Width

GetOutlineTextMetrics Gets text metrics for TrueType fonts. System.Drawing.Font properties
GetTabbedTextExtent Computes the width and height of a character string, including tabs. System.Drawing.Graphics.MeasureString
GetTextAlign Gets the text-alignment setting for a device context. System.Drawing.StringFormat.Alignment
System.Drawing.StringFormat.LineAlignment
GetTextColor Gets the text color for a device context. System.Drawing.SolidBrush.Color
GetTextExtentPoint32 Computes the width and height of a string of text. System.Drawing.Graphics.MeasureString
GetTextFace Gets the name of the font that is selected into a device context. System.Drawing.Font.Name
GetTextMetrics Fills a buffer with the metrics for a font. System.Drawing.Font properties
RemoveFontMemResourceEx Removes a font whose source was embedded in a document from the system font table. System.Drawing.Text.PrivateFontCollection.Dispose
RemoveFontResourceEx Removes a private or non-enumerable font from the system font table. System.Drawing.Text.PrivateFontCollection.Dispose
SetTextAlign Sets the text-alignment flags for a device context. System.Drawing.StringFormat.Alignment
System.Drawing.StringFormat.LineAlignment
SetTextColor Sets the text color for a device context. Either of the following:
System.Drawing.Brushes
System.Drawing.SolidBrush.SolidBrush(Color)
TabbedTextOut Writes a character string at a location, expanding tabs to specified values. System.Drawing.Graphics.DrawString using System.Drawing.StringFormat.SetTabStops
TextOut Writes a character string at a location. System.Drawing.Graphics.DrawString

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Icon Functions

Win32 function Description .NET Framework API
CopyIcon Copies an icon from another module. System.Drawing.Icon.FromHandle
CreateIcon Creates an icon with a specified size, color, and bit pattern. System.Drawing.Icon constructor
DestroyIcon Destroys an icon. System.Drawing.Icon.Dispose
DrawIcon Draws an icon. System.Drawing.Graphics.DrawIcon
DuplicateIcon Creates a duplicate of a specified icon. System.Drawing.Icon.Clone
LoadIcon Loads an icon from the executable file associated with an application. System.Drawing.Icon constructor

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Input Method Editor Functions

Win32 function Description .NET Framework API
ImmAssociateContext Associates the specified input context with the specified window. Either of the following:
System.Windows.Forms.Control.DefaultImeMode
System.Windows.Forms.Control.ImeMode
ImmAssociateContextEx Changes the association between the input method context and the specified window or its children. Any of the following:
System.Windows.Forms.Control.DefaultImeMode
System.Windows.Forms.Control.ImeMode
System.Windows.Forms.Control.ResetImeMode
ImmDisableIME Disables the Input Method Editor. System.Windows.Forms.Control.ImeMode = System.Windows.Forms.ImeMode.Disable
ImmGetContext Retrieves the input context associated with the specified window. System.Windows.Forms.Control.ImeMode

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Keyboard Accelerator Functions

Win32 function Description .NET Framework API
TranslateAccelerator Processes accelerator keys for menu commands. System.Windows.Forms.MenuItem.Shortcut

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Keyboard Input Functions

Win32 function Description .NET Framework API
ActivateKeyboardLayout Sets the input locale identifier for the calling thread or the current process. System.Windows.Forms.InputLanguage.CurrentInputLanguage
EnableWindow Enables or disables mouse and keyboard input to the specified window or control. System.Windows.Forms.Control.Enabled
GetActiveWindow Retrieves the window handle to the active window attached to the calling thread's message queue. System.Windows.Forms.Form.ActiveForm
GetFocus Retrieves the handle to the window that has the keyboard focus. System.Windows.Forms.Control.Controls[].Focused
GetKeyboardLayout Retrieves the active input locale identifier for the specified thread. System.Windows.Forms.InputLanguage.CurrentInputLanguage
GetKeyboardLayoutList Retrieves the input locale identifiers corresponding to the current set of input locales in the system. System.Windows.Forms.InputLanguage.InstalledInputLanguages
GetKeyboardLayoutName Retrieves the name of the active input locale identifier. System.Windows.Forms.InputLanguage.LayoutName
GetKeyNameText Retrieves a string that represents the name of a key. System.Windows.Forms.KeyEventArgs.KeyCode.ToString
IsWindowEnabled Determines whether the specified window is enabled for mouse and keyboard input. System.Windows.Forms.Form.Enabled
SetActiveWindow Activates a window. System.Windows.Forms.Activate
SetFocus Sets the keyboard focus to the specified window. System.Windows.Forms.Form.Focus
ToAscii Translates the specified virtual-key code and keyboard state to the corresponding character or characters. System.Windows.Forms.KeyPressEventArgs.KeyChar
ToUnicode Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters. System.Windows.Forms.KeyPressEventArgs.KeyChar

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Line and Curve Functions

Win32 function Description .NET Framework API
AngleArc Draws a line segment and an arc. System.Drawing.Graphics.DrawLine
System.Drawing.Graphics.DrawArc
Arc Draws an elliptical arc. System.Drawing.Graphics.DrawArc
ArcTo Draws an elliptical arc. System.Drawing.Graphics.DrawArc
LineTo Draws a line from the current position up to, but not including, the specified point. System.Drawing.Graphics.DrawLine
PolyBezier Draws one or more B&x00E9;zier curves. System.Drawing.Graphics.DrawBeziers
Polyline Draws a series of line segments by connecting the points in the specified array. System.Drawing.Graphics.DrawLines

Alphabetical Win32 Category List
Hierarchical Win32 Category List

List Box Functions

Win32 function Description .NET Framework API
DlgDirList Replaces the contents of a list box with the names of the subdirectories and files in a specified directory. System.Windows.Forms.ListBox.Items.AddRange(System.IO.Directory.GetFileSystemEntries)
DlgDirSelectEx Retrieves the current selection from a single-selection list box. System.Windows.Forms.ListBox.SelectedItem
GetListBoxInfo Retrieves information about the specified list box. System.Windows.Forms.ListBox properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Memory Management Functions

Memory management functions:

Win32 function Description .NET Framework API
GlobalMemoryStatus Obtains information about the system's current usage of both physical and virtual memory. System.Management.ManagementClass("Win32_OperatingSystem")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GlobalMemoryStatusEx Obtains information about the system's current usage of both physical and virtual memory. System.Management.ManagementClass("Win32_OperatingSystem")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties

Global and local functions:

Win32 function Description .NET Framework API
GlobalAlloc Allocates the specified number of bytes from the heap. System.Runtime.InteropServices.Marshall.AllocHGlobal
GlobalFree Frees the specified global memory object. System.Runtime.InteropServices.Marshall.FreeHGlobal
GlobalReAlloc Changes the size or attributes of a specified global memory object. System.Runtime.InteropServices.Marshall.ReAllocHGlobal
LocalAlloc Allocates the specified number of bytes from the heap. System.Runtime.InteropServices.Marshall.AllocHGlobal
LocalFree Frees the specified local memory object. System.Runtime.InteropServices.Marshall.FreeHGlobal
LocalReAlloc Changes the size or the attributes of a specified local memory object. System.Runtime.InteropServices.Marshall.ReAllocHGlobal

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Menu Functions

Win32 function Descriptions .NET Framework API
AppendMenu Appends an item to various menus and submenus. System.Windows.Forms.Menu.MenuItemCollection.Add
CheckMenuItem Checks or clears a menu item. System.Windows.Forms.MenuItem.Checked
CheckMenuRadioItem Checks a specified menu item and makes it a radio item. System.Windows.Forms.MenuItem.RadioCheck
CreateMenu Creates a menu. Any of the following:
System.Windows.Forms.ContextMenu constructor
System.Windows.Forms.MainMenu constructor
System.Windows.Forms.Menu.MenuItemCollection constructor
CreatePopupMenu Creates a drop-down menu, submenu, or shortcut menu. Either of the following:
System.Windows.Forms.ContextMenu constructor
System.Windows.Forms.Menu.MenuItemCollection constructor
DeleteMenu Deletes a menu item. System.Windows.Forms.Menu.MenuItemCollection.Remove
DestroyMenu Deletes a menu. System.Windows.Forms.Menu.Dispose
EnableMenuItem Enables, disables, or grays a menu item. System.Windows.Forms.MenuItem.Enabled
GetMenu Gets a handle to the menu. System.Windows.Forms.Form.Menu.Handle
GetMenuBarInfo Gets information about a menu bar. System.Windows.Forms.Form.Menu
GetMenuCheckMarkDimensions Returns the dimensions of the default check-mark bitmap. System.Windows.Forms.SystemInformation.MenuCheckSize
GetMenuDefaultItem Gets the default menu item on a menu. System.Windows.Forms.MenuItem.DefaultItem
GetMenuInfo Gets information about a menu. System.Windows.Forms.MenuItem properties
GetMenuItemCount Gets the number of items in a menu. System.Windows.Forms.Menu.MenuItemCollection.Count
GetMenuItemID Gets the identifier of a menu item. System.Windows.Forms.MenuItem.MenuID
GetMenuItemInfo Gets information about a menu item. System.Windows.Forms.MenuItem properties
GetMenuItemRect Gets the bounding rectangle for a menu item. System.Windows.Forms.MenuItem.DrawItem
System.Windows.Forms.DrawItemEventArgs.Bounds
GetMenuState Gets the menu flags associated with a menu item. System.Windows.Forms.MenuItem.Break
System.Windows.Forms.MenuItem.BarBreak
System.Windows.Forms.MenuItem.Checked
System.Windows.Forms.MenuItem.Enabled
System.Windows.Forms.MenuItem.OwnerDraw
GetMenuString Copies the text string of a menu item into a buffer. System.Windows.Forms.MenuItem.Text
GetSubMenu Gets a handle to the drop-down menu or submenu activated by a menu item. System.Windows.Forms.Menu.MenuItems[].Handle
InsertMenu Inserts a new menu item into a menu. System.Windows.Forms.Menu.MenuItemCollection.Add
InsertMenuItem Inserts a new menu item in a menu. System.Windows.Forms.Menu.MenuItemCollection.Add
ModifyMenu Changes an existing menu item. System.Windows.Forms.MenuItem.Break
System.Windows.Forms.MenuItem.BarBreak
System.Windows.Forms.MenuItem.Checked
System.Windows.Forms.MenuItem.Enabled
System.Windows.Forms.MenuItem.OwnerDraw
System.Windows.Forms.MenuItem.Text
RemoveMenu Deletes a menu item or detaches a submenu from a menu. System.Windows.Forms.Menu.MenuItemCollection.Remove
SetMenu Assigns a new menu to a window. System.Windows.Forms.Form.Menu
SetMenuDefaultItem Sets the default menu item for a menu. System.Windows.Forms.MenuItem.DefaultItem
SetMenuInfo Sets information for a menu. System.Windows.Forms.MenuItem properties
SetMenuItemBitmaps Associates a bitmap with a menu item. System.Windows.Forms.MenuItem.DrawItem
SetMenuItemInfo Changes information about a menu item. System.Windows.Forms.MenuItem properties
TrackPopupMenu Displays a shortcut menu at a location and tracks item selection on a menu. System.Windows.Forms.ContextMenu.Show

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Message and Message Queue Functions

Win32 function Description .NET Framework API
GetMessagePos Retrieves the position of the cursor for the last message retrieved by GetMessage. Inside an event handler:
System.Windows.Forms.Windows.Forms.Control.MousePosition
PostQuitMessage Indicates to the system that a thread has made a request to terminate (quit). System.Windows.Forms.Application.ExitThread
SendMessage Sends the specified message to a window or windows. Any of the following:
System.Windows.Forms.Control.DefWndProc
System.Windows.Forms.Control.WndProc
System.Windows.Forms.Form.DefWndProc
System.Windows.Forms.Form.WndProc

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Metafile Functions

Win32 function Description .NET Framework API
CopyEnhMetaFile Copies the contents of an enhanced-format metafile to a specified file. System.Drawing.Imaging.Metafile.Save
CreateEnhMetaFile Creates a device context for an enhanced-format metafile. System.Drawing.Imaging.Metafile constructor
DeleteEnhMetaFile Deletes an enhanced-format metafile or an enhanced-format metafile handle. System.Drawing.Imaging.Metafile.Dispose
EnhMetaFileProc An application-defined callback function used with EnumEnhMetaFile. System.Drawing.Graphics.EnumerateMetafileProc
EnumEnhMetaFile Enumerates the records within an enhanced-format metafile. System.Drawing.Graphics.EnumerateMetafile
GdiComment Copies a comment from a buffer into a specified enhanced-format metafile. System.Drawing.Graphics.AddMetafileComment
GetEnhMetaFile Creates a handle that identifies the enhanced-format metafile stored in the specified file. System.Drawing.Imaging.Metafile constructor
GetEnhMetaFileBits Retrieves the contents of the specified enhanced-format metafile and copies it into a buffer. System.Drawing.Imaging.Metafile.Save
GetEnhMetaFileHeader Retrieves the record containing the header for the specified enhanced-format metafile. System.Drawing.Imaging.Metafile.GetMetafileHeader
GetEnhMetaFilePaletteEntries Retrieves optional palette entries from the specified enhanced metafile. System.Drawing.Imaging.Metafile.Palette.Entries
GetWinMetaFileBits Converts the enhanced-format records from a metafile into Windows-format records. System.Drawing.Imaging.Metafile.Save
PlayEnhMetaFile Displays the picture stored in the specified enhanced-format metafile. System.Drawing.Graphics.DrawImage
PlayEnhMetaFileRecord Plays an enhanced-metafile record by executing the graphics device interface functions identified by the record. System.Drawing.Imaging.Metafile.PlayRecord
System.Drawing.Imaging.PlayRecordCallback
SetEnhMetaFileBits Creates a memory-based enhanced-format metafile from the specified data. System.Drawing.Imaging.Metafile.Save
SetWinMetaFileBits Converts a metafile from the older Windows format to the new enhanced format. System.Drawing.Imaging.Metafile.Save

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Mouse Input Functions

Win32 function Description .NET Framework API
GetDoubleClickTime Gets the double-click time for the mouse. System.Windows.Forms.SystemInformation.DoubleClickTime
mouse_event Synthesizes mouse motion and button clicks. System.Windows.Forms.MouseEventArgs
ReleaseCapture Releases the mouse capture and restores mouse input processing. System.Windows.Forms.Control.Capture
SetCapture Sets the mouse capture to a window. System.Windows.Forms.Control.Capture
TrackMouseEvent
–or–
_TrackMouseEvent
Posts messages when a mouse leaves a window or hovers over a window. System.Windows.Forms.Control.OnMouseLeave
System.Windows.Forms.Control.OnMouseHover

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Multiple Display Monitor Functions

Win32 function Description .NET Framework API
GetMonitorInfo Retrieves information about a display monitor. System.Windows.Forms.Screen.Bounds
System.Windows.Forms.Screen.Primary
System.Windows.Forms.Screen.WorkingArea
MonitorFromPoint Retrieves a handle to the display monitor that contains a specified point. System.Windows.Forms.Screen.FromPoint
MonitorFromRect Retrieves a handle to the display monitor that has the largest area of intersection with a specified rectangle. System.Windows.Forms.Screen.FromRectangle
MonitorFromWindow Retrieves a handle to the display monitor that has the largest area of intersection with the bounding rectangle of a specified window. System.Windows.Forms.Screen.FromHandle

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Multiple-Document Interface Functions

Win32 function Description .NET Framework API
CreateMDIWindow Creates a multiple-document interface (MDI) child window. System.Windows.Forms.Form constructor
System.Windows.Forms.Form.AutoScroll
System.Windows.Forms.Form.DesktopBounds
System.Windows.Forms.Form.MdiParent
System.Windows.Forms.Form.WindowState
TranslateMDISysAccel Processes accelerator keystrokes for window menu commands of the MDI child windows associated with the specified MDI client window. Keyboard events for MDI children are automatically translated.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

National Language Functions

Win32 function Description .NET Framework API
ConvertDefaultLocale Converts a default locale value to an actual locale identifier. System.Globalization.CultureInfo.CurrentCulture
System.Globalization.CultureInfo.InstalledUICulture
EnumCalendarInfo Enumerates calendar information for a specified locale. Access the System.Globalization.CultureInfo.DateTimeFormat property to get a System.Globalization.DateTimeFormatInfo object, and then access its properties:
System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames
System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames
System.Globalization.DateTimeFormatInfo.DayNames
System.Globalization.DateTimeFormatInfo.LongDatePattern
System.Globalization.DateTimeFormatInfo.MonthNames
System.Globalization.DateTimeFormatInfo.ShortDatePattern
EnumCalendarInfoEx Enumerates calendar information for a specified locale. Iterate through the calendars:
System.Globalization.CultureInfo.DateTimeFormat.Calendar = System.Globalization.CultureInfo.OptionalCalendars[i]
EnumCalendarInfoProc An application-defined function used with EnumCalendarInfo. Same as EnumCalendarInfo
EnumCalendarInfoProcEx An application-defined function used with EnumCalendarInfoEx. Same as EnumCalendarInfoEx
EnumCodePagesProc An application-defined function used with EnumSystemCodePages. Same as EnumSystemCodePages
EnumDateFormats Enumerates the long or short date formats that are available for a specified locale. System.DateTime.GetDateTimeFormats(System.Globalization.CultureInfo)
EnumDateFormatsEx Enumerates the long or short date formats that are available for a specified locale, including date formats for any alternate calendars. Iterate through the calendars:
System.Globalization.CultureInfo.DateTimeFormat.Calendar = System.Globalization.CultureInfo.OptionalCalendars[i];
System.DateTime.GetDateTimeFormats(System.Globalization.CultureInfo)
EnumDateFormatsProc An application-defined function used with EnumDateFormats. Same as EnumDateFormats
EnumDateFormatsProcEx An application-defined function used with EnumDateFormatsEx. Same as EnumDateFormatsEx
EnumGeoInfoProc A callback function used with EnumSystemGeoID. Same as EnumSystemGeoID
EnumLocalesProc An application-defined function used with EnumSystemLocales. Same as EnumSystemLocales
EnumSystemCodePages Enumerates the code pages that are either installed on or supported by a system. System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures) returns an array of CultureInfo

The various code page properties of System.Globalization.CultureInfo.TextInfo

EnumSystemGeoID Enumerates all GeoIDs on the system. Retrieve an array of CultureInfo by calling System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures), and then access the following CultureInfo properties:
System.Globalization.CultureInfo.ThreeLetterISOLanguageName
System.Globalization.CultureInfo.ThreeLetterWindowsLanguageName
System.Globalization.CultureInfo.TwoLetterISOLanguageName
EnumSystemLocales Enumerates the locales that are either installed on or supported by a system. System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.SpecificCultures)
System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.InstalledWin32Cultures)
EnumTimeFormats Enumerates the time formats that are available for a specified locale. System.DateTime.GetDateTimeFormats
EnumTimeFormatsProc An application-defined function used with EnumTimeFormats. Same as EnumTimeFormats
GetACP Retrieves the current ANSI code-page identifier for the system. System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage
GetCalendarInfo Retrieves information about a calendar. System.Globalization.CultureInfo.DateTimeFormat
GetCurrencyFormat Formats a number string as a currency string for a specified locale. Create a System.Globalization.CultureInfo object using the constructor, specifying either the culture name or identifier (or use the current culture of the application available on System.Threading.Thread.CurrentCulture);
call System.Convert.ToDouble(str) where str is the numeric string you want to format;
and then call System.Double.ToString("C", ci) (or System.Double.ToString("C") to use the current culture), where C is the standard currency format specifier and ci is the CultureInfo object you created

Note    For more information on the variety of formatting options available in the .NET Framework, see System.String.Format.

GetDateFormat Formats a date as a date string for a specified locale. System.DateTime(…, CultureInfo(LCID).Calendar).ToString
GetLocaleInfo Retrieves information about a locale. System.Globalization.CultureInfo.DateTimeFormat
System.Globalization.CultureInfo.NumberFormat
System.Globalization.CultureInfo.TextInfo
GetNumberFormat Formats a number string as a number string customized for a specified locale. Create a System.Globalization.CultureInfo object using the constructor, specifying either the culture name or identifier (or use the current culture of the application available on System.Threading.Thread.CurrentCulture);
call System.Convert.ToDouble(str). where str is the numeric string you want to format;
and then call System.Double.ToString("N", ci) (or System.Double.ToString("N") to use the current culture), where N is the standard number format specifier and ci is the CultureInfo object you created

Note    For more information on the variety of formatting options available in the .NET Framework, see System.String.Format.

GetOEMCP Retrieves the current original equipment manufacturer (OEM) code-page identifier for the system. System.Globalization.CultureInfo.InstalledUICulture.TextInfo.OEMCodePage
GetSystemDefaultLangID Retrieves the language identifier of the system locale. System.Globalization.CultureInfo.InstalledUICulture
GetSystemDefaultLCID Retrieves the system default locale identifier. System.Globalization.CultureInfo.InstalledUICulture
GetSystemDefaultUILanguage Retrieves the language identifier for the default language of the system. System.Globalization.CultureInfo.InstalledUICulture
GetThreadLocale Retrieves the current locale for the calling thread. Either of the following:
System.Globalization.CultureInfo.CurrentCulture
System.Threading.Thread.CurrentCulture
GetTimeFormat Formats time as a time string for a specified locale. System.DateTime(…, CultureInfo(LCID).Calendar).ToString
GetUserDefaultLangID Retrieves the language identifier of the current user locale. System.Globalization.CultureInfo.CurrentCulture
GetUserDefaultLCID Retrieves the user default–locale identifier. System.Globalization.CultureInfo.CurrentCulture
GetUserDefaultUILanguage Retrieves the language identifier for the current user language. System.Globalization.CultureInfo.CurrentUICulture
GetUserGeoID Gets information about the user's location. System.Globalization.RegionInfo
IsValidCodePage Determines whether a specified code page is valid. Use an array of CultureInfo objects returned by:
System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures)

Compare to the code page properties of System.Globalization.CultureInfo.TextInfo

IsValidLocale Determines whether a specified locale identifier is valid. try{ System.Globalization.CultureInfo(LCID) }
LCMapString Maps one character string to another, performing a specified locale-dependent transformation. System.Globalization.SortKey
SetCalendarInfo Sets an item of locale information for a calendar. System.Globalization.CultureInfo.DateTimeFormat
SetLocaleInfo Sets an item of locale information. System.Globalization.CultureInfo.DateTimeFormat
System.Globalization.CultureInfo.NumberFormat
SetThreadLocale Sets the current locale for the calling thread. System.Threading.Thread.CurrentCulture

Note   Sets langid only.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Painting and Drawing Functions

Win32 function Description .NET Framework API
BeginPaint Prepares a window for painting. System.Windows.Forms.Form.OnPaint
DrawFrameControl Draws a frame control. System.Window.Forms.ControlPaint
GetBkColor Returns the background color for a device context. System.Windows.Forms.Form.BackColor
GetBkMode Returns the background mix mode for a device context. System.Windows.Forms.Form.GetStyle(ControlStyles.Opaque)
GetUpdateRect Gets the coordinates of the smallest rectangle that encloses the update region of a window. System.Windows.Forms.PaintEventArgs.ClipRectangle
GetWindowDC Gets the device context for a window, including title bar, menus, and scroll bars. Any of the following:
System.Drawing.Graphics.FromHwnd(Windows.Forms.Control.Handle)
System.Windows.Forms.Control.CreateGraphics.GetHdc
System.Windows.Forms.PaintEventArgs.Graphics.GetHdc
GetWindowRgn Gets a copy of the window region of a window. System.Windows.Forms.Control.Region
GrayString Draws gray text at a location. System.Drawing.Graphics.DrawString(…, Drawing.Brushes.Gray, …)
InvalidateRect Adds a rectangle to the update region of a window. System.Windows.Forms.Control.Invalidate
InvalidateRgn Invalidates the client area within a region. System.Windows.Forms.Control.Invalidate(System.Windows.Forms.Form.ClientRectangle)
RedrawWindow Updates a region in the client area of a window. System.Windows.Forms.Control.Update
SetBkColor Sets the background to a color value. System.Windows.Forms.Form.BackColor
SetBkMode Sets the background mix mode of a device context. System.Windows.Forms.Form.SetStyle(System.Windows.Forms.ControlStyles.Opaque, System.Boolean)
SetWindowRgn Sets the window region of a window. System.Windows.Forms.Control.Region
UpdateWindow Updates the client area of a window. System.Windows.Forms.Control.Update

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Path Functions

Win32 function Description .NET Framework API
CloseFigure Closes an open figure in a path. System.Drawing.Drawing2D.GraphicsPath.CloseFigure
FillPath Closes any open figures in the current path and fills the interior of the path by using the current brush and polygon-filling mode. System.Drawing.Graphics.FillPath
System.Drawing.Drawing2D.GraphicsPath.CloseFigures
FlattenPath Transforms any curves in the path that is selected into the current device context, turning each curve into a sequence of lines. System.Drawing.Drawing2D.GraphicsPath.Flatten
GetMiterLimit Retrieves the miter limit for the specified device context. System.Drawing.Pen.MiterLimit
GetPath Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the specified device context. System.Drawing.Drawing2D.GraphicsPath.PathData
PathToRegion Creates a region from the path that is selected into the specified device context. System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
SetMiterLimit Sets the limit for the length of miter joins for the specified device context. System.Drawing.Pen.MiterLimit
StrokeAndFillPath Closes any open figures in a path, strokes the outline of the path by using the current pen, and fills its interior by using the current brush. System.Drawing.Graphics.DrawPath
System.Drawing.Graphics.FillPath
System.Drawing.Drawing2D.GraphicsPath.CloseFigures
StrokePath Renders the specified path by using the current pen. System.Drawing.Graphics.DrawPath
WidenPath Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the given device context. System.Drawing.Drawing2D.GraphicsPath.Widen

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Pen Functions

Win32 function Description .NET Framework API
CreatePen Creates a logical pen that has the specified style, width, and color. System.Drawing.Pen constructor
ExtCreatePen Creates a logical cosmetic or geometric pen that has the specified style, width, and brush attributes. System.Drawing.Pen constructor

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Performance Monitoring Functions

Win32 function Description .NET Framework API
PdhAddCounter Initializes a counter structure for the specified counter in the specified query. System.Diagnostics.PerformanceCounter constructor
PdhCalculateCounterFromRawValue Computes the current value of a counter using the raw counter data passed in the parameter list. System.Diagnostics.CounterSample.Calculate
PdhCloseLog Closes the specified log file. System.Diagnostics.EventLog.Close
PdhCloseQuery Closes all counters contained in the specified query, closes all handles related to the query, and frees all memory associated with the query. System.Diagnostics.PerformanceCounterCategory.Delete
PdhCollectQueryData Collects the current raw data value for all counters in the specified query and updates the status code of each counter. System.Diagnostics.PerformanceCounterCategory.ReadCategory
PdhEnumObjectItems Returns the available counters and instances provided by the specified object on the specified computer. System.Diagnostics.PerformanceCounterCategory.GetCounters
System.Diagnostics.PerformanceCounterCategory.GetInstanceNames
PdhEnumObjects Returns a list of objects available on the specified computer. System.Diagnostics.PerformanceCounterCategory.GetCategories
PdhFormatFromRawValue Converts one raw performance data value to the specified format or two raw performance data values if the format conversion is time-based. System.Diagnostics.CounterSample.Calculate
PdhGetCounterInfo Retrieves information about a counter, such as data size, counter type, path, and user-supplied data values. System.Diagnostics.PerformanceCounter properties
PdhGetCounterTimeBase Returns the time base of the specified counter. System.Diagnostics.CounterSample.CounterFrequency
PdhGetFormattedCounterValue Returns the current value of a specified counter in the format requested by the caller. System.Diagnostics.PerformanceCounter.NextValue
PdhGetRawCounterArray Returns an array of raw values from the specified counter. System.Diagnostics.PerformanceCounterCategory.ReadCategory
PdhGetRawCounterValue Returns the current raw value of the counter. System.Diagnostics.PerformanceCounter.NextSample

Note   System.Diagnostics.InstanceData holds the raw data.

PdhMakeCounterPath Creates a full counter path using the members specified in the structure passed in the parameter list. All of the following:

System.Diagnostics.PerformanceCounter.MachineName
System.Diagnostics.PerformanceCounter.CategoryName
System.Diagnostics.PerformanceCounter.InstanceName
System.Diagnostics.PerformanceCounter.CounterName

PdhOpenLog Opens the specified log file. System.Diagnotics.EventLog constructor

Note   Must explicitly handle writing to the log file.

PdhOpenQuery Creates and initializes a unique query structure that is used to manage the collection of performance data. System.Diagnostics.PerformanceCounterCategory constructor
PdhValidatePath Validates that the specified counter is present on the computer that is specified in the counter path. Either of the following:
System.Diagnostics.PerformanceCounterCategory.Exists
System.Diagnostics.PerformanceCounterCategory.InstanceExists

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Printing Functions

Functions used to print:

Win32 function Description .NET Framework API
AbortDoc Stops the current print job and erases everything drawn since the last call to StartDoc. System.Drawing.Printing.PrintPageEventArgs.Cancel
DeviceCapabilities Retrieves the capabilities of a printer device driver. System.Drawing.Printing.PrinterSettings.PrinterName
System.Drawing.Printing.PrinterSettings properties
EndDoc Ends a print job. Either of the following:
System.Drawing.Printing.PrintDocument.OnEndPrint
System.Drawing.Printing.PrintController.OnEndPrint
EndPage Notifies the device that the application has finished writing to a page. System.Drawing.Printing.PrintController.OnEndPage
StartDoc Starts a print job. System.Drawing.Printing.PrintDocument.Print
System.Drawing.Printing.PrintDocument.OnBeginPrint
System.Drawing.Printing.PrintController.OnStartPrint
StartPage Prepares the printer driver to accept data. System.Drawing.Printing.PrintDocument.OnQueryPageSettings
System.Drawing.Printing.PrintController.OnStartPage
System.Drawing.Printing.PrintDocument.OnPrintPage

Functions used to access the print spooler:

Win32 function Description .NET Framework API
DocumentProperties Retrieves or modifies printer initialization information or displays a printer-configuration property sheet for the specified printer. System.Windows.Forms.PageSetupDialog
System.Windows.Forms.PrintDialog
EndPagePrinter Notifies the print spooler that the application is at the end of a page in a print job. System.Drawing.Printing.PrintPageEventArgs.HasMorePages
EnumForms Enumerates the forms supported by the specified printer. System.Drawing.Printing.PrinterSettings.PaperSizes
EnumPrinters Enumerates available printers, print servers, domains, or print providers. System.Drawing.Printing.PrinterSettings.InstalledPrinters
GetDefaultPrinter Retrieves the printer name of the default printer for the current user on the local computer. System.Drawing.Printing.PrinterSettings constructor
System.Drawing.Printing.PrinterSettings.PrinterName
GetForm Retrieves information about a specified form. System.Drawing.Printing.PrinterSettings.PaperSizes[]
GetPrinter Retrieves information about a specified printer. System.Drawing.Printing.PrinterSettings.PrinterName
System.Drawing.Printing.PrinterSettings properties
PrinterProperties Displays a printer-properties property sheet for the specified printer. System.Windows.Forms.PageSetupDialog
System.Windows.Forms.PrintDialog
SetPrinter Sets the data for a specified printer or sets the state of the specified printer by pausing printing, resuming printing, or clearing all print jobs. System.Drawing.Printing.PrinterSettings.PrinterName
System.Drawing.Printing.PrinterSettings properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Process and Thread Functions

Functions used with processes:

Win32 function Description .NET Framework API
CreateProcess Creates a new process and its primary thread. System.Diagnostics.Process constructor
System.Diagnostics.Process.Start
ExitProcess Ends a process and all its threads. System.Diagnostics.Process.CloseMainWindow
GetCommandLine Retrieves the command-line string for the current process. Either of the following:
System.Environment.CommandLine
System.Diagnostics.ProcessStartInfo.Arguments
GetCurrentProcess Retrieves a pseudo handle for the current process. System.Diagnostics.Process.Handle
GetCurrentProcessId Retrieves the process identifier of the calling process. System.Diagnostics.Process.Id
GetEnvironmentStrings Retrieves the environment block for the current process. System.Diagnostics.ProcessStartInfo.EnvironmentVariables
GetEnvironmentVariable Retrieves the value of the specified variable from the environment block of the calling process. System.Diagnostics.ProcessStartInfo.EnvironmentVariables[]
GetExitCodeProcess Retrieves the termination status of the specified process. System.Diagnostics.Process.ExitCode
GetPriorityClass Retrieves the priority class for the specified process. System.Diagnostics.Process.PriorityClass
GetProcessAffinityMask Retrieves a process affinity mask for the specified process and the system affinity mask for the system. System.Diagnostics.Process.ProcessorAffinity
GetProcessPriorityBoost Retrieves the priority boost control state of the specified process. System.Diagnostics.Process.PriorityBoostEnabled
GetProcessTimes Retrieves timing information for the specified process. System.Diagnostics.Process.ExitTime
System.Diagnostics.Process.PrivilegedProcessorTime
System.Diagnostics.Process.StartTime
System.Diagnostics.Process.TotalProcessorTime
System.Diagnostics.Process.UserProcessorTime
GetProcessWorkingSetSize Retrieves the minimum and maximum working set sizes of the specified process. System.Diagnostics.Process.MinWorkingSet
System.Diagnostics.Process.MaxWorkingSet
GetStartupInfo Retrieves the contents of the STARTUPINFO structure that was specified when the calling process was created. System.Diagnostics.Process.StandardError
System.Diagnostics.Process.StandardInput
System.Diagnostics.Process.StandardOutput
System.Diagnostics.Process.StartInfo.WindowStyle
OpenProcess Opens an existing process object. System.Diagnostics.Process.GetProcessById
SetEnvironmentVariable Sets the value of an environment variable for the current process. System.Diagnostics.ProcessStartInfo.EnvironmentVariables[]
SetPriorityClass Sets the priority class for the specified process. System.Diagnostics.Process.PriorityClass
SetProcessAffinityMask Sets a processor affinity mask for the threads of a specified process. System.Diagnostics.Process.ProcessorAffinity
SetProcessPriorityBoost Disables the ability of the system to temporarily boost the priority of the threads of the specified process. System.Diagnostics.Process.PriorityBoostEnabled
SetProcessWorkingSetSize Sets the minimum and maximum working set sizes for the specified process. System.Diagnostics.Process.MaxWorkingSet
System.Diagnostics.Process.MinWorkingSet
TerminateProcess Terminates the specified process and all of its threads. System.Diagnostics.Process.Kill

Functions used with threads:

Win32 function Description .NET Framework API
CreateThread Creates a thread to execute within the virtual address space of the calling process. System.Threading.Thread constructor
System.Threading.Thread.Start
GetCurrentThread Retrieves a pseudo handle for the current thread. System.Threading.Thread.CurrentThread
GetCurrentThreadId Retrieves the thread identifier of the calling thread. Either of the following:
System.AppDomain.GetCurrentThreadId
System.Diagnostics.ProcessThread.Id
GetThreadPriority Retrieves the priority value for the specified thread. Either of the following:
System.Diagnostics.ProcessThread.PriorityLevel
System.Threading.Thread.Priority
GetThreadPriorityBoost Retrieves the priority boost control state of the specified thread. System.Diagnostics.ProcessThread.PriorityBoostEnabled
GetThreadTimes Retrieves timing information for the specified thread. System.Diagnostics.ProcessThread.PrivilegedProcessorTime
System.Diagnostics.ProcessThread.StartTime
System.Diagnostics.ProcessThread.TotalProcessorTime
System.Diagnostics.ProcessThread.UserProcessorTime
ResumeThread Decrements the suspend count for a thread. System.Threading.Thread.Resume
SetThreadAffinityMask Sets a processor affinity mask for the specified thread. System.Diagnostics.ProcessThread.ProcessorAffinity
SetThreadIdealProcessor Specifies a preferred processor for a thread. System.Diagnostics.ProcessThread.IdealProcessor
SetThreadPriority Sets the priority value for the specified thread. Either of the following:
System.Diagnostics.ProcessThread.PriorityLevel
System.Threading.Thread.Priority
SetThreadPriorityBoost Enables or disables the ability of the system to temporarily boost the priority of a thread. System.Diagnostics.ProcessThread.PriorityBoostEnabled
Sleep Suspends the execution of the current thread for a specified interval. System.Threading.Thread.Sleep
SuspendThread Suspends the specified thread. System.Threading.Thread.Suspend
SwitchToThread Causes the calling thread to yield execution to another thread that is ready to run on the current processor. System.Threading.Thread.Sleep(0)
TerminateThread Terminates a thread. System.Threading.Thread.Abort
ThreadProc An application-defined function that serves as the starting address for a thread. See System.Threading.ThreadStart delegate
TlsAlloc Allocates a thread local storage (TLS) index. System.Threading.Thread.AllocateNamedDataSlot
TlsFree Releases a TLS index. System.Threading.Thread.FreeNamedDataSlot
TlsGetValue Retrieves the value in the calling thread's TLS slot for a specified TLS index. System.Threading.Thread.GetData
TlsSetValue Stores a value in the calling thread's TLS slot for a specified TLS index. System.Threading.Thread.SetData
WaitForInputIdle Waits until the specified process is waiting for user input with no input pending or until the time-out interval has elapsed. System.Diagnostics.Process.WaitForInputIdle

Functions used in thread pooling:

Win32 function Description .NET Framework API
BindIoCompletionCallback Binds the specified file handle to the I/O completion port for the thread pool. System.Threading.ThreadPool.BindHandle
QueueUserWorkItem Queues a work item to a worker thread in the thread pool. System.Threading.ThreadPool.QueueUserWorkItem
System.Threading.ThreadPool.UnsafeQueueUserWorkItem

Alphabetical Win32 Category List
Hierarchical Win32 Category List

PSAPI Functions

Win32 function Description .NET Framework API
EnumProcesses Retrieves the process identifier for each process object in the system. System.Diagnostics.Process.GetProcesses
EnumProcessModules Retrieves a handle for each module in the specified process. System.Diagnostics.Process.Modules
GetModuleBaseName Retrieves the base name for the specified module. System.Diagnostics.ProcessModule.ModuleName
GetModuleFileNameEx Retrieves the fully qualified path for the specified module. Either of the following:
System.Diagnostics.ProcessModule.FileName
System.Reflection.Module.FullyQualifiedName
GetModuleInformation Retrieves information about the specified module. System.Diagnostics.ProcessModule
GetProcessMemoryInfo Retrieves information about the memory usage of the specified process. System.Diagnostics.Process.PagedMemorySize
System.Diagnostics.Process.PeakPagedMemorySize
System.Diagnostics.Process.PeakWorkingSet
System.Diagnostics.Process.WorkingSet

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Rectangle Functions

Win32 function Description .NET Framework API
EqualRect Determines whether the two specified rectangles are equal by comparing the coordinates of their upper-left and lower-right corners. System.Drawing.Rectangle.Equals
InflateRect Increases or decreases the width and height of the specified rectangle. System.Drawing.Rectangle.Inflate
IntersectRect Calculates the intersection of two source rectangles and places the coordinates of the intersection rectangle into the destination rectangle. System.Drawing.Rectangle.Intersect
IsRectEmpty Determines whether the specified rectangle is empty. System.Drawing.Rectangle.IsEmpty
OffsetRect Moves the specified rectangle by the specified offsets. System.Drawing.Rectangle.Offset
PtInRect Determines whether the specified point lies within the specified rectangle. System.Drawing.Rectangle.Contains
SetRect Sets the coordinates of the specified rectangle. System.Drawing.Rectangle.FromLTRB
SetRectEmpty Creates an empty rectangle in which all coordinates are set to zero. System.Drawing.Rectangle.FromLTRB
UnionRect Creates the union of two rectangles. System.Drawing.Rectangle.Union

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Region Functions

Win32 function Description .NET Framework API
CombineRgn Combines two regions and stores the result in a third region. System.Drawing.Region.Clone
System.Drawing.Region.Exclude
System.Drawing.Region.Intersect
System.Drawing.Region.Union
System.Drawing.Region.Xor
CreateEllipticRgn Creates an elliptical region. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddEllipse
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreateEllipticRgnIndirect Creates an elliptical region. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddEllipse
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreatePolygonRgn Creates a polygonal region. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddPolygon
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreatePolyPolygonRgn Creates a region consisting of a series of polygons. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddPolygon
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreateRectRgnIndirect Creates a rectangular region. System.Drawing.Region.Region(System.Drawing.Rectangle)
CreateRoundRectRgn Creates a rectangular region with rounded corners. System.Drawing.Drawing2D.GraphicsPath.AddLines
System.Drawing.Pen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round
EqualRgn Checks the two specified regions to determine whether they are identical. System.Drawing.Region.Equals
ExtCreateRegion Creates a region from the specified region and transformation data. System.Drawing.Region.Transform
FillRgn Fills a region by using the specified brush. System.Drawing.Graphics.FillRegion
GetPolyFillMode Retrieves the current polygon fill mode. System.Drawing.Drawing2D.GraphicsPath.FillMode
GetRegionData Fills the specified buffer with data describing a region. System.Drawing.Region.GetRegionData
GetRgnBox Retrieves the bounding rectangle of the specified region. System.Drawing.Region.GetBounds
OffsetRgn Moves a region by the specified offsets. System.Drawing.Region.Translate
PtInRegion Determines whether the specified point is inside the specified region. System.Drawing.Region.IsVisible
RectInRegion Determines whether any part of the specified rectangle is within the boundaries of a region. System.Drawing.Region.IsVisible
SetPolyFillMode Sets the polygon fill mode for functions that fill polygons. System.Drawing.Drawing2D.GraphicsPath.FillMode

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Registry Functions

Win32 function Description .NET Framework API
RegCloseKey Releases a handle to the specified registry key. Microsoft.Win32.RegistryKey.Close
RegConnectRegistry Establishes a connection to a predefined registry handle on another computer. Microsoft.Win32.RegistryKey.OpenRemoteBaseKey
RegCreateKeyEx Creates the specified registry key. Microsoft.Win32.RegistryKey.CreateSubKey
RegDeleteKey Deletes a subkey. Microsoft.Win32.RegistryKey.DeleteSubKeyTree
RegDeleteValue Removes a named value from the specified registry key. Microsoft.Win32.RegistryKey.DeleteValue
RegEnumKeyEx Enumerates subkeys of the specified open registry key. Microsoft.Win32.RegistryKey.GetSubKeyNames
RegEnumValue Enumerates the values for the specified open registry key. Microsoft.Win32.RegistryKey.GetValueNames
Microsoft.Win32.RegistryKey.GetValue
RegFlushKey Writes all the attributes of the specified open registry key into the registry. Microsoft.Win32.RegistryKey.Flush
RegOpenCurrentUser Retrieves a handle to the HKEY_CURRENT_USER key for the user that the current thread is impersonating. Microsoft.Win32.Registry.CurrentUser
RegOpenKeyEx Opens the specified registry key. Microsoft.Win32.RegistryKey.OpenSubKey
RegOpenUserClassesRoot Retrieves a handle to the HKEY_CLASSES_ROOT key for the specified user. Microsoft.Win32.Registry.ClassesRoot
RegQueryInfoKey Retrieves information about the specified registry key. Microsoft.Win32.RegistryKey.SubKeyCount
Microsoft.Win32.RegistryKey.ValueCount
RegQueryValueEx Retrieves the type and data for a specified value name associated with an open registry key. Microsoft.Win32.RegistryKey.GetValue
RegSetValueEx Sets the data and type of a specified value under a registry key. Microsoft.Win32.RegistryKey.SetValue

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Resource Functions

Win32 function Description .NET Framework API
CopyImage Creates a new icon, cursor, or bitmap and copies the attributes of the old one to the new one. System.Drawing.Image.Clone
EnumResNameProc An application-defined callback function used with EnumResourceNames. System.Resources.ResourceReader.GetEnumerator
EnumResourceNames Searches for resources of a specified type and passes the name or the ID to a callback function. System.Resources.ResourceReader.GetEnumerator
LoadImage Loads an icon, cursor, or bitmap. System.Drawing.Bitmap.Bitmap(System.Type, System.String)
System.Drawing.Icon.Icon(System.Type, System.String)
System.Windows.Forms.Cursor.Cursor(System.Type, System.String)
System.Resources.ResourceManager.GetObject
System.Resources.ResourceSet.GetObject

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Rich Edit Control Functions

Win32 Funtion Description .NET Framework API
EditStreamCallback An application-defined callback function used with the EM_STREAMIN and EM_STREAMOUT messages. System.Windows.Forms.RichTextBox.LoadFile
System.Windows.Forms.RichTextBox.RichTextBox.SaveFile

Note   Not a callback function.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Scroll Bar Functions

Win32 function Description .NET Framework API
EnableScrollBar Enables or disables one or both scroll bar arrows. System.Windows.Forms.ScrollBar.Enabled

Note   Cannot enable/disable built-in scrollbars (auto-scrolling).

GetScrollBarInfo Retrieves information about the specified scroll bar. System.Windows.Forms.ScrollBar.Value
System.Windows.Forms.ScrollEventArgs.Type
GetScrollInfo Retrieves the parameters of a scroll bar. System.Windows.Forms.ScrollBar.Maximum
System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Value
GetScrollPos Retrieves the current position of the scroll box. System.Windows.Forms.ScrollBar.Value
GetScrollRange Retrieves the current minimum and maximum scroll box positions. System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Maximum
SetScrollInfo Sets the parameters of a scroll bar. System.Windows.Forms.ScrollBar.Maximum
System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Value
SetScrollPos Sets the position of the scroll box. System.Windows.Forms.ScrollBar.Value
SetScrollRange Sets the minimum and maximum scroll box position. System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Maximum
ShowScrollBar Shows or hides the specified scroll bar. Any of the following:
System.Windows.Forms.Form.AutoScroll
System.Windows.Forms.HScrollBar constructor
System.Windows.Forms.ListBox.HorizontalScrollBar
System.Windows.Forms.ListBox.ScrollAlwaysVisible
System.Windows.Forms.RichTextBox.ScrollBars
System.Windows.Forms.ScrollableControl.HScroll
System.Windows.Forms.ScrollableControl.VScroll
System.Windows.Forms.TextBox.ScrollBars
System.Windows.Forms.VScrollBar constructor

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Service Functions

Functions implemented by services:

Win32 function Description .NET Framework API
Handler An application-defined callback function used with RegisterServiceCtrlHandler. All of the following:
System.ServiceProcess.ServiceBase.OnContinue
System.ServiceProcess.ServiceBase.OnCustomCommand
ServiceProcess.ServiceBase.OnPause
System.ServiceProcess.ServiceBase.OnShutdown
System.ServiceProcess.ServiceBase.OnStop
HandlerEx An application-defined callback function used with RegisterServiceCtrlHandlerEx. All of the following:
System.ServiceProcess.ServiceBase.OnContinue
System.ServiceProcess.ServiceBase.OnCustomCommand
System.ServiceProcess.ServiceBase.OnPause
System.ServiceProcess.ServiceBase.OnPowerEvent
System.ServiceProcess.ServiceBase.OnShutdown
System.ServiceProcess.ServiceBase.OnStop
ServiceMain An application-defined function that serves as the entry point for a service. System.ServiceProcess.ServiceBase.Run

Functions used by programs that control or configure services:

Win32 function Description .NET Framework API
ChangeServiceConfig Changes the configuration parameters of a service. System.ServiceProcess.ServiceController.DisplayName
CloseServiceHandle Closes the specified handle to a service control manager object or a service object. System.ServiceProcess.ServiceController.Close
ControlService Sends a control code to a service. System.ServiceProcess.ServiceController.Continue
System.ServiceProcess.ServiceController.Pause
System.ServiceProcess.ServiceController.Stop
CreateService Creates a service object and adds it to the specified service control manager database. System.ServiceProcess.ServiceBase.ServiceName
System.ServiceProcess.ServiceInstaller.Install
DeleteService Marks the specified service for deletion from the service control manager database. System.ServiceProcess.ServiceInstaller.Uninstall
EnumDependentServices Retrieves the name and status of each service that depends on the specified service. System.ServiceProcess.ServiceController.DependentServices
EnumServicesStatus Enumerates services in the specified service control manager database. System.ServiceProcess.ServiceController.GetServices
GetServiceDisplayName Retrieves the display name of the specified service. System.ServiceProcess.ServiceController.DisplayName
GetServiceKeyName Retrieves the name of the specified service. System.ServiceProcess.ServiceBase.ServiceName
System.ServiceProcess.ServiceController.ServiceName
OpenService Opens an existing service. System.ServiceProcess.ServiceController constructor
QueryServiceConfig Retrieves the configuration parameters of the specified service. System.ServiceProcess.ServiceController.DisplayName
System.ServiceProcess.ServiceController.ServicesDependedOn
System.ServiceProcess.ServiceController.ServiceName
System.ServiceProcess.ServiceController.ServiceType
QueryServiceStatus Retrieves the current status of the specified service. System.ServiceProcess.ServiceController.Status
StartService Starts a service. System.ServiceProcess.ServiceController.Start

Alphabetical Win32 Category List
Hierarchical Win32 Category List

String Functions

Win32 function Description .NET Framework API
CharLower Converts a character string or a single character to lowercase. System.String.ToLower
CharNext Retrieves a pointer to the next character in a string. System.String.GetEnumerator.MoveNext
CharUpper Converts a character string or a single character to uppercase. System.String.ToUpper
CompareString Compares two character strings, using the specified locale. System.String.Compare
IsCharAlpha Determines whether a character is an alphabetical character. System.Char.IsLetter
IsCharAlphaNumeric Determines whether a character is either an alphabetical or a numeric character. System.Char.IsLetterOrDigit
IsCharLower Determines whether a character is lowercase. System.Char.IsLower
IsCharUpper Determines whether a character is uppercase. System.Char.IsUpper
LoadString Loads a string resource from the executable file associated with a specified module. System.Resources.ResourceManager.GetString
lstrcat Appends one string to another. System.String.Concat

Note   Strings are immutable in the .NET Framework. Methods that appear to modify a string actually return a new string.

lstrcmp Compares two character strings. System.String.Compare
lstrcmpi Compares two character strings. System.String.Compare
lstrcpy Copies a string to a buffer. System.String.ToCharArray
lstrcpyn Copies a specified number of characters from a source string into a buffer. System.String.CopyTo
System.String.ToCharArray
lstrlen Retrieves the length of the specified string (not including the terminating null character). System.String.Length
wsprintf Formats and stores a series of characters and values in a buffer. System.String.Format
wvsprintf Formats and stores a series of characters and values in a buffer. System.String.Format

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Structured Exception-Handling Functions

Win32 function Description .NET Framework API
GetExceptionCode Retrieves a code that identifies the type of exception that occurred. System.Exception.GetType
GetExceptionInformation Retrieves a machine-independent description of an exception and information about the machine state that existed for the thread when the exception occurred. System.Exception class
RaiseException Raises an exception in the calling thread. Throw an instance of a System.Exception

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Synchronization Functions

CriticalSection functions:

Win32 function Description .NET Framework API
EnterCriticalSection Waits for ownership of the specified critical section object. System.Threading.Monitor.Enter
LeaveCriticalSection Releases ownership of the specified critical section object. System.Threading.Monitor.Exit
TryEnterCriticalSection Attempts to enter a critical section without blocking. System.Threading.Monitor.TryEnter

Event functions:

Win32 function Description .NET Framework API
CreateEvent Creates or opens a named or an unnamed event object. Either of the following:
System.Threading.AutoResetEvent constructor
System.Threading.ManualResetEvent constructor
ResetEvent Sets the specified event object to the nonsignaled state. Either of the following:
System.Threading.AutoResetEvent.Reset
System.Threading.ManualResetEvent.Reset
SetEvent Sets the specified event object to the signaled state. Either of the following:
System.Threading.AutoResetEvent.Set
System.Threading.ManualResetEvent.Set

Interlocked functions:

Win32 function Description .NET Framework API
InterlockedCompareExchange Performs an atomic comparison of the specified values and exchanges the values, based on the outcome of the comparison. System.Threading.Interlocked.CompareExchange
InterlockedCompareExchangePointer Performs an atomic comparison of the specified values and exchange of the values, based on the outcome of the comparison. System.Threading.Interlocked.CompareExchange
InterlockedDecrement Decrements (decreases by one) the value of the specified variable and checks the resulting value. System.Threading.Interlocked.Decrement
InterlockedExchange Atomically exchanges a pair of values. System.Threading.Interlocked.Exchange
InterlockedIncrement Increments (increases by one) the value of the specified variable and checks the resulting value. System.Threading.Interlocked.Increment

Mutex functions:

Win32 function Description .NET Framework API
CreateMutex Creates or opens a named or an unnamed mutex object. System.Threading.Mutex constructor
OpenMutex Opens an existing named mutex object. System.Threading.Mutex(false, string, name) constructor
ReleaseMutex Releases ownership of the specified mutex object. System.Threading.Mutex.ReleaseMutex

Wait functions:

Win32 function Description .NET Framework API
RegisterWaitForSingleObject Directs a wait thread in the thread pool to wait on the object. System.Threading.ThreadPool.RegisterWaitForSingleObject
System.Threading.ThreadPool.UnsafeRegisterWaitForSingleObject
UnregisterWait Cancels a registered wait operation. System.Threading.RegisteredWaitHandle.Unregister
WaitForMultipleObjects Returns when the specified criteria for the specified objects is met. Either of the following:
System.Threading.WaitHandle.WaitAll
System.Threading.WaitHandle.WaitAny
WaitForSingleObject Returns when the specified criteria for the specified object is met. System.Threading.WaitHandle.WaitOne
WaitOrTimerCallback Returns when the specified criteria is met. See System.Threading.WaitOrTimerCallback delegate

WaitableTimer functions:

Win32 function Description .NET Framework API
CancelWaitableTimer Sets the specified waitable timer to the inactive state. System.Threading.Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
CreateWaitableTimer Creates or opens a waitable timer object. System.Threading.Timer constructor
SetWaitableTimer Activates the specified waitable timer. System.Threading.Timer constructor
TimerAPCProc Application-defined timer completion routine used with SetWaitableTimer. See System.Threading.TimerCallback delegate

Alphabetical Win32 Category List
Hierarchical Win32 Category List

System Information Functions

Win32 function Description .NET Framework API
ExpandEnvironmentStrings Replaces environment-variable strings with their defined values. System.Environment.ExpandEnvironmentVariables
GetComputerName Retrieves the NetBIOS name of the local computer. System.Environment.MachineName
System.Windows.Forms.SystemInformation.ComputerName
GetCurrentHwProfile Retrieves the current hardware profile for the local computer. Use System.Management and Microsoft.Win32.RegistryKey
GetKeyboardType Retrieves information about the current keyboard. System.Management.ManagementClass("Win32_Keyboard")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GetNativeSystemInfo Retrieves information about the current system for an application running under WOW64. System.Management.ManagementClass("Win32_Processor")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GetSysColor Retrieves the current color of a display element. System.Drawing.SystemColors
GetSystemDirectory Retrieves the path of the system directory. System.Environment.SystemDirectory
GetSystemInfo Retrieves information about the current system. System.Management.ManagementClass("Win32_Processor")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GetSystemMetrics Retrieves system metrics and configuration settings. System.Windows.Forms.SystemInformation properties
GetUserName Retrieves the user name of the current thread. System.Environment.UserName
GetVersion Retrieves the version number of the operating system. System.Environment.OSVersion
GetVersionEx Retrieves the version number of the current operating system. System.Environment.OSVersion
GetWindowsDirectory Retrieves the path of the Windows directory. System.Management.ManagementClass("Win32_OperatingSystem")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject["WindowsDirectory"].ToString

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Tape Backup Functions

Win32 function Description .NET Framework API
GetTapeParameters Retrieves information that describes the tape or the tape drive. System.Management.ManagementClass("MSTapeMediaCapacity")
System.Management.ManagementClass("Win32_TapeDrive")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Text Object Model Functions

Win32 function Description .NET Framework API
ITextDocument Retrieves the active selection and range objects for any story in the document. System.Windows.Forms.RichTextBox
ITextFont Encapsulates the functionality of the Microsoft Word Font dialog box. System.Windows.Forms.RichTextBox
ITextPara Encapsulates the functionality of the Microsoft Word Paragraph dialog box. System.Windows.Forms.RichTextBox
ITextRange Enables an application to select text in a story, and then examine or change that text. System.Windows.Forms.RichTextBox

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Time Functions

Win32 function Description .NET Framework API
GetSystemTime Retrieves the current system date and time in UTC format. System.DateTime.UtcNow
GetTimeFormat Formats a system time as a time string for a specified locale. System.DateTime.ToString
SystemTimeToFileTime Converts a system time to a file time. System.DateTime.ToFileTime
FileTimeToLocalFileTime Converts a UTC file time to a local file time. System.DateTime.ToFileTime
GetLocalTime Retrieves the current local date and time. System.DateTime.Now
GetTimeZoneInformation Retrieves the current time-zone parameters. System.TimeZone.CurrentTimeZone
CompareFileTime Compares two file times. System.DateTime.Compare
FileTimeToLocalFileTime Converts a UTC file time to a local file time. System.DateTime.ToLocalTime
FileTimeToSystemTime Converts a file time to system time format. System.DateTime.ToUniversalTime
GetFileTime Retrieves the date and time that a file was created, last accessed, and last modified. Any of the following:
System.IO.Directory.GetCreationTime
System.IO.Directory.GetLastAccessTime
System.IO.Directory.GetLastWriteTime
System.IO.DirectoryInfo.CreationTime
System.IO.DirectoryInfo.LastAccessTime
System.IO.DirectoryInfo.LastWriteTime
System.IO.File.GetCreationTime
System.IO.File.GetLastAccessTime
System.IO.File.GetLastWriteTime
System.IO.FileInfo.CreationTime
System.IO.FileInfo.LastAccessTime
System.IO.FileInfo.LastWriteTime
GetSystemTimeAsFileTime Retrieves the current system date and time in UTC format. System.DateTime.UtcNow.ToFileTimeUtc
LocalFileTimeToFileTime Converts a local file time to a file time based on UTC. System.DateTime.ToFileTimeUtc
SetFileTime Sets the date and time that a file was created, last accessed, or last modified. Any of the following:
System.IO.Directory.SetCreationTime
System.IO.Directory.SetLastAccessTime
System.IO.Directory.SetLastWriteTime
System.IO.DirectoryInfo.CreationTime
System.IO.DirectoryInfo.LastAccessTime
System.IO.DirectoryInfo.LastWriteTime
System.IO.File.SetCreationTime
System.IO.File.SetLastAccessTime
System.IO.File.SetLastWriteTime
System.IO.FileInfo.CreationTime
System.IO.FileInfo.LastAccessTime
System.IO.FileInfo.LastWriteTime
SystemTimeToFileTime Converts a system time to a file time. System.DateTime.ToFileTime
GetTickCount Retrieves the number of milliseconds that have elapsed since the system was started. System.Environment.TickCount

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Timer Functions

Win32 function Description .NET Framework API
KillTimer Destroys the specified timer. System.Threading.Timer.Dispose
System.Timers.Timer.Dispose
System.Windows.Forms.Timer.Dispose
QueryPerformanceCounter Retrieves the current value of the high-resolution performance counter. System.Diagnostics.PerformanceCounter.NextValue
System.Diagnostics.PerformanceCounter.RawValue
QueryPerformanceFrequency Retrieves the frequency of the high-resolution performance counter. System.Diagnostics.PerformanceCounter.CounterType
SetTimer Creates a timer with the specified time-out value. Any of the following:
System.Threading.Timer constructor
System.Timers.Timer constructor
System.Windows.Forms.Timer constructor
System.Windows.Forms.Timer.Interval
TimerProc An application-defined callback function that processes WM_TIMER messages. Either of the following:
System.Threading.TimerCallback delegate
System.Timers.ElapsedEventHandler delegate

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Tool Help Functions

Win32 function Description .NET Framework API
CreateToolhelp32Snapshot Takes a snapshot of the processes and heaps, modules, and threads used by the processes. System.Diagnostics.Process.GetProcesses
System.Diagnostics.Process.Modules
System.Diagnostics.Process.Threads
Module32First Retrieves information about the first module associated with a process. System.Diagnostics.Process.Modules
Module32Next Retrieves information about the next module associated with a process or thread. System.Diagnostics.Process.Modules
Process32First Retrieves information about the first process encountered in a system snapshot. System.Diagnostics.Process.GetProcesses
Process32Next Retrieves information about the next process recorded in a system snapshot. System.Diagnostics.Process.GetProcesses
Thread32First Retrieves information about the first thread of any process encountered in a system snapshot. System.Diagnostics.Process.Threads
Thread32Next Retrieves information about the next thread of any process encountered in the system memory snapshot. System.Diagnostics.Process.Threads

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Unicode and Character Set Functions

Win32 function Description .NET Framework API
GetTextCharset Retrieves a character-set identifier for the font that is currently selected into a specified device context. System.Drawing.Font.GdiCharSet

Alphabetical Win32 Category List
Hierarchical Win32 Category List

User Profile Functions

Win32 function Description .NET Framework API
CreateEnvironmentBlock Retrieves the environment variables for the specified user. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
DeleteProfile Deletes the user profile and all user-related settings from the specified computer. System.IO.Directory.Delete
Microsoft.Win32.Registry
Microsoft.Win32.RegistryKey.DeleteSubKey
ExpandEnvironmentStringsForUser Expands the source string by using the environment block established for the specified user. Microsoft.Win32.Registry class

Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValueNames, and then call GetValue for each name

GetAllUsersProfileDirectory Retrieves the path to the root of the All Users profile. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
GetDefaultUserProfileDirectory Retrieves the path to the root of the Default User profile. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
GetProfilesDirectory Retrieves the path to the root directory where all of the user profiles are stored. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
GetUserProfileDirectory Retrieves the path to the root directory of the profile for the specified user. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Version Information Functions

Win32 function Description .NET Framework API
GetFileVersionInfo Retrieves version information for the specified file. System.Diagnostics.FileVersionInfo.GetVersionInfo
GetFileVersionInfoSize Determines whether the operating system can retrieve version information for a specified file. If version information is available, the function returns the size, in bytes, of that information. System.Diagnostics.FileVersionInfo.GetVersionInfo
VerLanguageName Retrieves a description string for the language associated with a specified binary Microsoft language identifier. System.Globalization.CultureInfo.Name
VerQueryValue Retrieves specified version information from the specified version-information resource. System.Diagnostics.FileVersionInfo properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Functions

Win32 function Description .NET Framework API
AdjustWindowRect Calculates the required size of the window rectangle, based on the desired client-rectangle size. System.Windows.Forms.Form.ClientSize
AdjustWindowRectEx Calculates the required size of the window rectangle, based on the desired client-rectangle size. System.Windows.Forms.Form.ClientSize
ArrangeIconicWindows Arranges all minimized (iconic) child windows of the specified parent window. System.Windows.Forms.Form.LayoutMdi(MdiLayout.ArrangeIcons)
BringWindowToTop Brings the specified window to the top of the Z order. System.Windows.Forms.Form.BringToFront
CascadeWindows Cascades the specified child windows of the specified parent window. System.Windows.Forms.Form.LayoutMdi(MdiLayout.Cascade)
ChildWindowFromPoint Determines which, if any, of the child windows belonging to a parent window contains the specified point. System.Windows.Forms.Form.GetChildAtPoint
CloseWindow Minimizes (but does not destroy) the specified window. System.Windows.Forms.Form.WindowState = System.Windows.Forms.FormWindowState.Minimized
CreateWindow Creates an overlapped, pop-up, or child window. System.Windows.Forms.Form constructor
CreateWindowEx Creates an overlapped, pop-up, or child window with an extended window style. System.Windows.Forms.Form constructor
DestroyWindow Destroys the specified window. System.Windows.Forms.Form.Close
EnumChildProc An application-defined callback function used with EnumChildWindows. Same as EnumChildWindows
EnumChildWindows Enumerates the child windows that belong to the specified parent window. System.Windows.Forms.Form.Controls
GetAncestor Retrieves the handle to the ancestor of the specified window. System.Windows.Forms.Form.FindForm
System.Windows.Forms.Form.Owner
System.Windows.Forms.Form.Parent
GetClientRect Retrieves the coordinates of the client area for a window. System.Windows.Forms.Form.ClientRectangle
GetForegroundWindow Returns a handle to the foreground window. System.Windows.Forms.Form.ActiveForm
GetLayeredWindowAttributes Retrieves the opacity and transparency color key of a layered window. System.Windows.Forms.Form.Opacity
System.Windows.Forms.Form.TransparencyKey
GetNextWindow Retrieves a handle to the next or previous window in Z order. System.Windows.Forms.Form.Controls[1 +/- Control.IndexOf]
GetParent Retrieves a handle to the parent window for the specified child window. System.Windows.Forms.Form.FindForm
System.Windows.Forms.Form.Parent
GetTitleBarInfo Retrieves information about the specified title bar. System.Windows.Forms.Form.SystemInformation.CaptionButtonSize
System.Windows.Forms.Form.SystemInformation.CaptionHeight
System.Windows.Forms.Form.HelpButton
System.Windows.Forms.Form.MaximizeBox
System.Windows.Forms.Form.MinimizeBox
GetTopWindow Retrieves a handle to the child window at the top of the Z order. System.Windows.Forms.Form.Controls[0]
GetWindow Retrieves a handle to a window that has the specified relationship to the specified window. System.Windows.Forms.Form.Controls
GetWindowInfo Retrieves information about the specified window. System.Windows.Forms.Form.ClientSize
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form.Name
System.Windows.Forms.Form.ProductVersion
System.Windows.Forms.Form.Size
System.Windows.Forms.SystemInformation.BorderSize
GetWindowPlacement Retrieves the show state and the restored, minimized, and maximized positions of the specified window. System.Windows.Forms.Form.Bounds
System.Windows.Forms.Form.MaximizedBounds
System.Windows.Forms.Form.Visible
System.Windows.Forms.Form.WindowState
GetWindowRect Retrieves the dimensions of the bounding rectangle of the specified window. System.Windows.Forms.Form.Bounds
GetWindowText Copies the text of the title bar of the specified window. System.Windows.Forms.Form.Text
GetWindowTextLength Retrieves the length of the title bar text for the specified window. System.Windows.Forms.Form.Text.Length
IsChild Tests whether a window is a child window or descendant window of a specified parent window. System.Windows.Forms.Form.Contains
System.Windows.Forms.Form.IsMdiChild
IsIconic Determines whether the specified window is minimized (iconic). System.Windows.Forms.Form.WindowState
IsWindowVisible Retrieves the visibility state of the specified window. System.Windows.Forms.Form.Visible
IsZoomed Determines whether a window is maximized (zoomed). System.Windows.Forms.Form.WindowState
MoveWindow Changes the position and dimensions of the specified window. System.Windows.Forms.Form.SetBounds
OpenIcon Restores a minimized (iconic) window to its previous size and position. System.Windows.Forms.Form.WindowState = System.Windows.Forms.FormWindowState.Normal
SetForegroundWindow Puts the thread that created the specified window into the foreground and activates the window. System.Windows.Forms.Form.Activate
SetLayeredWindowAttributes Sets the opacity and transparency color key of a layered window. System.Windows.Forms.Form.Opacity
System.Windows.Forms.Form.TransparencyKey
SetParent Changes the parent window of the specified child window. System.Windows.Forms.Form.Parent
SetWindowPlacement Sets the show state and the restored, minimized, and maximized positions of the specified window. System.Windows.Forms.Form.Bounds
System.Windows.Forms.Form.MaximizedBounds
System.Windows.Forms.Form.SetBounds
System.Windows.Forms.Form.Visible
System.Windows.Forms.Form.WindowState
SetWindowPos Changes the size, position, and Z order of a window. System.Windows.Forms.Form.BringToFront
System.Windows.Forms.Form.Enabled
System.Windows.Forms.Form.SendToBack
System.Windows.Forms.Form.SetBounds
System.Windows.Forms.Form.TopMost
System.Windows.Forms.Form.Visible
SetWindowText Changes the text of the title bar for the specified window. System.Windows.Forms.Form.Text
ShowWindow Sets the show state of the specified window. System.Windows.Forms.Form.Show
System.Windows.Forms.Form.Visible
System.Windows.Forms.Form.WindowState
TileWindows Tiles the specified child windows of the specified parent window. System.Windows.Forms.Form.LayoutMdi(MdiLayout.TileHorizontal)
System.Windows.Forms.Form.LayoutMdi(MdiLayout.TileVertical)
WindowFromPoint Retrieves a handle to the window that contains the specified point. System.Windows.Forms.Form.GetChildAtPoint

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Class Functions

Win32 function Description .NET Framework API
GetClassInfo Retrieves information about a window class. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
GetClassLong Retrieves the specified 32-bit value from the WNDCLASSEX structure associated with the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
GetClassLongPtr Retrieves the specified value from the WNDCLASSEX structure associated with the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
GetClassName Retrieves the name of the class to which the specified window belongs. System.Windows.Forms.Control.Name
GetWindowLong Retrieves information about the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
GetWindowLongPtr Retrieves information about the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
RegisterClass Registers a window class. System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
System.Windows.Forms.Form events
SetClassLong Replaces the specified 32-bit value at the specified offset into the extra class memory or the WNDCLASSEX structure. System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
System.Windows.Forms.Form events
SetClassLongPtr Replaces the specified value at the specified offset into the extra class memory or the WNDCLASSEX structure. System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
System.Windows.Forms.Form events
SetWindowLong Changes an attribute of the specified window. System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
System.Windows.Forms.Form events
SetWindowLongPtr Changes an attribute of the specified window. System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
System.Windows.Forms.Form events

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Procedure Functions

Win32 function Description .NET Framework API
DefWindowProc Calls the default window procedure to provide default processing for any window messages that an application does not process. Any of the following:
System.Windows.Forms.Form.DefWndProc
System.Windows.Forms.Control.DefWndProc
System.Windows.Forms.NativeWindow.DefWndProc
WindowProc An application-defined function that processes messages sent to a window. Any of the following:
System.Windows.Forms.Form.WndProc
System.Windows.Forms.Control.WndProc
System.Windows.Forms.NativeWindow.WndProc

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Property Functions

Win32 function Description .NET Framework API
GetProp Retrieves a data handle from the property list of the specified window. System.Windows.Forms.Control.Tag
RemoveProp Removes an entry from the property list of the specified window. System.Windows.Forms.Control.Tag
SetProp Adds a new entry or changes an existing entry in the property list of the specified window.
发表在 article | 标签为 | 59条评论

linux指令大全(完整篇)

cat cd
chmod chown
cp cut

名称:cat
使用权限:所有使用者
使用方式:cat [-AbeEnstTuv] [--help] [--version] fileName
说明:把档案串连接后传到基本输出(萤幕或加 > fileName 到另一个档案)
参数:
-n 或 --number 由 1 开始对所有输出的行数编号
-b 或 --number-nonblank 和 -n 相似,只不过对于空白行不编号
-s 或 --squeeze-blank 当遇到有连续两行以上的空白行,就代换为一行的空白行
-v 或 --show-nonprinting

范例:
cat -n textfile1 > textfile2 把 textfile1 的档案内容加上行号后输入 textfile2 这个档案里
cat -b textfile1 textfile2 >> textfile3 把 textfile1 和 textfile2 的档案内容加上行号(空白行不加)之后将内容附加到 textfile3

名称 : cd
使用权限 : 所有使用者

使用方式 : cd [dirName]

说明 : 变换工作目录至 dirName。 其中 dirName 表示法可为绝对路径或相对路径。若目录名称省略,则变换至使用者的 home directory (也就是刚 login 时所在的目录)。

另外,"~" 也表示为 home directory 的意思,"." 则是表示目前所在的目录,".." 则表示目前目录位置的上一层目录。

范例 : 跳到 /usr/bin/ :
cd /usr/bin

跳到自己的 home directory :
cd ~

跳到目前目录的上上两层 :
cd ../..

指令名称 : chmod
使用权限 : 所有使用者

使用方式 : chmod [-cfvR] [--help] [--version] mode file...

说明 : Linux/Unix 的档案存取权限分为三级 : 档案拥有者、群组、其他。利用 chmod 可以藉以控制档案如何被他人所存取。

把计 :

mode : 权限设定字串,格式如下 : [ugoa...][[+-=][rwxX]...][,...],其中u 表示该档案的拥有者,g 表示与该档案的拥有者属于同一个群体(group)者,o 表示其他以外的人,a 表示这三者皆是。
+ 表示增加权限、- 表示取消权限、= 表示唯一设定权限。
r 表示可读取,w 表示可写入,x 表示可执行,X 表示只有当该档案是个子目录或者该档案已经被设定过为可执行。
-c : 若该档案权限确实已经更改,才显示其更改动作
-f : 若该档案权限无法被更改也不要显示错误讯息
-v : 显示权限变更的详细资料
-R : 对目前目录下的所有档案与子目录进行相同的权限变更(即以递回的方式逐个变更)
--help : 显示辅助说明
--version : 显示版本

范例 :将档案 file1.txt 设为所有人皆可读取 :
chmod ugo+r file1.txt

将档案 file1.txt 设为所有人皆可读取 :
chmod a+r file1.txt

将档案 file1.txt 与 file2.txt 设为该档案拥有者,与其所属同一个群体者可写入,但其他以外的人则不可写入 :
chmod ug+w,o-w file1.txt file2.txt

将 ex1.py 设定为只有该档案拥有者可以执行 :
chmod u+x ex1.py

将目前目录下的所有档案与子目录皆设为任何人可读取 :
chmod -R a+r *

此外chmod也可以用数字来表示权限如 chmod 777 file
语法为:chmod abc file

其中a,b,c各为一个数字,分别表示User、Group、及Other的权限。

r=4,w=2,x=1
若要rwx属性则4+2+1=7;
若要rw-属性则4+2=6;
若要r-x属性则4+1=7。

范例:
chmod a=rwx file


chmod 777 file

效果相同
chmod ug=rwx,o=x file


chmod 771 file

效果相同

若用chmod 4755 filename可使此程式具有root的权限

指令名称 : chown
使用权限 : root

使用方式 : chmod [-cfhvR] [--help] [--version] user[:group] file...

说明 : Linux/Unix 是多人多工作业系统,所有的档案皆有拥有者。利用 chown 可以将档案的拥有者加以改变。一般来说,这个指令只有是由系统管理者(root)所使用,一般使用者没有权限可以改变别人的档案拥有者,也没有权限可以自己的档案拥有者改设为别人。只有系统管理者(root)才有这样的权限。

把计 :

user : 新的档案拥有者的使用者 IDgroup : 新的档案拥有者的使用者群体(group)-c : 若该档案拥有者确实已经更改,才显示其更改动作-f : 若该档案拥有者无法被更改也不要显示错误讯息-h : 只对于连结(link)进行变更,而非该 link 真正指向的档案-v : 显示拥有者变更的详细资料-R : 对目前目录下的所有档案与子目录进行相同的拥有者变更(即以递回的方式逐个变更)--help : 显示辅助说明--version : 显示版本

范例 :
将档案 file1.txt 的拥有者设为 users 群体的使用者 jessie :
chown jessie:users file1.txt

将目前目录下的所有档案与子目录的拥有者皆设为 users 群体的使用者 lamport :
chmod -R lamport:users *

名称:cp
使用权限:所有使用者

使用方式:

cp [options] source dest
cp [options] source... directory

说明:将一个档案拷贝至另一档案,或将数个档案拷贝至另一目录。

把计

-a 尽可能将档案状态、权限等资料都照原状予以复制。
-r 若 source 中含有目录名,则将目录下之档案亦皆依序拷贝至目的地。
-f 若目的地已经有相同档名的档案存在,则在复制前先予以删除再行复制。
范例:
将档案 aaa 复制(已存在),并命名为 bbb :
cp aaa bbb

将所有的C语言程式拷贝至 Finished 子目录中 :
cp *.c Finished

名称:cut

使用权限:所有使用者

用法:cut -cnum1-num2 filename

说明:显示每行从开头算起 num1 到 num2 的文字。

范例:

shell>> cat example
test2
this is test1
shell>> cut -c0-6 example ## print 开头算起前 6 个字元
test2
this i

名称 : find
用法 : find
使用说明 :

将档案系统内符合 expression 的档案列出来。你可以指要档案的名称、类别、时间、大小、权限等不同资讯的组合,只有完全相符的才会被列出来。

find 根据下列规则判断 path 和 expression,在命令列上第一个 - ( ) , ! 之前的部份为 path,之后的是 expression。如果 path 是空字串则使用目前路径,如果 expression 是空字串则使用 -print 为预设 expression

expression 中可使用的选项有二三十个之多,在此只介绍最常用的部份。

-mount, -xdev : 只检查和指定目录在同一个档案系统下的档案,避免列出其它档案系统中的档案
-amin n : 在过去 n 分钟内被读取过
-anewer file : 比档案 file 更晚被读取过的档案
-atime n : 在过去 n 天过读取过的档案
-cmin n : 在过去 n 分钟内被修改过
-cnewer file :比档案 file 更新的档案
-ctime n : 在过去 n 天过修改过的档案
-empty : 空的档案-gid n or -group name : gid 是 n 或是 group 名称是 name
-ipath p, -path p : 路径名称符合 p 的档案,ipath 会忽略大小写
-name name, -iname name : 档案名称符合 name 的档案。iname 会忽略大小写
-size n : 档案大小 是 n 单位,b 代表 512 位元组的区块,c 表示字元数,k 表示 kilo bytes,w 是二个位元组。-type c : 档案类型是 c 的档案。
d: 目录
c: 字型装置档案
b: 区块装置档案
p: 具名贮列
f: 一般档案
l: 符号连结
s: socket
-pid n : process id 是 n 的档案

你可以使用 ( ) 将运算式分隔,并使用下列运算。
exp1 -and exp2
! expr
-not expr
exp1 -or exp2
exp1, exp2
范例:
将目前目录及其子目录下所有延伸档名是 c 的档案列出来。
# find . -name "*.c"

将目前目录其其下子目录中所有一般档案列出
# find . -ftype f

将目前目录及其子目录下所有最近 20 分钟内更新过的档案列出
# find . -ctime -20

名称:less

使用权限:所有使用者

使用方式:

less [Option] filename

说明:
less 的作用与 more 十分相似,都可以用来浏览文字档案的内容,不同的是 less 允许使用者往回卷动
以浏览已经看过的部份,同时因为 less 并未在一开始就读入整个档案,因此在遇上大型档案的开启时,会比一般的文书编辑器(如 vi)来的快速。

范例:

指令名称 : ln
使用权限 : 所有使用者

使用方式 : ln [options] source dist,其中 option 的格式为 :

[-bdfinsvF] [-S backup-suffix] [-V {numbered,existing,simple}]
[--help] [--version] [--]
说明 : Linux/Unix 档案系统中,有所谓的连结(link),我们可以将其视为档案的别名,而连结又可分为两种 : 硬连结(hard link)与软连结(symbolic link),硬连结的意思是一个档案可以有多个名称,而软连结的方式则是产生一个特殊的档案,该档案的内容是指向另一个档案的位置。硬连结是存在同一个档案系统中,而软连结却可以跨越不同的档案系统。
ln source dist 是产生一个连结(dist)到 source,至于使用硬连结或软链结则由参数决定。

不论是硬连结或软链结都不会将原本的档案复制一份,只会占用非常少量的磁碟空间。

-f : 链结时先将与 dist 同档名的档案删除-d : 允许系统管理者硬链结自己的目录-i : 在删除与 dist 同档名的档案时先进行询问-n : 在进行软连结时,将 dist 视为一般的档案-s : 进行软链结(symbolic link)-v : 在连结之前显示其档名-b : 将在链结时会被覆写或删除的档案进行备份-S SUFFIX : 将备份的档案都加上 SUFFIX 的字尾-V METHOD : 指定备份的方式--help : 显示辅助说明--version : 显示版本
范例 :
将档案 yy 产生一个 symbolic link : zz
ln -s yy zz

将档案 yy 产生一个 hard link : zz
ln yy xx

名称:locate
使用权限:所有使用者
使用方式: locate [-q] [-d ] [--database=]
locate [-r ] [--regexp=]
locate [-qv] [-o ] [--output=]
locate [-e ] [-f ] <[-l ] [-c]
<[-U ] [-u]>
locate [-Vh] [--version] [--help]
说明:
locate 让使用者可以很快速的搜寻档案系统内是否有指定的档案。其方法是先建立一个包括系统内所有档案名称及路径的资料库,之后当寻找时就只需查询这个资料库,而不必实际深入档案系统之中了。

在一般的 distribution 之中,资料库的建立都被放在 contab 中自动执行。一般使用者在使用时只要用

# locate your_file_name

的型式就可以了。 参数:
-u
-U

建立资料库,-u 会由根目录开始,-U 则可以指定开始的位置。

-e


排除在寻找的范围之外。

-l
如果 是 1.则启动安全模式。在安全模式下,使用者不会看到权限无法看到的档案。这会始速度减慢,因为 locate 必须至实际的档案系统中取得档案的权限资料。

-f
将特定的档案系统排除在外,例如我们没有到理要把 proc 档案系统中的档案放在资料库中。

-q
安静模式,不会显示任何错误讯息。

-n
至多显示 个输出。

-r
使用正规运算式 做寻找的条件。

-o
指定资料库存的名称。

-d

指定资料库的路径

-h
显示辅助讯息

-v
显示更多的讯息

-V
显示程式的版本讯息 范例:

locate chdrv : 寻找所有叫 chdrv 的档案
locate -n 100 a.out : 寻找所有叫 a.out 的档案,但最多只显示 100 个
locate -u : 建立资料库

名称 : ls
使用权限 : 所有使用者

使用方式 : ls [-alrtAFR] [name...]

说明 : 显示指定工作目录下之内容(列出目前工作目录所含之档案及子目录)。-a 显示所有档案及目录 (ls内定将档案名或目录名称开头为"."的视为隐藏档,不会列出)
-l 除档案名称外,亦将档案型态、权限、拥有者、档案大小等资讯详细列出
-r 将档案以相反次序显示(原定依英文字母次序)
-t 将档案依建立时间之先后次序列出
-A 同 -a ,但不列出 "." (目前目录) 及 ".." (父目录)
-F 在列出的档案名称后加一符号;例如可执行档则加 "*", 目录则加 "/"
-R 若目录下有档案,则以下之档案亦皆依序列出

范例:
列出目前工作目录下所有名称是 s 开头的档案,愈新的排愈后面 :
ls -ltr s*

将 /bin 目录以下所有目录及档案详细资料列出 :
ls -lR /bin

列出目前工作目录下所有档案及目录;目录于名称后加 "/", 可执行档于名称后加 "*" :
ls -AF

名称:more
使用权限:所有使用者
使用方式:more [-dlfpcsu] [-num] [+/pattern] [+linenum] [fileNames..]
说明:类似 cat ,不过会以一页一页的显示方便使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就会往回(back)一页显示,而且还有搜寻字串的功能(与 vi 相似),使用中的说明文件,请按 h 。
参数:-num 一次显示的行数
-d 提示使用者,在画面下方显示 [Press space to continue, q to quit.] ,如果使用者按错键,则会显示 [Press h for instructions.] 而不是 哔 声
-l 取消遇见特殊字元 ^L(送纸字元)时会暂停的功能
-f 计算行数时,以实际上的行数,而非自动换行过后的行数(有些单行字数太长的会被扩展为两行或两行以上)
-p 不以卷动的方式显示每一页,而是先清除萤幕后再显示内容
-c 跟 -p 相似,不同的是先显示内容再清除其他旧资料
-s 当遇到有连续两行以上的空白行,就代换为一行的空白行
-u 不显示下引号 (根据环境变数 TERM 指定的 terminal 而有所不同)
+/ 在每个档案显示前搜寻该字串(pattern),然后从该字串之后开始显示
+num 从第 num 行开始显示
fileNames 欲显示内容的档案,可为复数个数
范例:
more -s testfile 逐页显示 testfile 之档案内容,如有连续两行以上空白行则以一行空白行显示。
more +20 testfile 从第 20 行开始显示 testfile 之档案内容。

名称:mv
使用权限:所有使用者

使用方式:

mv [options] source dest
mv [options] source... directory
说明:将一个档案移至另一档案,或将数个档案移至另一目录。
参数:-i 若目的地已有同名档案,则先询问是否覆盖旧档。

范例:

将档案 aaa 更名为 bbb :
mv aaa bbb

将所有的C语言程式移至 Finished 子目录中 :
mv -i *.c

名称:rm
使用权限:所有使用者

使用方式:rm [options] name...

说明:删除档案及目录。

把计

-i 删除前逐一询问确认。
-f 即使原档案属性设为唯读,亦直接删除,无需逐一确认。
-r 将目录及以下之档案亦逐一删除。
范例:
删除所有C语言程式档;删除前逐一询问确认 :
rm -i *.c

将 Finished 子目录及子目录中所有档案删除 :
rm -r Finished

名称:rmdir
使用权限:于目前目录有适当权限的所有使用者

使用方式: rmdir [-p] dirName

说明: 删除空的目录。

参数: -p 是当子目录被删除后使它也成为空目录的话,则顺便一并删除。

范例:

将工作目录下,名为 AAA 的子目录删除 :
rmdir AAA

在工作目录下的 BBB 目录中,删除名为 Test 的子目录。若 Test 删除后,BBB 目录成为空目录,则 BBB 亦予删除。
rmdir -p BBB/Test

名称:split
使用权限:所有使用者

使用方式:split [OPTION] [INPUT [PREFIX]]

说明:

将一个档案分割成数个。而从 INPUT 分割输出成固定大小的档案,其档名依序为 PREFIXaa, PREFIXab...;PREFIX 预设值为 `x。若没有 INPUT 档或为 `-,则从标准输入读进资料。

匡兜

-b, --bytes=SIZE

SIZE 值为每一输出档案的大小,单位为 byte。
-C, --line-bytes=SIZE

每一输出档中,单行的最大 byte 数。
-l, --lines=NUMBER

NUMBER 值为每一输出档的列数大小。
-NUMBER

与 -l NUMBER 相同。
--verbose

于每个输出档被开启前,列印出侦错资讯到标准错误输出。
--help

显示辅助资讯然后离开。
--version

列出版本资讯然后离开。
SIZE 可加入单位: b 代表 512, k 代表 1K, m 代表 1 Meg。

范例:

PostgresSQL 大型资料库备份与回存:

因 Postgres 允许表格大过你系统档案的最大容量,所以要将表格 dump 到单一的档案可能会有问题,使用 split进行档案分割。

% pg_dump dbname | split -b 1m - filename.dump.

重新载入

% createdb dbname
% cat filename.dump.* | pgsql dbname

名称:touch
使用权限:所有使用者

使用方式:
touch [-acfm]
[-r reference-file] [--file=reference-file]
[-t MMDDhhmm[[CC]YY][.ss]]
[-d time] [--date=time] [--time={atime,access,use,mtime,modify}]
[--no-create] [--help] [--version]
file1 [file2 ...]

说明:
touch 指令改变档案的时间记录。 ls -l 可以显示档案的时间记录。

参数:
a 改变档案的读取时间记录。
m 改变档案的修改时间记录。
c 假如目的档案不存在,不会建立新的档案。与 --no-create 的效果一样。
f 不使用,是为了与其他 unix 系统的相容性而保留。
r 使用参考档的时间记录,与 --file 的效果一样。
d 设定时间与日期,可以使用各种不同的格式。
t 设定档案的时间记录,格式与 date 指令相同。
--no-create 不会建立新档案。
--help 列出指令格式。
--version 列出版本讯息。

范例:

最简单的使用方式,将档案的时候记录改为现在的时间。若档案不存在,系统会建立一个新的档案。

touch file
touch file1 file2

将 file 的时间记录改为 5 月 6 日 18 点 3 分,公元两千年。时间的格式可以参考 date 指令,至少需输入 MMDDHHmm ,就是月日时与分。

touch -c -t 05061803 file
touch -c -t 050618032000 file

将 file 的时间记录改变成与 referencefile 一样。

touch -r referencefile file

将 file 的时间记录改成 5 月 6 日 18 点 3 分,公元两千年。时间可以使用 am, pm 或是 24 小时的格式,日期可以使用其他格式如 6 May 2000 。

touch -d "6:03pm" file
touch -d "05/06/2000" file
touch -d "6:03pm 05/06/2000" file
名称 : at
使用权限 : 所有使用者

使用方式 : at -V [-q queue] [-f file] [-mldbv] TIME

说明 : at 可以让使用者指定在 TIME 这个特定时刻执行某个程式或指令,TIME 的格式是 HH:MM其中的 HH 为小时,MM 为分钟,甚至你也可以指定 am, pm, midnight, noon, teatime(就是下午 4 点锺)等口语词。

如果想要指定超过一天内的时间,则可以用 MMDDYY 或者 MM/DD/YY 的格式,其中 MM 是分钟,DD 是第几日,YY 是指年份。另外,使用者甚至也可以使用像是 now + 时间间隔来弹性指定时间,其中的时间间隔可以是 minutes, hours, days, weeks

另外,使用者也可指定 today 或 tomorrow 来表示今天或明天。当指定了时间并按下 enter 之后,at 会进入交谈模式并要求输入指令或程式,当你输入完后按下 ctrl+D 即可完成所有动作,至于执行的结果将会寄回你的帐号中。

把计 :

-V : 印出版本编号
-q : 使用指定的伫列(Queue)来储存,at 的资料是存放在所谓的 queue 中,使用者可以同时使用多个 queue,而 queue 的编号为 a, b, c... z 以及 A, B, ... Z 共 52 个
-m : 即使程式/指令执行完成后没有输出结果, 也要寄封信给使用者
-f file : 读入预先写好的命令档。使用者不一定要使用交谈模式来输入,可以先将所有的指定先写入档案后再一次读入
-l : 列出所有的指定 (使用者也可以直接使用 atq 而不用 at -l)
-d : 删除指定 (使用者也可以直接使用 atrm 而不用 at -d)
-v : 列出所有已经完成但尚未删除的指定

例子 :
三天后的下午 5 点锺执行 /bin/ls :
at 5pm + 3 days /bin/ls

三个星期后的下午 5 点锺执行 /bin/ls :
at 5pm + 2 weeks /bin/ls

明天的 17:20 执行 /bin/date :
at 17:20 tomorrow /bin/date

1999 年的最后一天的最后一分钟印出 the end of world !
at 23:59 12/31/1999 echo the end of world !

名称:cal

使用权限:所有使用者

使用方式:cal [-mjy] [month [year]]

说明:

显示日历。若只有一个参数,则代表年份(1-9999),显示该年的年历。年份必须全部写出:``cal 89 将不会是显示 1989 年的年历。使用两个参数,则表示月份及年份。若没有参数则显示这个月的月历。
1752 年 9 月第 3 日起改用西洋新历,因这时大部份的国家都采用新历,有 10 天被去除,所以该月份的月历有些不同。在此之前为西洋旧历。

匡兜

-m : 以星期一为每周的第一天方式显示。
-j : 以凯撒历显示,即以一月一日起的天数显示。
-y : 显示今年年历。

范例:

cal : 显示本月的月历。

[root@mylinux /root]# date
Tue Aug 15 08:00:18 CST 2000
[root@mylinux /root]# cal
August 2000
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

[root@mylinux /root]#

cal 2001 : 显示公元 2001 年年历。

[root@mylinux /root]# cal 2001
2001

January February March
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 1 2 3 1 2 3
7 8 9 10 11 12 13 4 5 6 7 8 9 10 4 5 6 7 8 9 10
14 15 16 17 18 19 20 11 12 13 14 15 16 17 11 12 13 14 15 16 17
21 22 23 24 25 26 27 18 19 20 21 22 23 24 18 19 20 21 22 23 24
28 29 30 31 25 26 27 28 25 26 27 28 29 30 31

April May June
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7 1 2 3 4 5 1 2
8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9
15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16
22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23
29 30 27 28 29 30 31 24 25 26 27 28 29 30

July August September
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7 1 2 3 4 1
8 9 10 11 12 13 14 5 6 7 8 9 10 11 2 3 4 5 6 7 8
15 16 17 18 19 20 21 12 13 14 15 16 17 18 9 10 11 12 13 14 15
22 23 24 25 26 27 28 19 20 21 22 23 24 25 16 17 18 19 20 21 22
29 30 31 26 27 28 29 30 31 23 24 25 26 27 28 29
30
October November December
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 1 2 3 1
7 8 9 10 11 12 13 4 5 6 7 8 9 10 2 3 4 5 6 7 8
14 15 16 17 18 19 20 11 12 13 14 15 16 17 9 10 11 12 13 14 15
21 22 23 24 25 26 27 18 19 20 21 22 23 24 16 17 18 19 20 21 22
28 29 30 31 25 26 27 28 29 30 23 24 25 26 27 28 29
30 31

[root@mylinux /root]#

cal 5 2001 : 显示公元 2001 年 5 月月历。

[root@mylinux /root]# cal 5 2001
May 2001
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

[root@mylinux /root]#

cal -m : 以星期一为每周的第一天方式,显示本月的月历。

[root@mylinux /root]# cal -m
August 2000
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

[root@mylinux /root]#

cal -jy : 以一月一日起的天数显示今年的年历。

[root@mylinux /root]# cal -jy
2000

January February
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
1 32 33 34 35 36
2 3 4 5 6 7 8 37 38 39 40 41 42 43
9 10 11 12 13 14 15 44 45 46 47 48 49 50
16 17 18 19 20 21 22 51 52 53 54 55 56 57
23 24 25 26 27 28 29 58 59 60
30 31
March April
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
61 62 63 64 92
65 66 67 68 69 70 71 93 94 95 96 97 98 99
72 73 74 75 76 77 78 100 101 102 103 104 105 106
79 80 81 82 83 84 85 107 108 109 110 111 112 113
86 87 88 89 90 91 114 115 116 117 118 119 120
121
May June
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
122 123 124 125 126 127 153 154 155
128 129 130 131 132 133 134 156 157 158 159 160 161 162
135 136 137 138 139 140 141 163 164 165 166 167 168 169
142 143 144 145 146 147 148 170 171 172 173 174 175 176
149 150 151 152 177 178 179 180 181 182

July August
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
183 214 215 216 217 218
184 185 186 187 188 189 190 219 220 221 222 223 224 225
191 192 193 194 195 196 197 226 227 228 229 230 231 232
198 199 200 201 202 203 204 233 234 235 236 237 238 239
205 206 207 208 209 210 211 240 241 242 243 244
212 213
September October
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
245 246 275 276 277 278 279 280 281
247 248 249 250 251 252 253 282 283 284 285 286 287 288
254 255 256 257 258 259 260 289 290 291 292 293 294 295
261 262 263 264 265 266 267 296 297 298 299 300 301 302
268 269 270 271 272 273 274 303 304 305

November December
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
306 307 308 309 336 337
310 311 312 313 314 315 316 338 339 340 341 342 343 344
317 318 319 320 321 322 323 345 346 347 348 349 350 351
324 325 326 327 328 329 330 352 353 354 355 356 357 358
331 332 333 334 335 359 360 361 362 363 364 365
366

[root@mylinux /root]#

名称 : crontab
使用权限 : 所有使用者

使用方式 :

crontab [ -u user ] filecrontab [ -u user ] { -l | -r | -e }
说明 :
crontab 是用来让使用者在固定时间或固定间隔执行程式之用,换句话说,也就是类似使用者的时程表。-u user 是指设定指定 user 的时程表,这个前提是你必须要有其权限(比如说是 root)才能够指定他人的时程表。如果不使用 -u user 的话,就是表示设定自己的时程表。

餐数 :

-e : 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
-r : 删除目前的时程表
-l : 列出目前的时程表

时程表的格式如下 :
f1 f2 f3 f4 f5 program

其中 f1 是表示分钟,f2 表示小时,f3 表示一个月份中的第几日,f4 表示月份,f5 表示一个星期中的第几天。program 表示要执行的程式。
当 f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程式,其余类推
当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,f2 为 a-b 时表示从第 a 到第 b 小时都要执行,其余类推
当 f1 为 */n 时表示每 n 分钟个时间间隔执行一次,f2 为 */n 表示每 n 小时个时间间隔执行一次,其余类推
当 f1 为 a, b, c,... 时表示第 a, b, c,... 分钟要执行,f2 为 a, b, c,... 时表示第 a, b, c...个小时要执行,其余类推

使用者也可以将所有的设定先存放在档案 file 中,用 crontab file 的方式来设定时程表。
例子 :

每月每天每小时的第 0 分钟执行一次 /bin/ls :
0 7 * * * /bin/ls

在 12 月内, 每天的早上 6 点到 12 点中,每隔 20 分钟执行一次 /usr/bin/backup :
0 6-12/3 * 12 * /usr/bin/backup

周一到周五每天下午 5:00 寄一封信给 alex@domain.name :
0 17 * * 1-5 mail -s "hi" alex@domain.name < /tmp/maildata

每月每天的午夜 0 点 20 分, 2 点 20 分, 4 点 20 分....执行 echo "haha"
20 0-23/2 * * * echo "haha"

注意 :

当程式在你所指定的时间执行后,系统会寄一封信给你,显示该程式执行的内容,若是你不希望收到这样的信,请在每一行空一格之后加上 > /dev/null 2>&1 即可。

名称 : date
使用权限 : 所有使用者

使用方式 :

date [-u] [-d datestr] [-s datestr] [--utc] [--universal] [--date=datestr] [--set=datestr] [--help] [--version] [+FORMAT] [MMDDhhmm[[CC]YY][.ss]]

说明 :

date 可以用来显示或设定系统的日期与时间,在显示方面,使用者可以设定欲显示的格式,格式设定为一个加号后接数个标记,其中可用的标记列表如下 :

时间方面 :

% : 印出 %
%n : 下一行
%t : 跳格
%H : 小时(00..23)
%I : 小时(01..12)
%k : 小时(0..23)
%l : 小时(1..12)
%M : 分钟(00..59)
%p : 显示本地 AM 或 PM
%r : 直接显示时间 (12 小时制,格式为 hh:mm:ss [AP]M)
%s : 从 1970 年 1 月 1 日 00:00:00 UTC 到目前为止的秒数
%S : 秒(00..61)
%T : 直接显示时间 (24 小时制)
%X : 相当于 %H:%M:%S
%Z : 显示时区

日期方面 :
%a : 星期几 (Sun..Sat)
%A : 星期几 (Sunday..Saturday)
%b : 月份 (Jan..Dec)
%B : 月份 (January..December)
%c : 直接显示日期与时间
%d : 日 (01..31)
%D : 直接显示日期 (mm/dd/yy)
%h : 同 %b
%j : 一年中的第几天 (001..366)
%m : 月份 (01..12)
%U : 一年中的第几周 (00..53) (以 Sunday 为一周的第一天的情形)
%w : 一周中的第几天 (0..6)
%W : 一年中的第几周 (00..53) (以 Monday 为一周的第一天的情形)
%x : 直接显示日期 (mm/dd/yy)
%y : 年份的最后两位数字 (00.99)
%Y : 完整年份 (0000..9999)

若是不以加号作为开头,则表示要设定时间,而时间格式为 MMDDhhmm[[CC]YY][.ss],其中 MM 为月份,DD 为日,hh 为小时,mm 为分钟,CC 为年份前两位数字,YY 为年份后两位数字,ss 为秒数
把计 :

-d datestr : 显示 datestr 中所设定的时间 (非系统时间)
--help : 显示辅助讯息
-s datestr : 将系统时间设为 datestr 中所设定的时间
-u : 显示目前的格林威治时间
--version : 显示版本编号

例子 :
显示时间后跳行,再显示目前日期 :
date +%T%n%D

显示月份与日数 :
date +%B %d

显示日期与设定时间(12:34:56) :
date --date 12:34:56

注意 :

当你不希望出现无意义的 0 时(比如说 1999/03/07),则可以在标记中插入 - 符号,比如说 date +%-H:%-M:%-S 会把时分秒中无意义的 0 给去掉,像是原本的 08:09:04 会变为 8:9:4。另外,只有取得权限者(比如说 root)才能设定系统时间。

当你以 root 身分更改了系统时间之后,请记得以 clock -w 来将系统时间写入 CMOS 中,这样下次重新开机时系统时间才会持续抱持最新的正确值。

名称 : sleep
使用权限 : 所有使用者

使用方式 : sleep [--help] [--version] number[smhd]

说明 : sleep 可以用来将目前动作延迟一段时间

参数说明 :

--help : 显示辅助讯息
--version : 显示版本编号
number : 时间长度,后面可接 s、m、h 或 d
其中 s 为秒,m 为 分钟,h 为小时,d 为日数

例子 :
显示目前时间后延迟 1 分钟,之后再次显示时间 :
date;sleep 1m;date

名称: time
使用权限: 所有使用者

使用方式: time [options] COMMAND [arguments]

说明: time 指令的用途,在于量测特定指令执行时所需消耗的时间及系统资源等资讯。例如 CPU 时间、记忆体、输入输出等等。需要特别注意的是,部分资讯在 Linux 上显示不出来。这是因为在 Linux 上部分资源的分配函式与 time 指令所预设的方式并不相同,以致于 time 指令无法取得这些资料。

把计

-o or --output=FILE
设定结果输出档。这个选项会将 time 的输出写入 所指定的档案中。如果档案已经存在,系统将覆写其内容。
-a or --append
配合 -o 使用,会将结果写到档案的末端,而不会覆盖掉原来的内容。
-f FORMAT or --format=FORMAT
以 FORMAT 字串设定显示方式。当这个选项没有被设定的时候,会用系统预设的格式。不过你可以用环境变数 time 来设定这个格式,如此一来就不必每次登入系统都要设定一次。
一般设定上,你可以用
t
表示跳栏,或者是用
n
表示换行。每一项资料要用 % 做为前导。如果要在字串中使用百分比符号,就用 。(学过 C 语言的人大概会觉得很熟悉)
time 指令可以显示的资源有四大项,分别是:

Time resources
Memory resources
IO resources
Command info

详细的内容如下:

Time Resources
E 执行指令所花费的时间,格式是:[hour]:minute:second。请注意这个数字并不代表实际的 CPU 时间。
e 执行指令所花费的时间,单位是秒。请注意这个数字并不代表实际的 CPU 时间。
S 指令执行时在核心模式(kernel mode)所花费的时间,单位是秒。
U 指令执行时在使用者模式(user mode)所花费的时间,单位是秒。
P 执行指令时 CPU 的占用比例。其实这个数字就是核心模式加上使用者模式的 CPU 时间除以总时间。

Memory Resources
M 执行时所占用的实体记忆体的最大值。单位是 KB
t 执行时所占用的实体记忆体的平均值,单位是 KB
K 执行程序所占用的记忆体总量(stack+data+text)的平均大小,单位是 KB
D 执行程序的自有资料区(unshared data area)的平均大小,单位是 KB
p 执行程序的自有堆叠(unshared stack)的平均大小,单位是 KB
X 执行程序间共享内容(shared text)的平均值,单位是 KB
Z 系统记忆体页的大小,单位是 byte。对同一个系统来说这是个常数

IO Resources
F 此程序的主要记忆体页错误发生次数。所谓的主要记忆体页错误是指某一记忆体页已经置换到置换档(swap file)中,而且已经分配给其他程序。此时该页的内容必须从置换档里再读出来。
R 此程序的次要记忆体页错误发生次数。所谓的次要记忆体页错误是指某一记忆体页虽然已经置换到置换档中,但尚未分配给其他程序。此时该页的内容并未被破坏,不必从置换档里读出来
W 此程序被交换到置换档的次数
c 此程序被强迫中断(像是分配到的 CPU 时间耗尽)的次数
w 此程序自愿中断(像是在等待某一个 I/O 执行完毕,像是磁碟读取等等)的次数
I 此程序所输入的档案数
O 此程序所输出的档案数
r 此程序所收到的 Socket Message
s 此程序所送出的 Socket Message
k 此程序所收到的信号 ( Signal )数量

Command Info
C 执行时的参数以及指令名称
x 指令的结束代码 ( Exit Status )

-p or --portability
这个选项会自动把显示格式设定成为:
real %e
user %U
sys %S
这么做的目的是为了与 POSIX 规格相容。
-v or --verbose
这个选项会把所有程式中用到的资源通通列出来,不但如一般英文语句,还有说明。对不想花时间去熟习格式设定或是刚刚开始接触这个指令的人相当有用。

范例:
利用下面的指令
time -v ps -aux

我们可以获得执行 ps -aux 的结果和所花费的系统资源。如下面所列的资料:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.4 1096 472 ? S Apr19 0:04 init
root 2 0.0 0.0 0 0 ? SW Apr19 0:00 [kflushd]
root 3 0.0 0.0 0 0 ? SW Apr19 0:00 [kpiod]
......
root 24269 0.0 1.0 2692 996 pts/3 R 12:16 0:00 ps -aux

Command being timed: "ps -aux"
User time (seconds): 0.05
System time (seconds): 0.06
Percent of CPU this job got: 68%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.16
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 238
Minor (reclaiming a frame) page faults: 46
Voluntary context switches: 0
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0

名称: uptime
使用权限: 所有使用者
使用方式: uptime [-V]
说明: uptime 提供使用者下面的资讯,不需其他参数:

现在的时间
系统开机运转到现在经过的时间
连线的使用者数量
最近一分钟,五分钟和十五分钟的系统负载
参数: -V 显示版本资讯。
范例: uptime
其结果为:
10:41am up 5 days, 10 min, 1 users, load average: 0.00, 0.00, 1.99

名称:chfn

使用权限:所有使用者

用法:shell>> chfn

说明:提供使用者更改个人资讯,用于 finger and mail username

范例:

shell>> chfn
Changing finger information for user
Password: [del]
Name[]:Johnney Huang ### 提供 finger 时的资料
Office[]:NCCU
Office Phone[]: [del]
Home Phone[]: [del]

名称:chsh

使用权限:所有使用者

用法:shell>> chsh

说明:更改使用者 shell 设定

范例:

shell>> chsh
Changing fihanging shell for user1
Password: [del]
New shell [/bin/tcsh]: ### [是目前使用的 shell]
[del]

shell>> chsh -l ### 展示 /etc/shells 档案内容
/bin/bash
/bin/sh
/bin/ash
/bin/bsh
/bin/tcsh
/bin/csh

” finger [返回]
名称: finger
使用权限: 所有使用者

使用方式: finger [options] user[@address]

说明:finger 可以让使用者查询一些其他使用者的资料。会列出来的资料有:

Login Name
User Name
Home directory
Shell
Login status
mail status
.plan
.project
.forward

其中 .plan ,.project 和 .forward 就是使用者在他的 Home Directory 里的 .plan , .project 和 .forward 等档案里的资料。如果没有就没有。finger 指令并不限定于在同一伺服器上查询,也可以寻找某一个远端伺服器上的使用者。只要给一个像是 E-mail address 一般的地址即可。
把计

-l
多行显示。

-s
单行显示。这个选项只显示登入名称,真实姓名,终端机名称,闲置时间,登入时间,办公室号码及电话号码。如果所查询的使用者是远端伺服器的使用者,这个选项无效。

范例:下列指令可以查询本机管理员的资料:
finger root

其结果如下:
Login: root Name: root
Directory: /root Shell: /bin/bash
Never logged in.
No mail.
No Plan.

名称:last

使用权限:所有使用者

使用方式:shell>> last [options]

说明:显示系统开机以来获是从每月初登入者的讯息

把计

-R 省略 hostname 的栏位
-num 展示前 num 个
username 展示 username 的登入讯息
tty 限制登入讯息包含终端机代号

范例:

shell>> last -R -2
johnney pts/1 Mon Aug 14 20:42 still logged in
johnney pts/0 Mon Aug 14 19:59 still logged in

wtmp begins Tue Aug 1 09:01:10 2000 ### /var/log/wtmp

shell>> last -2 minery
minery pts/0 140.119.217.115 Mon Aug 14 18:37 - 18:40 (00:03)
minery pts/0 140.119.217.115 Mon Aug 14 17:22 - 17:24 (00:02)

wtmp begins Tue Aug 1 09:01:10 2000

名称:login

这个命令都不会就不要干算了!呵呵我也不在这里多费笔墨耽误大家美好青春了^_^

名称:passwd

使用权限:所有使用者

使用方式:passwd [-k] [-l] [-u [-f]] [-d] [-S] [username]

说明:用来更改使用者的密码

参数:
-k

-l

-u

-f

-d 关闭使用者的密码认证功能, 使用者在登入时将可以不用输入密码, 只有具备 root 权限的使用者方可使用.

-S 显示指定使用者的密码认证种类, 只有具备 root 权限的使用者方可使用.

[username] 指定帐号名称.

名称 : who
使用权线 : 所有使用者都可使用

使用方式 : who - [husfV] [user]

说明 : 显示系统中有那些使用者正在上面,显示的资料包含了使用者 ID,使用的终端机,从那边连上来的,上线时间,呆滞时间,CPU 使用量,动作等等。

把计 :

-h : 不要显示标题列
-u : 不要显示使用者的动作/工作
-s : 使用简短的格式来显示
-f : 不要显示使用者的上线位置
-V : 显示程式版本
名称:/etc/aliases
使用权限:系统管理者
使用方式: 请用 newaliases 更新资料库
说明:
sendmail 会使用一个在 /etc/aliases 中的档案做使用者名称转换的动作。当 sendmail 收到一个要送给 xxx 的信时,它会依据 aliases档的内容送给另一个使用者。这个功能可以创造一个只有在信件系统内才有效的使用者。例如 mailing list 就会用到这个功能,在 mailinglist 中,我们可能会创造一个叫 redlinux@link.ece.uci.edu 的 mailinglist,但实际上并没有一个叫 redlinux 的使用者。实际 aliases 档的内容是将送给这个使用者的信都收给 mailing list 处理程式负责分送的工作。

/etc/aliases 是一个文字模式的档案,sendmail 需要一个二进位格式的 /etc/aliases.db。newaliases 的功能传是将 /etc/aliases 转换成一个 sendmail 所能了解的资料库。范例:
# newaliases

下面命令会做相同的事,
# sendmail -bi

相关命令:
mail, mailq, newaliases, sendmail

” mail [返回]
名称:mail

使用权限:所有使用者

使用方式:mail [-iInv] [-s subject] [-c cc-addr] [-b bcc-addr] user1 [user 2 ...]

说明:
mail 不仅只是一个指令, mail 还是一个电子邮件程式,不过利用 mail 来读信的人应该很少吧!对于系统管理者来说 mail 就很有用,因为管理者可以用 mail 写成 script ,定期寄一些备忘录提醒系统的使用者。

参数:
i 忽略 tty 的中断讯号。 (interrupt)
I 强迫设成互动模式。 (Interactive)
v 列印出讯息,例如送信的地点、状态等等。 (verbose)
n 不读入 mail.rc 设定档。
s 邮件标题。
c cc 邮件地址。
b bcc 邮件地址。

范例:

将信件送给一个或以上的电子邮件地址,由于没有加入其他的选项,使用者必须输入标题与信件的内容等。而 user2 没有主机位置,就会送给邮件伺服器的 user2 使用者。

mail user1@email.address
mail user1@email.address user2

将 mail.txt 的内容寄给 user2 同时 cc 给 user1 。如果将这一行指令设成 cronjob 就可以定时将备忘录寄给系统使用者。

mail -s 标题 -c user1 user2 < mail.txt

指令:mesg
使用权限 : 所有使用者

使用方式 : mesg [y|n]

说明 : 决定是否允许其他人传讯息到自己的终端机介面

把计 

y : 允许讯息传到终端机介面上。
n : 不允许讯息传到终端机介面上 。
如果没有设定,则讯息传递与否则由终端机界面目前状态而定。

例子 :
改变目前讯息设定,改成不允许讯息传到终端机介面上 :
mesg n

与 mesg 相关的指令有: talk,write,wall。

名称:/etc/aliases
使用权限:系统管理者
使用方式: newaliases
说明:
sendmail 会使用一个在 /etc/aliases 中的档案做使用者名称转换的动作。当 sendmail 收到一个要送给 xxx 的信时,它会依据 aliases档的内容送给另一个使用者。这个功能可以创造一个只有在信件系统内才有效的使用者。例如 mailing list 就会用到这个功能,在 mailinglist 中,我们可能会创造一个叫 redlinux@link.ece.uci.edu 的 mailinglist,但实际上并没有一个叫 redlinux 的使用者。实际 aliases 档的内容是将送给这个使用者的信都收给 mailing list 处理程式负责分送的工作。

/etc/aliases 是一个文字模式的档案,sendmail 需要一个二进位格式的 /etc/aliases.db。newaliases 的功能传是将 /etc/aliases 转换成一个 sendmail 所能了解的资料库。

参数:没有任何参数。 范例:
# newaliases

下面命令会做相同的事,
# sendmail -bi

相关命令:
mail, mailq, newaliases, sendmail

名称 : talk
使用权限 : 所有使用者

使用方式 :

talk person [ttyname]
说明 : 与其他使用者对谈

把计 :

person : 预备对谈的使用者帐号,如果该使用者在其他机器上,则可输入 person@machine.name
ttyname : 如果使用者同时有两个以上的 tty 连线,可以自行选择合适的 tty 传讯息

例子.1 :

与现在机器上的使用者Rollaend对谈,此时 Rollaend 只有一个连线 :
talk Rollaend

接下来就是等Rollaend回应,若Rollaend接受,则Rollaend输入 `talk jzlee`即可开始对谈,结束请按 ctrl+c

例子.2 :与linuxfab.cx上的使用者Rollaend对谈,使用pts/2来对谈 :
talk Rollaend@linuxfab.cx pts/2

接下来就是等Rollaend回应,若Rollaend接受,则Rollaend输入 `talk jzlee@jzlee.home`即可开始对谈,结束请按 ctrl+c

注意 : 若萤幕的字会出现不正常的字元,试着按 ctrl+l 更新萤幕画面。

名称 : wall
使用权限 : 所有使用者

使用方式 :

wall [ message ]
使用说明:
wall 会将讯息传给每一个 mesg 设定为 yes 的上线使用者。当使用终端机介面做为标准传入时, 讯息结束时需加上 EOF (通常用 Ctrl+D)

例子 :

传讯息"hi" 给每一个使用者 :
wall hi

名称 : write
使用权限 : 所有使用者

使用方式 :

write user [ttyname]
说明 : 传讯息给其他使用者

把计 :

user : 预备传讯息的使用者帐号
ttyname : 如果使用者同时有两个以上的 tty 连线,可以自行选择合适的 tty 传讯息

例子.1 :

传讯息给 Rollaend,此时 Rollaend 只有一个连线 :
write Rollaend

接下来就是将讯息打上去,结束请按 ctrl+c

例子.2 :传讯息给 Rollaend,Rollaend 的连线有 pts/2,pts/3 :
write Rollaend pts/2

接下来就是将讯息打上去,结束请按 ctrl+c

注意 : 若对方设定 mesg n,则此时讯席将无法传给对方

名称:kill
使用权限:所有使用者

使用方式:

kill [ -s signal | -p ] [ -a ] pid ...
kill -l [ signal ]
说明:kill 送出一个特定的信号 (signal) 给行程 id 为 pid 的行程根据该信号而做特定的动作, 若没有指定, 预设是送出终止 (TERM) 的信号
把计

-s (signal) : 其中可用的讯号有 HUP (1), KILL (9), TERM (15), 分别代表着重跑, 砍掉, 结束; 详细的信号可以用 kill -l
-p : 印出 pid , 并不送出信号
-l (signal) : 列出所有可用的信号名称
范例:

将 pid 为 323 的行程砍掉 (kill) :
kill -9 323

将 pid 为 456 的行程重跑 (restart) :
kill -HUP 456

名称:nice
使用权限:所有使用者

使用方式:nice [-n adjustment] [-adjustment] [--adjustment=adjustment] [--help] [--version] [command [arg...]]

说明:以更改过的优先序来执行程式, 如果未指定程式, 则会印出目前的排程优先序, 内定的 adjustment 为 10, 范围为 -20 (最高优先序) 到 19 (最低优先序)

把计

-n adjustment, -adjustment, --adjustment=adjustment 皆为将该原有优先序的增加 adjustment
--help 显示求助讯息
--version 显示版本资讯
范例:
将 ls 的优先序加 1 并执行 :
nice -n 1 ls

将 ls 的优先序加 10 并执行 :
nice ls将 ls 的优先序加 10 并执行

注意 : 优先序 (priority) 为作业系统用来决定 CPU 分配的参数,Linux 使用『回合制(round-robin)』的演算法来做 CPU 排程,优先序越高,所可能获得的 CPU时间就越多。

名称:ps
使用权限:所有使用者
使用方式:ps [options] [--help]
说明:显示瞬间行程 (process) 的动态
参数:
ps 的参数非常多, 在此仅列出几个常用的参数并大略介绍含义
-A 列出所有的行程
-w 显示加宽可以显示较多的资讯
-au 显示较详细的资讯
-aux 显示所有包含其他使用者的行程

au(x) 输出格式 :

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
USER: 行程拥有者
PID: pid
%CPU: 占用的 CPU 使用率
%MEM: 占用的记忆体使用率
VSZ: 占用的虚拟记忆体大小
RSS: 占用的记忆体大小
TTY: 终端的次要装置号码 (minor device number of tty)
STAT: 该行程的状态:
D: 不可中断的静止 (通悸□□缜b进行 I/O 动作)
R: 正在执行中
S: 静止状态
T: 暂停执行
Z: 不存在但暂时无法消除
W: 没有足够的记忆体分页可分配
<: 高优先序的行程
N: 低优先序的行程
L: 有记忆体分页分配并锁在记忆体内 (即时系统或捱A I/O)
START: 行程开始时间
TIME: 执行的时间
COMMAND:所执行的指令

范例:

ps
PID TTY TIME CMD
2791 ttyp0 00:00:00 tcsh
3092 ttyp0 00:00:00 ps
% ps -A
PID TTY TIME CMD
1 ? 00:00:03 init
2 ? 00:00:00 kflushd
3 ? 00:00:00 kpiod
4 ? 00:00:00 kswapd
5 ? 00:00:00 mdrecoveryd
.......
% ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.7 1096 472 ? S Sep10 0:03 init [3]
root 2 0.0 0.0 0 0 ? SW Sep10 0:00 [kflushd]
root 3 0.0 0.0 0 0 ? SW Sep10 0:00 [kpiod]
root 4 0.0 0.0 0 0 ? SW Sep10 0:00 [kswapd]
........

名称:pstree
使用权限:所有使用者
使用方式:
pstree [-a] [-c] [-h|-Hpid] [-l] [-n] [-p] [-u] [-G|-U] [pid|user]
pstree -V
说明:将所有行程以树状图显示, 树状图将会以 pid (如果有指定) 或是以 init 这个基本行程为根 (root) ,如果有指定使用者 id , 则树状图会只显示该使用者所拥有的行程
参数:
-a 显示该行程的完整指令及参数, 如果是被记忆体置换出去的行程则会加上括号
-c 如果有重覆的行程名, 则分开列出 (预设值是会在前面加上 *
范例:

pstree

init-+-amd
|-apmd
|-atd
|-httpd---10*[httpd]
%pstree -p
init(1)-+-amd(447)
|-apmd(105)
|-atd(339)
%pstree -c
init-+-amd
|-apmd
|-atd
|-httpd-+-httpd
| |-httpd
| |-httpd
| |-httpd
....

名称:renice
使用权限:所有使用者

使用方式:renice priority [[-p] pid ...] [[-g] pgrp ...] [[-u] user ...]

说明:重新指定一个或多个行程(Process)的优先序(一个或多个将根据所下的参数而定)

把计

-p pid 重新指定行程的 id 为 pid 的行程的优先序
-g pgrp 重新指定行程群组(process group)的 id 为 pgrp 的行程 (一个或多个) 的优先序
-u user 重新指定行程拥有者为 user 的行程的优先序
范例:
将行程 id 为 987 及 32 的行程与行程拥有者为 daemon 及 root 的优先序号码加 1 :
renice +1 987 -u daemon root -p 32

注意 : 每一个行程(Process)都有一个唯一的 (unique) id

名称:top
使用权限:所有使用者

使用方式:top [-] [d delay] [q] [c] [S] [s] [i] [n] [b]

说明:即时显示 process 的动态

把计

d : 改变显示的更新速度,或是在交谈式指令列( interactive command)按 s
q : 没有任何延迟的显示速度,如果使用者是有 superuser 的权限,则 top 将会以最高的优先序执行
c : 切换显示模式,共有两种模式,一是只显示执行档的名称,另一种是显示完整的路径与名称S : 累积模式,会将己完成或消失的子行程 ( dead child process ) 的 CPU time 累积起来
s : 安全模式,将交谈式指令取消, 避免潜在的危机
i : 不显示任何闲置 (idle) 或无用 (zombie) 的行程
n : 更新的次数,完成后将会退出 top
b : 批次档模式,搭配 "n" 参数一起使用,可以用来将 top 的结果输出到档案内

范例:
显示更新十次后退出 ;
top -n 10

使用者将不能利用交谈式指令来对行程下命令 :
top -s

将更新显示二次的结果输入到名称为 top.log 的档案里 :
top -n 2 -b < top.log

名称:skill

使用权限:所有使用者

使用方式: skill [signal to send] [options] 选择程序的规则

说明:

送个讯号给正在执行的程序,预设的讯息为 TERM (中断) , 较常使用的讯息为 HUP , INT , KILL , STOP , CONT ,和 0

讯息有三种写法:分别为 -9 , -SIGKILL , -KILL , 可以使用 -l 或 -L 已列出可使用的讯息。

一般参数:

-f 快速模式/尚未完成

-i 互动模式/ 每个动作将要被确认

-v 详细输出/ 列出所选择程序的资讯

-w 智能警告讯息/ 尚未完成

-n 没有动作/ 显示程序代号

参数:选择程序的规则可以是, 终端机代号,使用者名称,程序代号,命令名称。

-t 终端机代号 ( tty 或 pty )

-u 使用者名称

-p 程序代号 ( pid )

-c 命令名称 可使用的讯号:

以下列出已知的讯号名称,讯号代号,功能。

名称 (代号) 功能/ 描述

ALRM 14 离开

HUP 1 离开

INT 2 离开

KILL 9 离开/ 强迫关闭

PIPE 13 离开

POLL 离开

PROF 离开

TERM 15 离开

USR1 离开

USR2 离开

VTALRM 离开

STKFLT 离开/ 只适用于i386, m68k, arm 和 ppc 硬体

UNUSED 离开/ 只适用于i386, m68k, arm 和 ppc 硬体

TSTP 停止 /产生与内容相关的行为

TTIN 停止 /产生与内容相关的行为

TTOU 停止 /产生与内容相关的行为

STOP 停止 /强迫关闭

CONT 从新启动 /如果在停止状态则从新启动,否则忽略

PWR 忽略 /在某些系统中会离开

WINCH 忽略

CHLD 忽略

ABRT 6 核心

FPE 8 核心

ILL 4 核心

QUIT 3 核心

SEGV 11 核心

TRAP 5 核心

SYS 核心 /或许尚未实作

EMT 核心 /或许尚未实作

BUS 核心 /核心失败

XCPU 核心 /核心失败

XFSZ 核心 /核心失败

范例:

停止所有在 PTY 装置上的程序
skill -KILL -v pts/*

停止三个使用者 user1 , user2 , user3
skill -STOP user1 user2 user3

其他相关的命令: kill
名称:expr

使用权限:所有使用者
### 字串长度

shell>> expr length "this is a test"
14

### 数字商数

shell>> expr 14 % 9
5

### 从位置处抓取字串

shell>> expr substr "this is a test" 3 5
is is

### 数字串 only the first character

shell>> expr index "testforthegame" e
2

### 字串真实重现

shell>> expr quote thisisatestformela
thisisatestformela

名称: tr

### 1.比方说要把目录下所有的大写档名换为小写档名?

似乎有很多方式,"tr"是其中一种:

#!/bin/sh

dir="/tmp/testdir";
files=`find $dir -type f`;
for i in $files
do
dir_name=`dirname $i`;
ori_filename=`basename $i`
new_filename=`echo $ori_filename | tr [:upper:] [:lower:]` > /dev/null;
#echo $new_filename;
mv $dir_name/$ori_filename $dir_name/$new_filename
done

### 2.自己试验中...lowercase to uppercase

tr abcdef...[del] ABCDE...[del]
tr a-z A-Z
tr [:lower:] [:upper:]

shell>> echo "this is a test" | tr a-z A-Z > www
shell>> cat www
THIS IS A TEST

### 3.去掉不想要的字串

shell>> tr -d this ### 去掉有关 t.e.s.t
this

man
man
test
e

### 4.取代字串

shell>> tr -s "this" "TEST"
this
TEST
th
TE

指令:clear
用途:清除萤幕用。

使用方法:在 console 上输入 clear。

名称: reset, tset
使用方法: tset [-IQqrs] [-] [-e ch] [-i ch] [-k ch] [-m mapping] [terminal]

使用说明:

reset 其实和 tset 是一同个命令,它的用途是设定终端机的状态。一般而言,这个命令会自动的从环境变数、命令列或是其它的组态档决定目前终端机的型态。如果指定型态是 ? 的话,这个程式会要求使用者输入终端机的型别。

由于这个程式会将终端机设回原始的状态,除了在 login 时使用外,当系统终端机因为程式不正常执行而进入一些奇怪的状态时,你也可以用它来重设终端机o 例如不小心把二进位档用 cat 指令进到终端机,常会有终端机不再回应键盘输入,或是回应一些奇怪字元的问题。此时就可以用 reset 将终端机回复至原始状态。选项说明:

-p
将终端机类别显示在萤幕上,但不做设定的动作。这个命令可以用来取得目前终端机的类别。
-e ch
将 erase 字元设成 ch
-i ch
将中断字元设成 ch
-k ch
将删除一行的字元设成 ch
-I
不要做设定的动作,如果没有使用选项 -Q 的话,erase、中断及删除字元的目前值依然会送到萤幕上。
-Q
不要显示 erase、中断及删除字元的值到萤幕上。
-r
将终端机类别印在萤幕上。
-s
将设定 TERM 用的命令用字串的型式送到终端机中,通常在 .login 或 .profile 中用
范例:
让使用者输入一个终端机型别并将终端机设到该型别的预设状态。
# reset ?

将 erase 字元设定 control-h
# reset -e ^B

将设定用的字串显示在萤幕上
# reset -s
Erase is control-B (^B).
Kill is control-U (^U).
Interrupt is control-C (^C).
TERM=xterm;

名称:compress

使用权限:所有使用者

使用方式:compress [-dfvcV] [-b maxbits] [file ...]

说明:
compress 是一个相当古老的 unix 档案压缩指令,压缩后的档案会加上一个 .Z 延伸档名以区别未压缩的档案,压缩后的档案可以以 uncompress 解压。若要将数个档案压成一个压缩档,必须先将档案 tar 起来再压缩。由于 gzip 可以产生更理想的压缩比例,一般人多已改用 gzip 为档案压缩工具。

参数:
c 输出结果至标准输出设备(一般指荧幕)
f 强迫写入档案,若目的档已经存在,则会被覆盖 (force)
v 将程式执行的讯息印在荧幕上 (verbose)
b 设定共同字串数的上限,以位元计算,可以设定的值为 9 至 16 bits 。由于值越大,能使用的共同字串就 越多,压缩比例就越大,所以一般使用预设值 16 bits (bits)
d 将压缩档解压缩
V 列出版本讯息

范例:

将 source.dat 压缩成 source.dat.Z ,若 source.dat.Z 已经存在,内容则会被压缩档覆盖。

compress -f source.dat

将 source.dat 压缩成 source.dat.Z ,并列印出压缩比例。
-v 与 -f 可以一起使用

compress -vf source.dat

将压缩后的资料输出后再导入 target.dat.Z 可以改变压缩档名。

compress -c source.dat > target.dat.Z

-b 的值越大,压缩比例就越大,范围是 9-16 ,预设值是 16 。

compress -b 12 source.dat

将 source.dat.Z 解压成 source.dat ,若档案已经存在,使用者按 y 以确定覆盖档案,若使用 -df 程式则会自动覆盖档案。由于系统会自动加入 .Z 为延伸档名,所以 source.dat 会自动当作 source.dat.Z 处理。

compress -d source.dat
compress -d source.dat.Z

名称: lpd

使用权限: 所有使用者

使用方式:lpd [-l] [#port]
lpd 是一个常驻的印表机管理程式,它会根据 /etc/printcap 的内容来管理本地或远端的印表机。/etc/printcap 中定义的每一个印表机必须在 /var/lpd 中有一个相对应的目录,目录中以 cf 开头的档案表示一个等待送到适当装置的印表工作。这个档案通常是由 lpr 所产生。

lpr 和 lpd 组成了一个可以离线工作的系统,当你使用 lpr 时,印表机不需要能立即可用,甚至不用存在。lpd 会自动监视印表机的状况,当印表机上线后,便立即将档案送交处理。这个得所有的应用程式不必等待印表机完成前一工作。

参数:

-l: 将一些除错讯息显示在标准输出上。
#port: 一般而言,lpd 会使用 getservbyname 取得适当的 TCP/IP port,你可以使用这个参数强迫 lpd 使用指定的 port。

范例:
这个程式通常是由 /etc/rc.d 中的程式在系统启始阶段执行。

名称 lpq
-- 显示列表机贮列中未完成的工作 用法

lpq [l] [P] [user]

说明
lpq 会显示由 lpd 所管理的列表机贮列中未完成的项目。

范例
范例 1. 显示所有在 lp 列表机贮列中的工作

# lpq -PlpRank Owner Job Files Total Size1st root 238 (standard input) 1428646 bytes

相关函数
lpr,lpc,lpd

名称: lpr

使用权限: 所有使用者

使用方式:lpr [ -P printer ]
将档案或是由标准输入送进来的资料送到印表机贮列之中,印表机管理程式 lpd 会在稍后将这个档案送给适当的程式或装置处理。lpr 可以用来将料资送给本地或是远端的主机来处理。

参数:

-p Printer: 将资料送至指定的印表机 Printer,预设值为 lp。

范例:
将 www.c 和 kkk.c 送到印表机 lp。
lpr -Plp www.c kkk.c

名称: lprm
-- 将一个工作由印表机贮列中移除 用法

/usr/bin/lprm [P] [file...]

说明
尚未完成的印表机工作会被放在印表机贮列之中,这个命令可用来将常未送到印表机的工作取消。由于每一个印表机都有一个独立的贮列,你可以用 -P 这个命令设定想要作用的印列机。如果没有设定的话,会使用系统预设的印表机。

这个命令会检查使用者是否有足够的权限删除指定的档案,一般而言,只有档案的拥有者或是系统管理员才有这个权限。

范例
将印表机 hpprinter 中的第 1123 号工作移除

lprm -Phpprinter 1123

将第 1011 号工作由预设印表机中移除

lprm 1011

名称: fdformat

使用权限: 所有使用者

使用方式:fdformat [-n] device

使用说明 :
对指定的软碟机装置进行低阶格式化。使用这个指令对软碟格式化的时候,最好指定像是下面的装置:

/dev/fd0d360 磁碟机 A: ,磁片为 360KB 磁碟
/dev/fd0h1440 磁碟机 A: ,磁片为 1.4MB 磁碟
/dev/fd1h1200 磁碟机 B: ,磁片为 1.2MB 磁碟
如果使用像是 /dev/fd0 之类的装置,如果里面的磁碟不是标准容量,格式化可能会失败。在这种情况之下,使用者可以用 setfdprm 指令先行指定必要参数。

参数:

-n 关闭确认功能。这个选项会关闭格式化之后的确认步骤。

范例:

fdformat -n /dev/fd0h1440

将磁碟机 A 的磁片格式化成 1.4MB 的磁片。并且省略确认的步骤。

名称: mformat

使用权限: 所有使用者

使用方式:

mformat [-t cylinders] [-h heads] [-s sectors] [-l volume_label] [-F] [-I fsVer-sion] [-S sizecode] [-2 sectors_on_track_0] [-M software_sector_size] [-a] [-X] [-C] [-H hidden_sectors] [-r root_sectors] [-B boot_sector] [-0 rate_on_track_0] [-A rate_on_other_tracks] [-1] [-k] drive:

在已经做过低阶格式化的磁片上建立 DOS 档案系统。如果在编译 mtools 的时候把 USE_2M 的参数打开,部分与 2M 格式相关的参数就会发生作用。否则这些参数(像是 S,2,1,M)不会发生作用。

参数:

-t 磁柱(synlider)数
-h 磁头(head)数
-s 每一磁轨的磁区数
-l 标签
-F 将磁碟格式化为 FAT32 格式,不过这个参数还在实验中。
-I 设定 FAT32 中的版本号。这当然也还在实验中。
-S 磁区大小代码,计算方式为 sector = 2^(大小代码+7)
-c 磁丛(cluster)的磁区数。如果所给定的数字会导致磁丛数超过 FAT 表的限制,mformat 会自动放大磁区数。
-s
-M 软体磁区大小。这个数字就是系统回报的磁区大小。通常是和实际的大小相同。
-a 如果加上这个参数,mformat 会产生一组 Atari 系统的序号给这块软碟。
-X 将软碟格式化成 XDF 格式。使用前必须先用 xdfcopy 指令对软碟作低阶格式化的动作。
-C 产生一个可以安装 MS-DOS 档案系统的磁碟影像档(disk image)。当然对一个实体磁碟机下这个参数是没有意义的。
-H 隐藏磁区的数目。这通常适用在格式化硬碟的分割区时,因为通常一个分割区的前面还有分割表。这个参数未经测试,能不用就不用。
-n 磁碟序号
-r 根目录的大小,单位是磁区数。这个参数只对 FAT12 和 FAT16 有效。
-B 使用所指定的档案或是设备的开机磁区做为这片磁片或分割区的开机磁区。当然当中的硬体参数会随之更动。
-k 尽量保持原有的开机磁区。
-0 第 0 轨的资料传输率
-A 第 0 轨以外的资料传输率
-2 使用 2m 格式
-1 不使用 2m 格式

范例:
mformat a:

这样会用预设值把 a: (就是 /dev/fd0)里的磁碟片格式化。

名称: mkdosfs

使用权限: 所有使用者

使用方式: mkdosfs [ -c | -l filename ]
[ -f number_of_FATs ]
[ -F FAT_size ]
[ -i volume_id ]
[ -m message_file ]
[ -n volume_name ]
[ -r root_dir_entry ]
[ -s sector_per_cluster ]
[ -v ]
device
[ block_count ]

说明: 建立 DOS 档案系统。 device 指你想要建立 DOS 档案系统的装置代号。像是 /dev/hda1 等等。 block_count 则是你希望配置的区块数。如果 block_count 没有指定则系统会自动替你计算符合该装置大小的区块数。

参数:

-c 建立档案系统之前先检查是否有坏轨。
-l 从得定的档案中读取坏轨记录。
-f 指定档案配置表(FAT , File Allocation Table)的数量。预设值为 2 。目前 Linux 的 FAT 档案系统不支援超过 2 个 FAT 表。通常这个不需要改。
-F 指定 FAT 表的大小,通常是 12 或是 16 个位元组。12 位元组通常用于磁碟片,16 位元组用于一般硬碟的分割区,也就是所谓的 FAT16 格式。这个值通常系统会自己选定适当的值。在磁碟片上用 FAT16 通常不会发生作用,反之在硬碟上用 FAT12 亦然。
-i 指定 Volume ID。一般是一个 4 个位元组的数字,像是 2e203a47 。如果不给系统会自己产生。
-m 当使用者试图用这片磁片或是分割区开机,而上面没有作业系统时,系统会给使用者一段警告讯息。这个参数就是用来变更这个讯息的。你可以先用档案编辑好,然后用这个参数指定,或是用
-m -
这样系统会要求你直接输入这段文字。要特别注意的是,档案里的字串长度不要超过 418 个字,包括展开的跳栏符号(TAB)和换行符号(换行符号在 DOS 底下算两个字元!)
-n 指定 Volume Name,就是磁碟标签。如同在 DOS 底下的 format 指令一样,给不给都可以。没有预设值。
-r 指定根目录底下的最大档案数。这里所谓的档案数包括目录。预设值是在软碟上是 112 或是 224 ,在硬碟上是 512。没事不要改这个数字。
-s 每一个磁丛(cluster)的磁区数。必须是 2 的次方数。不过除非你知道你在作什么,这个值不要乱给。
-v 提供额外的讯息

范例:
mkdosfs -n Tester /dev/fd0 将 A 槽里的磁碟片格式化为 DOS 格式,并将标签设为 Tester

发表在 article | 标签为 | 31条评论

apache、lighttpd和Nginx的404错误处理

最近在处理图片分布问题,问题来源是这样的:
1 把服务器B的图片定时同步到服务器A,用A来接受用户访问
2 同步有时间差,为了保证用户体验,需要在A发生404错误的时候转移到原服务器B,这样用户体会不到发生问题,否则上传图片会立刻看不到,不可能等你同步完的

我觉得这样的分布方式应该是很不错的,只要解决404错误的处理,就可以保证上面的服务正常。因为是说明问题,所以以下提及的代码都整理过,域名也做了更改。

一、最初用lighttpd来处理:

发生404错误,则交由cgi脚本来处理,取得$REQUEST_URI,location到源服务器

404.cgi脚本文件(比较简单,需要条件性的转移请自行修改):

 

#!/bin/sh

# disable filename globbing
set -f

URI=$REQUEST_URI

## by hqlulu @ aslibra.com 2008-8-14 ##
echo "location: http://www.aslibra.com$URI"
echo

Lighttpd下使用cgi测试:

 

#配置如下:
server.error-handler-404 = "/cgi-bin/404.cgi"

http://test404.aslibra.com/mag/nofile
得到的是www.aslibra.com的404错误提示,说明已经转移成功

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com/mag/nofile
HTTP/1.1 302 Found
Expires: Tue, 02 Sep 2008 12:52:44 GMT
Cache-Control: max-age=864000
location: http://www.aslibra.com/mag/nofile
Date: Sat, 23 Aug 2008 12:52:44 GMT
Server: lighttpd/1.4.15

二、Apache安装在8080端口,尝试cgi失败了:

 

#配置如下:
ErrorDocument 404 "/cgi-bin/404.cgi"

http://test404.aslibra.com:8080/mag/nofile
看到的是空白页面

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:8080/mag/nofile
HTTP/1.1 404 Not Found
Date: Sat, 23 Aug 2008 12:55:45 GMT
Server: Apache/2.2.6 (Unix)
location: http://www.aslibra.com/mag/nofile
Connection: close
Content-Type: text/plain

琢磨了很久,才发现问题,可以看到原因,已经发出了404错误的文件头了,导致后面的location失效,但是怎么去掉404的输出呢,让我纳闷了很久。

经过查实Apache的文档:

 

引用
如果ErrorDocument指定了一个到本地CGI脚本的重定向,该脚本应当在它的输出中包含一个"Status:"头字段以确保将导致调用它的错误条件始终返回客户端。举例来说,一个Perl ErrorDocument脚本可能包含如下内容:

print "Content-type: text/html\n";
printf "Status: %s <中断条件>\n", $ENV{"REDIRECT_STATUS"};

如果该脚本专门用于处理一个特定的错误条件,比如:404 Not Found ,它就可以使用特定的代码和错误文本进行替代。

需要注意的是如果应答包含一个"Location:"头(为了进行一个客户端重定向),脚本必须发出一个适当的"Status:"头(比如:302 Found)。否则"Location:"头可能无效。

这就找到原因了,加上一段就可以了:

 

#!/bin/sh

# disable filename globbing
set -f

URI=$REQUEST_URI
echo "Status:302 Found"

## by hqlulu @ aslibra.com 2008-8-14 ##
echo "location: http://www.aslibra.com$URI"
echo

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:8080/mag/nofile
HTTP/1.1 302 Found
Date: Sat, 23 Aug 2008 13:02:54 GMT
Server: Apache/2.2.6 (Unix)
location: http://www.aslibra.com/mag/nofile
Connection: close
Content-Type: text/plain

三、Apache的PHP处理方式(安装了PHP的模块):

 

ErrorDocument 404 /404.php

404.php文件内容(条件转移自行修改):
 

<?php
$url=$_SERVER[REQUEST_URI];
header("location: http://www.aslibra.com".$url);
?>

测试结果:
 

引用
[root@gx ~]# curl -I http://pic.zcom.com/mag/nofile
HTTP/1.1 302 Found
Date: Sat, 23 Aug 2008 13:10:14 GMT
Server: Apache/2.2.6 (Unix) PHP/5.2.6
X-Powered-By: PHP/5.2.6
location: http://www.aslibra.com/mag/nofile
Content-Type: text/html

四、Nginx的配置:

因为Nginx没法使用cgi,只能使用fastcgi,所以配置了PHP的fastcgi处理404错误。

 

error_page  404              /404.php;

location ~ \.php$ {
    fastcgi_pass   192.168.1.5:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /Data/webapps/www.aslibra.com$fastcgi_script_name;
    include        fastcgi_params;
}

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:88/mag/nofile
HTTP/1.1 404 Not Found
Server: nginx/0.6.31
Date: Sat, 23 Aug 2008 13:10:42 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.2.6
location: http://www.aslibra.com/mag/nofile

碰到了apache的一样的问题,于是查看官方说明的错误处理:

 

引用
error_page
syntax: error_page code [ code... ] [ = |=answer-code ] uri

default: no

context: http, server, location, if in location

The directive specifies the URI, which will be showed for the errors indicated.

Example of the use:

error_page   404          /404.html;
error_page   502 503 504  /50x.html;
error_page   403          http://example.com/forbidden.html;
Furthermore, it is possible to change the code of answer to another, for example:

error_page 404 =200 /.empty.gif;
If an erroneous answer is processed by the proxied or FastCGI server and this server can return the different answer codes, for example, 200, 302, 401 or 404, then it is possible to issue the code returned:

error_page   404  =  /404.php;

终于看到这个例子了:
error_page 404 =200 /.empty.gif;

也就是指定一个answer-code就正常了,修改配置:
 

error_page  404 =302             /404.php;

location ~ \.php$ {
    fastcgi_pass   192.168.1.5:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /Data/webapps/www.aslibra.com$fastcgi_script_name;
    include        fastcgi_params;
}

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:88/mag/nofile
HTTP/1.1 302 Moved Temporarily
Server: nginx/0.6.31
Date: Sat, 23 Aug 2008 13:15:20 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.2.6
location: http://www.aslibra.com/mag/nofile

这回就正常了!

以上是常见的三种web服务器的404错误处理,希望可以对解决大家的应用问题有参考价值。

五、404.cgi的条件判断(代码有点笨,sh不是专长):

 

#!/bin/sh

# disable filename globbing
set -f

URI=$REQUEST_URI
echo "Status:302 Found"

if
  echo $URI | grep "^/mag" >/dev/null
then
        echo "location: http://www1.aslibra.com$URI"
elif
  echo $URI | grep "^/op" >/dev/null
then
        echo "location: http://www2.aslibra.com$URI"
else
        echo
        echo "file not exists!"
fi

发表在 web server | 标签为 , , | apache、lighttpd和Nginx的404错误处理已关闭评论

Nginx 0.5.33 + PHP 5.2.5 (FastCGI) 可以承受3万以上的并发连接数,相当于同等环境下Apache的10倍

根据我的经验,4GB内存的服务器+Apache(prefork模式)一般只能处理3000个并发连接,因为它们将占用3GB以上的内存,还得为系统预留1GB的内存。我曾经就有两台Apache服务器,因为在配置文件中设置的MaxClients为4000,当Apache并发连接数达到3800时,导致服务器内存和Swap空间用满而崩溃。

  而这台 Nginx 0.5.33 + PHP 5.2.5 (FastCGI) 服务器在3万并发连接下,开启的10个Nginx进程消耗150M内存(15M*10=150M),开启的64个php-cgi进程消耗1280M内存(20M*64=1280M),加上系统自身消耗的内存,总共消耗不到2GB内存。如果服务器内存较小,完全可以只开启25个php-cgi进程,这样php-cgi消耗的总内存数才500M。

 


  安装步骤:
  (系统要求:Linux 2.6+ 内核,本文中的Linux操作系统为CentOS 4.4)

  一、获取相关开源程序:
  1、下载程序源码包到当前目录:
  本文中提到的所有开源软件为截止到2007年11月25日的最新稳定版。我将它们打了两个压缩包。

  第一个压缩包:nginx-php-1.zip
  下载地址:http://ishare.iask.sina.com.cn/cgi-bin/fileid.cgi?fileid=2746375

  第二个压缩包:nginx-php-2.zip
  下载地址:http://ishare.iask.sina.com.cn/cgi-bin/fileid.cgi?fileid=2746370

  附:各开源软件单独下载地址(如果下载了以上两个压缩包,则无需下载以下软件):
  http://down.s135.com/linux/nginx-php/
(登录用户名、密码均为blog.s135.com)

  2、解压缩:
 

mkdir -p /data0/software
cd /data0/software
unzip nginx-php-1.zip
unzip nginx-php-2.zip
cd /data0/software/nginx-php

 


  二、安装PHP 5.2.5(FastCGI模式)
  1、编译安装PHP 5.2.5所需的支持库:
 

tar zxvf libiconv-1.11.tar.gz
cd libiconv-1.11/
./configure --prefix=/usr/local
make
make install
cd ../

tar zxvf freetype-2.3.5.tar.gz
cd freetype-2.3.5/
./configure
make
make install
cd ../

tar zxvf libpng-1.2.20.tar.gz
cd libpng-1.2.20/
./configure
make
make install
cd ../

tar zxvf jpegsrc.v6b.tar.gz
cd jpeg-6b/
./configure --enable-static --enable-shared
make
make install
make install-lib
cd ../

#----If your system was install libxml2, you do not need to install it.----
#tar zxvf libxml2-2.6.30.tar.gz
#cd libxml2-2.6.30/
#./configure
#make
#install
#cd ../

tar zxvf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8/
./configure
make
make install
/sbin/ldconfig
cd libltdl/
./configure --enable-ltdl-install
make
make install
cd ../../

tar zxvf mhash-0.9.9.tar.gz
cd mhash-0.9.9/
./configure
make
make install
cd ../

cp /usr/local/lib/libmcrypt.* /usr/lib
ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2

tar zxvf mcrypt-2.6.6.tar.gz
cd mcrypt-2.6.6/
./configure
make
make install
cd ../

 


  2、编译安装MySQL 5.0.45
 

/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql
tar zxvf mysql-5.0.45.tar.gz
cd mysql-5.0.45
./configure --prefix=/usr/local/webserver/mysql/ --without-debug --with-unix-socket-path=/tmp/mysql.sock --with-client-ldflags=-all-static --with-mysqld-ldflags=-all-static --enable-assembler --with-extra-charsets=gbk,gb2312,utf8 --with-pthread --enable-thread-safe-client
make && make install
chmod +w /usr/local/webserver/mysql
chown -R mysql:mysql /usr/local/webserver/mysql
cp support-files/my-medium.cnf /usr/local/webserver/mysql/my.cnf
cd ../

 


  附:以下为附加步骤,如果你想在这台服务器上运行MySQL数据库,则执行以下两步。如果你只是希望让PHP支持MySQL扩展库,能够连接其他服务器上的MySQL数据库,那么,以下两步无需执行。
  ①、以mysql用户帐号的身份建立数据表:
 

/usr/local/webserver/mysql/bin/mysql_install_db --defaults-file=/usr/local/webserver/mysql/my.cnf --basedir=/usr/local/webserver/mysql --datadir=/usr/local/webserver/mysql/data --user=mysql --pid-file=/usr/local/webserver/mysql/mysql.pid --skip-locking --port=3306 --socket=/tmp/mysql.sock

  ②、启动MySQL(最后的&表示在后台运行)
 

/bin/sh /usr/local/webserver/mysql/bin/mysqld_safe --defaults-file=/usr/local/webserver/mysql/my.cnf &

 


  3、编译安装PHP(FastCGI模式)
 

tar zxvf php-5.2.5.tar.gz
cd php-5.2.5/
./configure --prefix=/usr/local/webserver/php --with-config-file-path=/usr/local/webserver/php/etc --with-mysql=/usr/local/webserver/mysql --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir --enable-xml --disable-debug --disable-rpath --enable-discard-path --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fastcgi --enable-force-cgi-redirect --enable-mbstring --with-mcrypt
sed -i 's#-lz -lm -lxml2 -lz -lm -lxml2 -lz -lm -lcrypt#& -liconv#' Makefile
make
make install
cp php.ini-dist /usr/local/webserver/php/etc/php.ini
cd ../

 


  4、编译安装PHP5扩展模块
 

tar zxvf memcache-2.2.1.tgz
cd memcache-2.2.1/
/usr/local/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../

cd php-5.2.5/ext/gd/
/usr/local/webserver/php/bin/phpize
./configure --with-jpeg-dir --with-png-dir --with-zlib-dir --with-ttf --with-freetype-dir --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../../../

  5、修改php.ini文件
  手工修改:查找/usr/local/webserver/php/etc/php.ini中的extension_dir = "./"
  修改为extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"
  并在此行后增加以下几行,然后保存:
  extension = "memcache.so"
  extension = "gd.so"

  自动修改:若嫌手工修改麻烦,可执行以下shell命令,自动完成对php.ini文件的修改:
 

sed -i 's#extension_dir = "./"#extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"\nextension = "memcache.so"\nextension = "gd.so"\n#' /usr/local/webserver/php/etc/php.ini

 


  6、创建www用户和组,以及其使用的目录:
 

/usr/sbin/groupadd www -g 48
/usr/sbin/useradd -u 48 -g www www
mkdir -p /data0/vshare/htdocs
chmod +w /data0/vshare/htdocs
chown -R www:www /data0/vshare/htdocs

  7、安装lighttpd中附带的spawn-fcgi,用来启动php-cgi
  注:压缩包中的spawn-fcgi程序为已经编译成二进制的版本。
 

cp spawn-fcgi /usr/local/webserver/php/bin
chmod +x /usr/local/webserver/php/bin/spawn-fcgi

  8、启动php-cgi进程,监听127.0.0.1的10080端口,进程数为64(如果服务器内存小于3GB,可以只开启25个进程),用户为www:
 

/usr/local/webserver/php/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 64 -u www -f /usr/local/webserver/php/bin/php-cgi

 


  三、安装Nginx 0.5.33
  1、安装Nginx所需的pcre库:
 

tar zxvf pcre-7.2.tar.gz
cd pcre-7.2/
./configure
make && make install
cd ../

  2、安装Nginx
 

tar zxvf nginx-0.5.33.tar.gz
cd nginx-0.5.33/
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --with-http_stub_status_module
make && make install
cd ../

  3、创建Nginx日志目录
 

mkdir -p /data1/logs
chmod +w /data1/logs
chown -R www:www /data1/logs

  4、创建Nginx配置文件
  ①、在/usr/local/webserver/nginx/conf/目录中创建nginx.conf文件:
 

rm -f /usr/local/webserver/nginx/conf/nginx.conf
vi /usr/local/webserver/nginx/conf/nginx.conf

  输入以下内容:
 

引用
user  www www;

worker_processes 10;

error_log  /data1/logs/nginx_error.log  crit;

#pid        logs/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;

events
{
      use epoll;

      worker_connections 51200;
}

http
{
      include       conf/mime.types;
      default_type  application/octet-stream;

      charset  gb2312;
     
      server_names_hash_bucket_size 128;
     
      #sendfile on;
      #tcp_nopush     on;

      keepalive_timeout 60;

      tcp_nodelay on;

      gzip on;
      gzip_min_length  1k;
      gzip_buffers     4 8k;
      gzip_http_version 1.1;
      gzip_types       text/plain application/x-javascript text/css text/html application/xml;

      server
      {
              listen       80;
              server_name  blog.s135.com;
              index index.html index.htm index.php;
              root  /data0/vshare/htdocs;

              if (-d $request_filename)
              {
                     rewrite ^/(.*)([^/])$ http://$host/$1$2/
permanent;
              }
                             
              location ~ .*\.php?$
              {
                   include conf/fcgi.conf;      
                   fastcgi_pass  127.0.0.1:10080;
                   fastcgi_index index.php;
              }

              log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
                                    '$status $body_bytes_sent "$http_referer" '
                                    '"$http_user_agent" $http_x_forwarded_for';
              access_log  /data1/logs/access.log  access;
      }

      server
      {
              listen  80;
              server_name  status.blog.s135.com;

              location / {
                   stub_status on;
                   access_log   off;
              }
      }
}

  ②、在/usr/local/webserver/nginx/conf/目录中创建fcgi.conf文件:
 

vi /usr/local/webserver/nginx/conf/fcgi.conf

  输入以下内容:
 

引用
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
#fastcgi_param  REDIRECT_STATUS    200;

  5、启动Nginx
 

ulimit -SHn 51200
/usr/local/webserver/nginx/sbin/nginx -c /usr/local/webserver/nginx/conf/nginx.conf

 


  四、配置开机自动启动Nginx + PHP
 

vi /etc/rc.local

  在末尾增加以下内容:
 

引用
ulimit -SHn 51200
/usr/local/webserver/php/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 64 -u www -f /usr/local/webserver/php/bin/php-cgi
/usr/local/webserver/nginx/sbin/nginx -c /usr/local/webserver/nginx/conf/nginx.conf

 


  五、优化Linux内核参数
 

vi /etc/sysctl.conf

  在末尾增加以下内容:
 

引用
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 5000    65000

  使配置立即生效:
 

/sbin/sysctl -p

 


  六、在不停止Nginx服务的情况下平滑变更Nginx配置
  (1)、修改/usr/local/webserver/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:
 

/usr/local/webserver/nginx/sbin/nginx -t

  如果屏幕显示以下两行信息,说明配置文件正确:
  the configuration file /usr/local/webserver/nginx/conf/nginx.conf syntax is ok
  the configuration file /usr/local/webserver/nginx/conf/nginx.conf was tested successfully

  (2)、这时,输入以下命令查看Nginx主进程号:
 

ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'

  屏幕显示的即为Nginx主进程号,例如:
  6302

  这时,执行以下命令即可使修改过的Nginx配置文件生效:
 

kill -HUP 6302

 

发表在 web server | 标签为 , | Nginx 0.5.33 + PHP 5.2.5 (FastCGI) 可以承受3万以上的并发连接数,相当于同等环境下Apache的10倍已关闭评论

Nginx PHP FastCGI 安装配置记录

因需要兼容老程序,这里用的还是 PHP4 ,可根据自己的需要更改编译选项。
tar jxvf php-4.4.8.tar.bz2
cd php-4.4.8
./configure \
--prefix=/usr/local/php-fcgi \
--enable-fastcgi \
--enable-discard-path \
--enable-force-cgi-redirect \
--enable-mbstring=all \
--enable-memcache \
--with-config-file-path=/usr/local/php-fcgi/etc \
--with-gd=/usr/local/gd \
--with-zlib \
--with-png \
--with-jpeg \
--with-freetype \
--with-mysql=/usr/local/mysql \
--with-dom
make
make install
cp -f php.ini-dist /usr/local/php-fcgi/etc/php.ini

安装 ZendOptimizer
Zend 的优化器,免费使用,如果加密了 PHP 程序文件,这是必须的。
如果没有使用 Zend 优化器,PHP 进程的内存会难以释放。
下载:http://www.zend.com/en/products/guard/downloads
tar zxvf ZendOptimizer-3.3.3-linux-glibc23-i386.tar.gz
cd ZendOptimizer-3.3.3-linux-glibc23-i386
./install
cd ..

安装 eAccelerator
PHP scripts 的缓存,对于提高 PHP 程序执行速度很有帮助。
下载:http://eaccelerator.net/
tar jxvf eaccelerator-0.9.5.2.tar.bz2
cd eaccelerator-0.9.5.2
/usr/local/php-fcgi/bin/phpize
./configure --enable-eaccelerator=shared --with-php-config=/usr/local/php-fcgi/bin/php-config
make
make install
cd ..

安装 memcache
用于缓存 sql 查询,对于降低数据库压力,提升查询速度有很大好处。
下载:http://pecl.php.net/package/memcache
tar zxvf memcache-2.2.3.tgz
cd memcache-2.2.3
/usr/local/php-fcgi/bin/phpize
./configure --with-php-config=/usr/local/php-fcgi/bin/php-config
make
make install

安装 Linghttpd's spawn-fcgi
用 Lighttpd 的 spawn-fcgi 来管理 PHP FastCGI 进程。
下载 Lighttpd: http://www.lighttpd.net/download
yum -y install pcre-devel
(debian: apt-get -y install libpcre3-dev)
tar zxvf lighttpd-1.4.19.tar.bz2
cd lighttpd-1.4.19
./configure --without-bzip2
make
cp -a src/spawn-fcgi /usr/local/php-fcgi/bin/
 

安装 Nginx
下载:http://nginx.net/
tar zxvf nginx-0.5.35.tar.gz
cd nginx-0.5.35
./configure \
--user=nobody \
--group=nobody \
--prefix=/usr/local/nginx \
--with-http_stub_status_module
make
make install

配置 PHP
vi /usr/local/php-fcgi/etc/php.ini
# 最大执行时间
max_execution_time = 5
# 打开全局变量兼容老程序
register_globals = On
# 默认编码
default_charset = "gbk"
# 扩展模块的目录
extension_dir = "/usr/local/php-fcgi/lib/php/extensions/no-debug-non-zts-20020429"
# 关闭 mysql 持久连接。高访问量下会把数据库可用连接用完。
mysql.allow_persistent = Off
# 降低连接超时时间
mysql.connect_timeout = 10
# session 文件存储目录,这里为两级目录,需要手动创建。
session.save_path = "2;/tmpfs/phpsession"
# session 过期时间设为一小时。
session.gc_maxlifetime = 3600
# 关闭
session.bug_compat_42 = 0
session.bug_compat_warn = 0

# 开启 eAccelerator
[eAccelerator]
extension="eaccelerator.so"
# 可使用内存设为了 32M,太大会启动不了 PHP。
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/tmpfs/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

# 在 eAccelerator 之后启用 ZO ,避免 eaccelerator.so 不能加载。
[Zend]
zend_optimizer.optimization_level=1023
zend_extension_manager.optimizer=/usr/local/Zend/lib/Optimizer-3.3.3
zend_optimizer.version=3.3.3
zend_extension=/usr/local/Zend/lib/ZendExtensionManager.so

# 开启 memcache
[memcache]
extension=memcache.so

配置 Nginx
建立相应目录
mkdir /var/log/nginx
cd /usr/local/nginx
mv logs conf/vhosts
cd conf
vi nginx.conf

  1. # 运行 Nginx 的用户
  2. user  nobody nobody;
  3. # Nginx 的进程数
  4. worker_processes  8;
  5.  
  6. # 错误日志
  7. error_log  /var/log/nginx/error.log;
  8.  
  9. # pid 文件
  10. pid        /var/run/nginx.pid;
  11.  
  12. events {
  13. # 使用 epoll(For Linux Kernel 2.6+) 提升 Nginx 性能。
  14.     use  epoll;
  15. # 最大连接数
  16.     worker_connections  4096;
  17. }
  18.  
  19.  
  20. http {
  21. # 包含 mime types 的配置文件
  22.     include       conf/mime.types;
  23. # 默认类型
  24.     default_type  application/octet-stream;
  25.  
  26. # 定义 temp 的路径
  27.     client_body_temp_path  /tmpfs/nginx/client_body_temp;
  28.     proxy_temp_path        /tmpfs/nginx/proxy_temp;
  29.     fastcgi_temp_path      /tmpfs/nginx/fastcgi_temp;
  30.  
  31. # 如果 server_name 定义的域名过多,需要增大这个值
  32.     server_names_hash_bucket_size  128;
  33.  
  34. # 定义主访问日志格式,因开启了 gzip,加入了 $gzip_ratio
  35.     log_format  main  '$remote_addr - $remote_user [$time_local] $request '
  36.                       '"$status" $body_bytes_sent "$http_referer" '
  37.                       '"$http_user_agent" "$gzip_ratio"';
  38.  
  39. # 默认的访问日志存放文件
  40.     access_log  /var/log/nginx/access.log  main;
  41.  
  42. # Linux Kernel 2.4+ 可通过调用内核级 sendfile() 来提高性能
  43.     sendfile  on;
  44.  
  45. # FreeBSD 或基于 TCP_CORK 的 Linux 系统可使用
  46.     tcp_nopush on;
  47.  
  48. # 只在 keep-alive 连接状态中使用
  49.     tcp_nodelay  on;
  50.  
  51. # 设置保持连接超时时间 和 header 超时时间(单位:秒)
  52.     keepalive_timeout  60 15;
  53.  
  54. # 开启 gzip
  55.     gzip  on;
  56. # 压缩级别 1-9,9 为最高压缩级别
  57.     gzip_comp_level  9;
  58. # 回送给客户端最小的 gzip 压缩大小
  59.     gzip_min_length  1100;
  60. # 设置 gzip 缓存的大小,默认是 4-8k 之间
  61.     gzip_buffers  4 8k;
  62. # gzip http 版本
  63.     gzip_http_version  1.1;
  64. # 需要使用 gzip 压缩的文件类型
  65.     gzip_types  text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  66.  
  67. # 定义默认主机
  68.     server {
  69. # 监听端口
  70.         listen       80;
  71. # 匹配所有域名
  72.         server_name  _ *;
  73. # 默认首页
  74.         index  index.php;
  75. # 根目录路径
  76.         root  /home/www;
  77. # 执行 php 程序文件的设置
  78.         location ~ .*\.php?$ {
  79.             include  conf/fcgi.conf;
  80.         }
  81. # 对于以下文件不记录访问日志
  82.         location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
  83.             access_log  off;
  84.         }
  85.     }
  86.  
  87. # 包含其它虚拟主机的配置
  88.     include  conf/vhosts/*.conf;
  89. }

vi fcgi.conf

  1. fastcgi_pass  127.0.0.1:10080;
  2.  
  3. fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
  4. fastcgi_param  SERVER_SOFTWARE    nginx;
  5.  
  6. fastcgi_param  QUERY_STRING       $query_string;
  7. fastcgi_param  REQUEST_METHOD     $request_method;
  8. fastcgi_param  CONTENT_TYPE       $content_type;
  9. fastcgi_param  CONTENT_LENGTH     $content_length;
  10.  
  11. fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
  12. fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
  13. fastcgi_param  REQUEST_URI        $request_uri;
  14. fastcgi_param  DOCUMENT_URI       $document_uri;
  15. fastcgi_param  DOCUMENT_ROOT      $document_root;
  16. fastcgi_param  SERVER_PROTOCOL    $server_protocol;
  17.  
  18. fastcgi_param  REMOTE_ADDR        $remote_addr;
  19. fastcgi_param  REMOTE_PORT        $remote_port;
  20. fastcgi_param  SERVER_ADDR        $server_addr;
  21. fastcgi_param  SERVER_PORT        $server_port;
  22. fastcgi_param  SERVER_NAME        $server_name;
  23.  
  24. # PHP only, required if PHP was built with --enable-force-cgi-redirect
  25. fastcgi_param  REDIRECT_STATUS    200;

再来配置 Discuz! 论坛和 SupeSite/X-Space 的虚拟主机
vi vhosts/main.conf

  1. server {
  2.     listen       80;
  3. # 分论坛可使用子域名
  4.     server_name  bbs.domain.com *.bbs.domain.com;
  5.     index  index.php;
  6.     root  /home/www/bbs;
  7. # 和 Apache Rewrite 规则很相似
  8.     rewrite  ^/archiver/((fid|tid)-[\w\-]+\.html)$ /archiver/index.php?$1;
  9.     rewrite  ^/forum-([0-9]+)-([0-9]+)\.html$ /forumdisplay.php?fid=$1&page=$2;
  10.     rewrite  ^/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /viewthread.php?tid=$1&extra=page\%3D$3&page=$2;
  11.     rewrite  ^/space-(username|uid)-(.+)\.html$ /space.php?action=viewpro&$1=$2;
  12.     rewrite  ^/tag-(.+)\.html$ /tag.php?name=$1;
  13.         location ~ .*\.php?$ {
  14.             include  conf/fcgi.conf;
  15.         }
  16.         location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
  17.             access_log  off;
  18.         }
  19.     }
  20.  
  21.     server {
  22.     listen       80;
  23.     server_name  blog.domain.com;
  24.     index  index.php;
  25.     root  /home/www/blog;
  26.     rewrite  ^([0-9]+)/spacelist(.*)$ index.php?$1/action_spacelist$2;
  27.     rewrite  ^([0-9]+)/viewspace_(.+)$ index.php?$1/action_viewspace_itemid_$2;
  28.     rewrite  ^([0-9]+)/viewbbs_(.+)$ index.php?$1/action_viewbbs_tid_$2;
  29.     rewrite  ^([0-9]+)/(.*)$ index.php?$1/$2;
  30.     rewrite  ^([0-9]+)$ index.php?$1;
  31.     rewrite  ^action_(.+)$ index.php?action_$1;
  32.     rewrite  ^category_(.+)$ index.php?action_category_catid_$1;
  33.     rewrite  ^itemlist_(.+)$ index.php?action_itemlist_catid_$1;
  34.     rewrite  ^viewnews_(.+)$ index.php?action_viewnews_itemid_$1;
  35.     rewrite  ^viewthread_(.+)$ index.php?action_viewthread_tid_$1;
  36.     rewrite  ^index([\.a-zA-Z0-9]*)$ index.php;
  37.     rewrite  ^html/([0-9]+)/viewnews_itemid_([0-9]+)\.html$ index.php?action_viewnews_itemid_$2;
  38.  
  39.     rewrite  ^/([0-9]+)/spacelist(.+)$ /index.php?uid/$1/action/spacelist/type$2;
  40.     rewrite  ^/([0-9]+)/viewspace(.+)$ /index.php?uid/$1/action/viewspace/itemid$2;
  41.     rewrite  ^/([0-9]+)/viewbbs(.+)$ /index.php?uid/$1/action/viewbbs/tid$2;
  42.     rewrite  ^/([0-9]+)/(.*)$ /index.php?uid/$1/$2;
  43.     rewrite  ^/([0-9]+)$ /index.php?uid/$1;
  44.  
  45.     rewrite  ^/action(.+)$ /index.php?action$1;
  46.     rewrite  ^/category(.+)$ /index.php?action/category/catid$1;
  47.     rewrite  ^/viewnews(.+)$ /index.php?action/viewnews/itemid$1;
  48.     rewrite  ^/viewthread(.+)$ /index.php?action/viewthread/tid$1;
  49.     rewrite  ^/mygroup(.+)$ /index.php?action/mygroup/gid$1;
  50. # 归档目录的默认首页设置
  51.         location /archiver/ {
  52.             index index.html;
  53.         }
  54.         location ~ .*\.php?$ {
  55.             include  conf/fcgi.conf;
  56.         }
  57.         location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
  58.             access_log  off;
  59.         }
  60.     }

用 tmpfs 提升性能
mkdir /tmpfs
在 /etc/fstab 中加入
tmpfs /tmpfs tmpfs size=256m,mode=1777 0 0

mount -a

创建相关目录
vi /usr/local/sbin/mkdir.sh

#/
bin
/
sh

 

mkdir
/
tmpfs
/
nginx


chown
-
R

nobody
:
nobody
/
tmpfs
/
nginx


chmod
-
R

1777
/
tmpfs
/
nginx

 

mkdir
/
tmpfs
/
eaccelerator


chown
-
R

nobody
:
nobody
/
tmpfs
/
eaccelerator


chmod
-
R

1777
/
tmpfs
/
eaccelerator

 

I
=
"
0 1 2 3 4 5 6 7 8 9 a b c d e f
"


for

acm

in
$
I
;

do


for

x

in
$
I
;

do


mkdir
-
p
/
tmpfs
/
phpsession
/$
acm
/$
x
;

done
;

done


chown
-
R

nobody
:
nobody
/
tmpfs
/
phpsession


chmod
-
R

1777
/
tmpfs
/
phpsession

chmod +x /usr/local/sbin/mkdir.sh
mkdir.sh

启动 PHP 和 Nginx
/usr/local/php-fcgi/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 32 -u nobody -g nobody -f /usr/local/php-fcgi/bin/php
监听在 127.0.0.1 的 10080 端口并开启 32 个进程,使用和 Nginx 一样的 nobody 用户。(PHP5 的执行程序是 php-cgi)
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
重启 PHP 进程可以先 killall php 再启动。
重启 Nginx
kill -HUP `cat /var/run/nginx.pid`

清除超过一小时没有被访问到的 eAccelerator 缓存文件和创建时间超过一小时的 php session 文件,防止占满空间。
vi /etc/crontab
0 * * * * root find /tmpfs/eaccelerator -type f -amin +60 -exec rm {} \;
0 * * * * root find /tmpfs/phpsession -type f -cmin +60 -exec rm {} \;

配置开机自启动
vi /etc/rc.local
/usr/local/sbin/mkdir.sh
/usr/local/php-fcgi/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 32 -u nobody -g nobody -f /usr/local/php-fcgi/bin/php
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

方便重启 Nginx
vi ~/.bashrc
alias nginx='kill -HUP `cat /var/run/nginx.pid`'

source ~/.bashrc

 

----------------------------------------------------------------------------------------

Nginx
是俄罗斯人编写的十分轻量级的HTTP服务器,以事件驱动的方式编写,所以有非常好的性能,同时也是一个非常高效的反向代理、负载平衡。其拥有匹配Lighttpd的性能,同时还没有Lighttpd的内存泄漏问题,而且Lighttpd的mod_proxy也有一些问题并且很久没有更新。

因此我打算用其替代Apache应用于Linux
服务器上。但是Nginx并不支持cgi方式运行,原因是可以减少因此带来的一些程序上的漏洞。那么我们必须使用FastCGI方式来执行PHP程序。

下面是我成功地配置Nginx + PHP5 FastCGI的过程

 

首先安装或编译Nginx。

安装Nginx

源码包可以在官方主页
上下载。Ubuntu 7.10可以直接通过apt安装,也可以从这里下载
最新的deb包:

sudo apt-get install nginx

如果要自己编译的话,需要确保自己已经有编译器和PCRE的库(用于Nginx的rewrite模块,如果不需要这个模块可以在configure时使用./configure –without-rewrite)。编译方法如下:

wget http://sysoev.ru/nginx/nginx-0.5.34.tar.gz
tar zxvf nginx-0.5.34.tar.gz
cd nginx-0.5.34
./configure #默认配置安装路径为/usr/local/nginx 可以追加--prefix=/usr设置到/usr
make && make install  # install要求有root权限

Ubuntu安装之后的文件结构大致为:

  • 所有的配置文件都在/etc/nginx下,并且每个虚拟主机已经安排在了/etc/nginx/sites-available下
  • 程序文件在/usr/sbin/nginx
  • 日志放在了/var/log/nginx中
  • 并已经在/etc/init.d/下创建了启动脚本nginx
  • 默认的虚拟主机的目录设置在了/var/www/nginx-default

而自己利用默认配置编译的,则放在/usr/local/nginx下,以下是目录结构:

  • /usr/local/nginx/conf 配置目录
  • /usr/local/nginx/html 默认的网站根目录
  • /usr/local/nginx/logs 日志和pid文件目录
  • /usr/local/nginx/sbin 执行文件目录

下面可以启动nginx来看看效果(请确保80端口没有其他服务在使用):
Ubuntu请运行:

sudo /etc/init.d/nginx start

其他请运行:

/usr/local/nginx/sbin/nginx

然后就可以通过http://localhost/来看看效果了。

要配置nginx的自动运行,可以将/usr/local/nginx/sbin/nginx添加到/etc/rc.local中,Ubuntu可以执行

update-rc.d nginx defaults

安装PHP5

至于如何在Linux
上安装PHP,有很多文章,甚至很多平台上都有现成的软件包,无需自己编译。在这里我们需要的是cgi方式的php。Ubuntu下可以直接运行:

sudo apt-get install php-cgi

并且可以根据自己的情况安装一些字节码优化和缓存的扩展,如eaccelerator、apc、xcache等。

PHP5的CGI方式的一大优势是内置了FastCGI的支持,只需指明绑定的地址和端口参数便可以以FastCGI的方式运行,如下:

php-cgi -b 127.0.0.1:9000

如何配置其与nginx一起运行呢?

配置Nginx的PHP FastCGI

请将以下内容保存为fastcgi_params文件,保存于/usr/local/nginx/conf下(Ubuntu可保存于/etc/nginx下),他为我们的FastCGI模块设置了基本的环境变量:

#fastcgi_params
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

请特别注意加粗的一行,PHP-CGI特别需要此行信息来确定PHP文件的位置。

另外需要在PHP-CGI的配置文件(Ubuntu 上此配置文件位于/etc/php5/cgi/php.ini)中,打开cgi.fix_pathinfo选项:

cgi.fix_pathinfo=1;

这样php-cgi方能正常使用SCRIPT_FILENAME这个变量。

接下来在nginx的配置中针对php文件配置其利用FastCGI进程来执行:

server {
    index index.php;
    root  /usr/local/nginx/html;

    location ~ .*.php$ {
        include /usr/local/nginx/conf/fastcgi_params;  #请根据自己保存的路径进行设置
        fastcgi_index index.php;
        fastcgi_pass  127.0.0.1:9000; #请根据自己的FastCGI绑定的地址和端口进行配置
    }
}

通知Nginx重新载入配置:

kill -HUP `cat /usr/local/nginx/logs/nginx.pid`

Ubuntu用户可以使用init脚本:sudo /etc/init.d/nginx reload

然后启动php-cgi -b 127.0.0.1:9000

假设你在文档根目录放了index.php,并包含“”的内容,现在再看http://localhost/index.php便应该能看到php的调试信息了。

配置php进程

直接使用php-cgi的FastCGI运行方式有两个问题(貌似应该有解决方案,如果知道的话可以教教我):

  1. 如果进程崩溃,难以配置重新启动
  2. 单进程的效率低

因此,我们可以利用Lighttpd的spawn-fcgi来控制进程的运行。获得spawn-fcgi的方法如下:

wget http://www.lighttpd.net/download/lighttpd-1.4.18.tar.bz2 #获取Lighttpd的源码包
tar -xvjf lighttpd-1.4.18.tar.bz2
cd lighttpd-1.4.18
./configure  #编译
make
cp src/spawn-fcgi /usr/local/bin/spawn-fcgi #取出spawn-fcgi的程序

下面我们就可以使用 spawn-fcgi 来控制php-cgi的FastCGI进程了

/usr/local/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 5 -u www-data -g www-data -f /usr/bin/php-cgi

参数含义如下

  • -f <fcgiapp> 指定调用FastCGI的进程的执行程序位置,根据系统上所装的PHP的情况具体设置
  • -a <addr> 绑定到地址addr
  • -p <port> 绑定到端口port
  • -s <path> 绑定到unix socket的路径path
  • -C <childs> 指定产生的FastCGI的进程数,默认为5(仅用于PHP)
  • -P <path> 指定产生的进程的PID文件路径
  • -u和-g FastCGI使用什么身份(-u 用户 -g 用户组)运行,Ubuntu下可以使用www-data,其他的根据情况配置,如nobody、apache等

然后我们可以将这行代码加入到/etc/rc.local文件底部,这样系统启动的时候也可以同时启动PHP的FastCGI进程

发表在 web server | 标签为 , , | Nginx PHP FastCGI 安装配置记录已关闭评论

Nginx+PHP+MySQL双机互备、全自动切换方案

在生产应用中,某台“Nginx+PHP+MySQL”接口数据服务器,扮演的角色十分重要,如果服务器硬件或Nginx、MySQL发生故障,而短时间内无法恢复,后果将非常严重。为了避免单点故障,我设计了此套方案,编写了failover.sh脚本,实现了双机互备、全自动切换,故障转移时间只需几十秒。

  一、双机互备、全自动切换方案:
  1、拓扑图:

点击查看原图

2、解释:
  (1)、假设外网域名blog.s135.com解析到外网虚拟IP 72.249.146.214上,内网hosts设置db10对应内网虚拟IP 192.168.146.214

  (2)、默认情况下,由主机绑定内、外网虚拟IP,备机作为备份,当主机的MySQL、Nginx或服务器出现故障无法访问时,备机会自动接管内、外网虚拟IP。两台服务器都启动负责监控、自动切换虚拟IP的守护进程/usr/bin/nohup /bin/sh /usr/local/webserver/failover/failover.sh 2>&1 > /dev/null &

  (3)、主机和备机上的MySQL服务器互为主从,互相同步。在主机处于活动状态(即由主机绑定虚拟IP)时,读写主机的MySQL,写到主机的数据会同步到备机;在备机处于活动状态时,读写备机的MySQL,写到备机的数据会同步到主机(如果主机上的MySQL死掉暂时无法同步,主机上的MySQL恢复后,数据会自动从备机上同步过来,反之亦然)。

  (4)、主机处于活动状态时,每20秒会把/data0/htdocs/(网页、程序、图片存放目录)、/usr/local/webserver/php/etc/(php.ini等配置文件目录)、/usr/local/webserver/nginx/conf/(Nginx配置文件目录)三个目录下的文件通过rsync推送到备机服务器上的对应目录(增量推送,两台服务器上一样的文件不会重复推送),反之如果备机处于活动状态时,每20秒会尝试把文件推送到主机。rsync的配置文件见两台服务器的/etc/rsyncd.conf,rsync守护进程的启动命令为rsync --daemon

  3、自动切换流程
  (1)、主机默认绑定内、外网虚拟IP,当主机的MySQL、Nginx无法访问或服务器宕机,主机上的failover.sh守护进程会自动摘除自己绑定的内、外网虚拟IP(如果主机上的failover.sh死掉,无法摘除自己绑定的虚拟IP也没关系),备机上的failover.sh守护进程会自动接管备机原来绑定的内、外网虚拟IP,并发送ARPing包给内、外网网关更新MAC,强行接管。

  (2)、备机绑定虚拟IP后,会发送ARPing包给内、外网网关,通知网关更新虚拟IP的MAC地址为备机的MAC地址,从而保证了切换后能够通过虚拟IP及时访问到备机。

  (3)、如果主机的MySQL、Nginx启动起来,全部恢复正常访问,主机上的failover.sh守护进程会检测主机上的MySQL数据是否已经完全从备机上同步过来。如果同步延迟时间为0,主机会自动接管内、外网虚拟IP,并发送ARPing包给内、外网网关,而备机也会自动摘除内、外网虚拟IP。

  (4)、整个切换流程均由failover.sh自动完成,无需人工处理。 

  4、注意事项(很重要):
  (1)、crontab里的文件没有做自动同步,如果修改,需要手工在两台服务器上都做修改。

  (2)、/data0/htdocs/目录内任何用ln -s建立的软连接,rsync不会自动同步,如果在一台服务器上建了软连接,需要手工在另外一台服务器上也建相同的软连接。

  (3)、如果要删除/data0/htdocs/目录内的某些文件或目录,需要先删除处于活动状态(即绑定了虚拟IP)服务器上的文件或目录,再删除处于备用状态服务器上的文件或目录。

  (4)、除了/data0/htdocs/(网页、程序、图片存放目录)、/usr/local/webserver/php/etc/(php.ini等配置文件目录)、/usr/local/webserver/nginx/conf/(Nginx配置文件目录)三个目录之外的其他配置修改,需要在两台服务器上都做修改。

二、配置文档与脚本:
  1、主机、备机两台服务器的rsync配置(配置相同)
  (1)、rsync配置文件
 

vi /etc/rsyncd.conf

  输入一些内容并保存:
 

引用
uid = root
gid = root
use chroot = no
max connections = 20
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log

[data0_htdocs]
path = /data0/htdocs/
ignore errors
read only = no
hosts allow = 192.168.146.0/24
hosts deny = 0.0.0.0/32

[php_etc]
path = /usr/local/webserver/php/etc/
ignore errors
read only = no
hosts allow = 192.168.146.0/24
hosts deny = 0.0.0.0/32

[nginx_conf]
path = /usr/local/webserver/nginx/conf/
ignore errors
read only = no
hosts allow = 192.168.146.0/24
hosts deny = 0.0.0.0/32

  (2)、启动rsync守护进程
 

/usr/bin/rsync --daemon

  2、两台MySQL互为主从的配置
  这里就不详细写出互为主从的配置过程了,如果不懂的朋友可以在Google上搜一下。有一点需要指出,my.cnf配置文件中请加上skip-name-resolve参数,使用IP来进行MySQL帐号验证。

  3、主机、备机两台服务器负载监控、虚拟IP自动切换的failover.sh守护进程
  (1)、启动failover.sh守护进程(为了开机能够自动运行,请将以下语句添加到/etc/rc.local文件中):
 

/usr/bin/nohup /bin/sh /usr/local/webserver/failover/failover.sh 2>&1 > /dev/null &

  (2)、停止failover.sh守护进程:
 

ps -ef | grep failover.sh

  会显示以下信息:
  root     15428     1  0 Nov17 ?        00:00:03 /bin/sh /usr/local/webserver/failover/failover.sh
  root     20123  6878  0 16:16 pts/2    00:00:00 grep failover.sh


  然后杀死failover.sh的进程:
 

kill -9 15428

  (3)、failover.sh代码内容(请注意其中的type设置,主机设为master,备机设为slave
):
 

#!/bin/sh
LANG=C
date=$(date -d "today" +"%Y-%m-%d %H:%M:%S")

#---------------配置信息(开始)---------------
#类型:主机设为master,备机设为slave
type="master"

#主机、备机切换日志路径
logfile="/var/log/failover.log"

#MySQL可执行文件地址,例如/usr/local/mysql/bin/mysql;MySQL用户名;密码;端口
mysql_bin="/usr/local/webserver/mysql/bin/mysql"
mysql_username="root"
mysql_password="123456"
mysql_port="3306"

#内网网关
gateway_eth0="192.168.146.1"

#主机内网真实IP
rip_eth0_master="192.168.146.213"

#备机内网真实IP
rip_eth0_slave="192.168.146.215"

#主机、备机内网共用的虚拟IP
vip_eth0_share="192.168.113.214"

#外网网关
gateway_eth1="72.249.146.193"

#主机外网真实IP
rip_eth1_master="72.249.146.213"

#备机外网真实IP
rip_eth1_slave="72.249.146.215"

#主机、备机外网共用的虚拟IP
vip_eth1_share="72.249.146.214"
#---------------配置信息(结束)---------------

#绑定内、外网虚拟IP
function_bind_vip()
{
   /sbin/ifconfig eth0:vip ${vip_eth0_share} broadcast ${vip_eth0_share} netmask 255.255.255.255 up
   /sbin/route add -host ${vip_eth0_share} dev eth0:vip
   /sbin/ifconfig eth1:vip ${vip_eth1_share} broadcast ${vip_eth1_share} netmask 255.255.255.255 up
   /sbin/route add -host ${vip_eth1_share} dev eth1:vip
   /usr/local/webserver/php/sbin/php-fpm reload
   kill -USR1 `cat /usr/local/webserver/nginx/logs/nginx.pid`
   /sbin/service crond start
}

#解除内、外网虚拟IP
function_remove_vip()
{
   /sbin/ifconfig eth0:vip ${vip_eth0_share} broadcast ${vip_eth0_share} netmask 255.255.255.255 down
   /sbin/ifconfig eth1:vip ${vip_eth1_share} broadcast ${vip_eth1_share} netmask 255.255.255.255 down
   /sbin/service crond stop
}

#主机向备机推送文件的函数
function_rsync_master_to_slave()
{
   /usr/bin/rsync -zrtuog /data0/htdocs/ ${rip_eth0_slave}::data0_htdocs/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/php/etc/ ${rip_eth0_slave}::php_etc/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/nginx/conf/ ${rip_eth0_slave}::nginx_conf/ > /dev/null 2>&1
}

#备机向主机推送文件的函数
function_rsync_slave_to_master()
{
   /usr/bin/rsync -zrtuog /data0/htdocs/ ${rip_eth0_master}::data0_htdocs/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/php/etc/ ${rip_eth0_master}::php_etc/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/nginx/conf/ ${rip_eth0_master}::nginx_conf/ > /dev/null 2>&1
}

#虚拟IP ARPing
function_vip_arping()
{
 /sbin/arping -I eth0 -c 3 -s ${vip_eth0_share} ${gateway_eth0} > /dev/null 2>&1
 /sbin/arping -I eth1 -c 3 -s ${vip_eth1_share} ${gateway_eth1} > /dev/null 2>&1  
}

while true
do
   #用HTTP协议检查虚拟IP
   if (curl -m 30 -G 
http://$
{vip_eth1_share}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${vip_eth0_share}" -e"show slave status\G" > /dev/null 2>&1)
   then
   #取得与内网VIP绑定的服务器内网IP
   eth0_active_server=$(${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${vip_eth0_share}" -e"show slave status\G" | grep "Master_Host" | awk -F ': ' '{printf $2}')
   
   #如果内网VIP=主机内网IP(主机MySQL中的Master_Host显示的是备机的域名或IP),且本机为主机
   if [ "${eth0_active_server}" = "${rip_eth0_slave}" ] && [ "${type}" = "master" ]
   then
     function_rsync_master_to_slave
     function_vip_arping    
   #如果内网VIP=备机内网IP(备机MySQL中的Master_Host显示的是主机的域名或IP)
   elif [ "${eth0_active_server}" = "${rip_eth0_master}" ]
   then
     if (curl -m 30 -G 
http://$
{rip_eth1_master}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${rip_eth0_master}" -e"show slave status\G" | grep "Seconds_Behind_Master: 0" > /dev/null 2>&1)
     then
       #如果主机能够访问,数据库同步无延迟,且本机就是主机,那么由本机绑定虚拟IP
       if [ "${type}" = "master" ]
       then
         #如果本机为主机
      function_bind_vip
         function_vip_arping
         echo "${date} 主机已绑定虚拟IP!(Type:1)" >> ${logfile}
       else
         #如果本机为备机
      function_remove_vip
         echo "${date} 备机已去除虚拟IP!(Type:2)" >> ${logfile}
       fi
     else
       if [ "${type}" = "slave" ]
       then
         #如果本机为备机
      function_rsync_slave_to_master        
         function_vip_arping
       fi      
     fi
   fi
   else
       #虚拟IP无法访问时,判断主机能否访问
       if (curl -m 30 -G 
http://$
{rip_eth1_master}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${rip_eth0_master}" -e"show slave status\G" > /dev/null 2>&1)
       then
           #如果主机能够访问,且本机就是主机,那么由本机绑定虚拟IP
           if [ "${type}" = "master" ]
           then
               function_bind_vip
               function_vip_arping
               echo "${date} 主机已绑定虚拟IP!(Type:3)" >> ${logfile}
           else
               function_remove_vip
               echo "${date} 备机已去除虚拟IP!(Type:4)" >> ${logfile}
           fi
   elif (curl -m 30 -G 
http://$
{rip_eth1_slave}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${rip_eth0_slave}" -e"show slave status\G" > /dev/null 2>&1)
       then
           #如果主机不能访问而备机能够访问,且本机就是备机,那么由备机绑定虚拟IP
           if [ "${type}" = "slave" ]
           then
               function_bind_vip
               function_vip_arping
               echo "${date} 备机已绑定虚拟IP!(Type:5)" >> ${logfile}
           else
               function_remove_vip
               echo "${date} 主机已去除虚拟IP!(Type:6)" >> ${logfile}
           fi
       else
           echo "${date} 主机、备机全部无法访问!(Type:7)" >> ${logfile}
       fi
   fi
   #每次循环暂停20秒(即间隔20秒检测一次)
   sleep 20
done

发表在 web server | 标签为 , | Nginx+PHP+MySQL双机互备、全自动切换方案已关闭评论

网易开通了一个开源软件的镜像站点

网易开通了一个开源软件的镜像站点,网址为:

  http://mirrors.163.com/

  提供的镜像有:

  1、Linux及BSD发行版镜像:FreeBSD、OpenBSD、RedHat、archlinux、centos、debian、fedora、gentoo、trixbox、ubuntu等。

  2、开源软件镜像:eclipse可扩展开发平台、防火墙、openfiler网络存储管理工具。

  该镜像目前只有一台杭州电信的服务器,网通用户访问可能会比较慢。

 


  如果您安装 CentOS 5.2 系统的服务器位于电信机房,您可以修改/etc/yum.repos.d/CentOS-Base.repo文件,将它的yum源更改成网易的镜像,代替国外的镜像,以便获取更快的下载速度。

  您可以按照以下步骤从 blog.s135.com

下载修改后的 CentOS-Base.repo 文件到您的服务器。

 

cd /etc/yum.repos.d/
mv CentOS-Base.repo CentOS-Base.repo.bak
wget http://blog.s135.com/soft/linux/centos/5.2/CentOS-Base.repo

 




  附:修改后的 CentOS-Base.repo 文件内容如下:

 

  1. # CentOS-Base.repo

  2. #

  3. # This file uses a new mirrorlist system developed by Lance Davis for CentOS.

  4. # The mirror system uses the connecting IP address of the client and the

  5. # update status of each mirror to pick mirrors that are updated to and

  6. # geographically close to the client.  You should use this for CentOS updates

  7. # unless you are manually picking other mirrors.

  8. #

  9. # If the mirrorlist= does not work for you, as a fall back you can try the 

  10. # remarked out baseurl= line instead.

  11. #

  12. #

      
  13.   
  14. [base]   
  15. name=CentOS-$releasever - Base
  16. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os

  17. #baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/

      
  18. baseurl=http:
    //mirrors.163.com/centos/$releasever/os/$basearch/

      
  19. gpgcheck=1   
  20. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  21.  
  22. #released updates 

      
  23. [updates]   
  24. name=CentOS-$releasever - Updates
  25. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates

  26. #baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/

      
  27. baseurl=http:
    //mirrors.163.com/centos/$releasever/updates/$basearch/

      
  28. gpgcheck=1   
  29. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  30.  
  31. #packages used/produced in the build but not released

      
  32. [addons]   
  33. name=CentOS-$releasever - Addons
  34. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=addons

  35. #baseurl=http://mirror.centos.org/centos/$releasever/addons/$basearch/

      
  36. baseurl=http:
    //mirrors.163.com/centos/$releasever/addons/$basearch/

      
  37. gpgcheck=1   
  38. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  39.  
  40. #additional packages that may be useful

      
  41. [extras]   
  42. name=CentOS-$releasever - Extras
  43. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras

  44. #baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/

      
  45. baseurl=http:
    //mirrors.163.com/centos/$releasever/extras/$basearch/

      
  46. gpgcheck=1   
  47. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  48.  
  49. #additional packages that extend functionality of existing packages

      
  50. [centosplus]   
  51. name=CentOS-$releasever - Plus
  52. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus

  53. #baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/

      
  54. baseurl=http:
    //mirrors.163.com/centos/$releasever/centosplus/$basearch/

      
  55. gpgcheck=1   
  56. enabled=0   
  57. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5

      

发表在 info | 网易开通了一个开源软件的镜像站点已关闭评论

亿级数据的高并发通用搜索引擎架构设计

曾经在七月,写过一篇文章──《基于Sphinx+MySQL的千万级数据全文检索(搜索引擎)架构设计
》,前公司的分类信息搜索基于此架构,效果明显,甚至将很大一部分带Where条件的MySQL SQL查询,都改用了Sphinx+MySQL搜索。但是,这套架构仍存在局限:一是MySQL本身的并发能力有限,在200~300个并发连接下,查询和更新就比较慢了;二是由于MySQL表的主键与Sphinx索引的ID一一对应,从而无法跨多表建立整站查询,而且新增加类别还得修改配置文件,比较麻烦;三是因为和MySQL集成,无法发挥出Sphinx的优势。

  最近,我设计出了下列这套最新的搜索引擎架构,目前已经写出“搜索查询接口”和“索引更新接口”的beta版。经测试,在一台“奔腾四 3.6GHz 双核CPU、2GB内存”的普通PC机,7000万条索引记录的条件下,“搜索查询接口”平均查询速度为0.0XX秒(查询速度已经达到百度、谷歌、搜狗、中国雅虎等搜索引擎的水平,详见文章末尾的“附2”),并且能够支撑高达5000的并发连接;而“索引更新接口”进行数据分析、入队列、返回信息给用户的全过程,高达1500 Requests/Sec。

  “队列控制器”这一部分是核心,它要控制队列读取,更新MySQL主表与增量表,更新搜索引擎数据存储层Tokyo Tyrant,准实时(1分钟内)完成更新Sphinx增量索引,定期合并Sphinx索引。我预计在这周写出beta版。

点击查看原图

  图示说明:

  1、搜索查询接口:
  ①、Web应用服务器通过HTTP POST/GET方式,将搜索关键字等条件,传递给搜索引擎服务器的search.php接口;
  ②③、search.php通过Sphinx的API(我根据最新的Sphinx 0.9.9-rc1 API,改写了一个C语言的PHP扩展sphinx.so),查询Sphinx索引服务,取得满足查询条件的搜索引擎唯一ID(15位搜索唯一ID:前5位类别ID+后10位原数据表主键ID)列表;
  ④⑤、search.php将这些ID号作为key,通过Memcache协议一次性从Tokyo Tyrant中mget取回ID号对应的文本数据。
  ⑥⑦、search.php将搜索结果集,按查询条件,进行摘要和关键字高亮显示处理,以JSON格式或XML格式返回给Web应用服务器。

  2、索引更新接口:
  ⑴、Web应用服务器通过HTTP POST/GET方式,将要增加、删除、更新的内容告知搜索服务器的update.php接口;
  ⑵、update.php将接收到的信息处理后,写入TT高速队列(我基于Tokyo Tyrant做的一个队列系统);
  注:这两步的速度可达到1500次请求/秒以上,可应对6000万PV的搜索索引更新调用。

  3、搜索索引与数据存储控制:
  ㈠、“队列控制器”守护进程从TT高速队列中循环读取信息(每次50条,直到末尾);
  ㈡、“队列控制器”将读取出的信息写入搜索引擎数据存储层Tokyo Tyrant;
  ㈢、“队列控制器”将读取出的信息异步写入MySQL主表(这张主表按500万条记录进行分区,仅作为数据永久性备份用);
  ㈣、“队列控制器”将读取出的信息写入MySQL增量表;
  ㈤、“队列控制器”在1分钟内,触发Sphinx更新增量索引,Sphinx的indexer会将MySQL增量表作为数据源,建立增量索引。Sphinx的增量索引和作为数据源的MySQL增量表成对应关系;
  ㈥、“队列控制器”每间隔3小时,短暂停止从TT高速队列中读取信息,并触发Sphinx将增量索引合并入主索引(这个过程非常快),同时清空MySQL增量表(保证了MySQL增量表的记录数始终只有几千条至几十万条,大大加快Sphinx增量索引更新速度),然后恢复从TT高速队列中取出数据,写入MySQL增量表。

  本架构使用的开源软件:

  1、Sphinx 0.9.9-rc1
  2、Tokyo Tyrant 1.1.9
  3、MySQL 5.1.30
  4、Nginx 0.7.22
  5、PHP 5.2.6

  本架构自主研发的程序:

  1、搜索查询接口(search.php)
  2、索引更新接口(update.php)
  3、队列控制器
  4、Sphinx 0.9.9-rc1 API的PHP扩展(sphinx.so)
  5、基于Tokyo Tyrant的高速队列系统

 


  附1:MySQL FullText、Lucene搜索、Sphinx搜索的第三方对比结果:

  1、查询速度:
  MySQL FullText最慢,Lucene、Sphinx查询速度不相上下,Sphinx稍占优势。
  点击查看原图

  2、建索引速度:
  Sphinx建索引速度是最快的,比Lucene快9倍以上。因此,Sphinx非常适合做准实时搜索引擎。

  3、详细对比数据见以下PDF文档: 

     

发表在 article | 标签为 , | 亿级数据的高并发通用搜索引擎架构设计已关闭评论

易趣网淘宝网5年交战史

自2003年阿里巴巴旗下淘宝网上线以来,易趣网与淘宝网的战斗一直没有停止过。从一下淘宝网与易趣网的交战历史,可以看出在斗争中成长的两大C2C网站,也可以看到中国C2C发展的一丝脉络。
 

 

  易趣淘宝交战史:
 

 

  1999年8月 两位哈佛商学院毕业生,邵亦波和谭海音,在中国上海创办易趣网。成立之初,公司在上海一个两居室的民居内办公。两位创始人邵亦波和谭海英是当时仅有的两名员工。
 

 

  2000年7月 易趣推出个人网上开店服务,短短一周即吸引5,000多位网友“尝鲜”,此举切实地培养起中国首批真正靠网络来赚钱的网民。
 

 

  2001年7月 易趣宣布网站开始对卖家登录物品收取登录费。
 

 

  2002年9月 易趣开始对卖家网上商品成交后收取商品交易服务费。易趣开始进入了电子商务平台非免费运营的阶段,也标志着中国电子商务的发展的一个里程碑。
 

 

  2003年6月,eBay投资1.5亿美金,收购易趣(美国)公司的股份。易趣公司和eBay展开全面合作。
 

 

  2003年5月10日,淘宝网上线。同时宣布全站免费。
 

 

  2003年,电子商务巨头美国eBay在这个时候投资1.8亿美元,接管易趣,
 

 

  2003年,淘宝网上线。
 

 

  2003年,eBay将易趣网更名为eBay易趣。
 

 

  2003年10月,淘宝网发布了“支付宝”服务。
 

 

  2004年2月2日,易趣正式调低了自己的商品登录费用,这是易趣采取收费策略后第一次“降价让利”。
 

 

  2004年4月,yahoo与新浪合作的一拍网成立。
 

 

  2004年9月17日,易趣与eBay正式完成对接。
 

 

  2005年4月,淘宝网和搜狐宣布结成战略联盟,紧接着在5月,成为MSN中国拍卖频道的合作伙伴。
 

 

  2005年5月1日易趣网再次宣布登录费、月租费下调;6月9日的“安付通”升级。
 

 

  2005年7月11日,贝宝(PayPal China)中国网站正式开通,标志着贝宝正式登陆中国市场。
 

 

  2005年10月20日,淘宝网宣布将继续免费三年。
 

 

  2006年5月10日,正式推出全新B2C(企业对个人)业务——淘宝商城。并同时推出竞价排名服务“招财进宝”,在宣布继续免费3年之后,这项有偿增值服务被认为是“变相收费”,成为淘宝成立以来最大的一次改革。
 

 

  2006年12月,eBay与TOM在线合作携手组建一家合资公司,结合双方的优势资源,专为中国市场打造一个本地化的交易平台。TOM在线CEO王雷雷同时兼任合资公司CEO。
 

 

  2007年7月,eBay和TOM联手打造的全新交易平台—易趣正式上线启用。
 

 

  2008年4月,淘宝B2C平台正式上线。与此同时,淘宝将对该B2C的“品牌/商城”业务收费,此举被认为是提前收费,违反了淘宝2005年10月宣布的继续免费3年的承诺。同月,淘宝出现轰动一时的“评价门”事件。
 

 

  2008年4月14日,易趣针对老卖家、其他网站卖家和新手卖家发起一轮“易趣卖家共成长计划”,根据不同层面的卖家需求,提供从认证、培训到推广等各种免费且有效的资源支持,帮助这三类卖家在易趣上快速开店、稳步成长。凡是在易趣上开有店铺并提交了准确个人信息的卖家都可报名参加易趣这一成长计划。
 

 

  2008年5月5日,易趣宣布,用户到易趣上开店,易趣将终身免收包括高级店铺和超级店铺在内的店铺费,并免收商品登录费、店铺使用费等传统收费项目。这意味着,易趣这一国内首家收费的C2C网站,在经过若干年的收费探索后,开始转向全平台免费使用的模式。

发表在 info | 易趣网淘宝网5年交战史已关闭评论

C++ socket 编程

使用socket写代码主要是要看自己的需求是什么。
如果通信时,内容很重要就要使TCP方式。
如果用户数太多,可能就要使用UDP方式了。
在TCP模式下,最简单的方式就是这样的,使阻塞方式:
服务端:
1.初始化socket环境,创建socket
2.梆定一个端口
3.开始监听
4.接收客户端
5.接收到客户端之后,使用这个socket来与这个客户通信

#include "stdAfx.h"
#include <winsock2.h>
#include <mswsock.h>
#include <iostream>

using namespace std;

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")

DWORD IniSOCKDLL()
{
WORD wVersionRequested;
WSADATA wsaData;
int err=0;

wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
return err;
}

int main(int argc, char* argv[])
{
cout<<"程序开始"<<endl;
IniSOCKDLL();
SOCKET ss=WSASocket(AF_INET,
   SOCK_STREAM,
   0,
   NULL,
   0,
   NULL);

SOCKADDR_IN addr;
int len;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(1002);
len=sizeof(addr);

bind(ss , (PSOCKADDR)&addr , len);
listen(ss,5);

SOCKET sc=accept(ss,(PSOCKADDR)&addr,&len);
char buff[1024];
ZeroMemory(buff,1024);
recv(sc,buff,1024,0);
cout<<buff<<endl;

ZeroMemory(buff,1024);
memcpy(buff,"123",3);
send(sc,buff,3,0);

closesocket(sc);
closesocket(ss);
return 0;
}

客户端:
1.初始化socket环境,创建socket
2.连接服务端
3.开启一个线程来接收数据
4.使用send直接发数据包

#include "stdAfx.h"
#include <winsock2.h>
#include <mswsock.h>
#include <iostream>

using namespace std;

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")

DWORD IniSOCKDLL()
{
WORD wVersionRequested;
WSADATA wsaData;
int err=0;

wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
return err;
}

int main(int argc, char* argv[])
{
IniSOCKDLL();
SOCKET sc=WSASocket(AF_INET,
   SOCK_STREAM,
   0,
   NULL,
   0,
   NULL);

SOCKADDR_IN addr;
int len;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(1002);
len=sizeof(addr);

connect(sc, (struct sockaddr *)&addr, len);

char buff[1024];
ZeroMemory(buff,1024);
memcpy(buff,"123",3);
send(sc,buff,3,0);

recv(sc,buff,1024,0);
cout<<buff<<endl;

closesocket(sc);
return 0;
}

由这个我们可以做一个这样的模型:
为每个阻塞函数开一个线程,让它来处理。
这就要留意退出的时候把这一些线程给关闭。

 

当然TCP方式的模型还有事件选择模型。
就是把所有的网络事件和我们的一个程序里定义的事件梆定。
这个有它的好处,可能可以让我们更好的写一个线程来管理
接收与发送。
现在来讲一下一个完成端口模型。

完成端口

一个完成端口其实就是一个通知队列,由操作系统把已经完成的重叠I/O请求的通知
放入其中。当某项I/O操作一旦完成,某个可以对该操作结果进行处理的工作者线程
就会收到一则通知。而套接字在被创建后,可以在任何时候与某个完成端口进行关
联。

步骤:
1、创建一个空的完成端口;
2、得到本地机器的CPU个数;
3、开启CPU*2个工作线程(又名线程池),全部都在等待完成端口的完成包;
4、创建TCP的监听socket,使用事件邦定,创建监听线程;
5、当有人连接进入的时候,将Client socket保存到一个我们自己定义的关键键,
    并把它与我们创建的完成端口关联;
6、使用WSARecv和WSASend函数投递一些请求,这是使用重叠I/O的方式;
7、重复5~6;

注:1、重叠I/O的方式中,接收与发送数据包的时候,一定要进行投递请求这是
    它们这个体系结构的特点
    当然,在完成端口方式中,不是直接使用的WSARecv和WSASend函数进行请求
    的投递的。而是使用的ReadFile,Write的方式
   2、完成端口使用了系统内部的一些模型,所以我们只要按照一定的顺序调用就
    可以完成了。
   3、完成端口是使用在这样的情况下,有成千上万的用户连接的时候,它能够
    保证性能不会降低。

#include <winsock2.h>
#include <windows.h>
#include <stdio.h>

#define PORT 5150
#define DATA_BUFSIZE 8192

//关键项
typedef struct
{
   OVERLAPPED Overlapped;
   WSABUF DataBuf;
   CHAR Buffer[DATA_BUFSIZE];
   DWORD BytesSEND;
   DWORD BytesRECV;
} PER_IO_OPERATION_DATA, * LPPER_IO_OPERATION_DATA;

typedef struct
{
   SOCKET Socket;
} PER_HANDLE_DATA, * LPPER_HANDLE_DATA;

DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID);

void main(void)
{
   SOCKADDR_IN InternetAddr;
   SOCKET Listen;
   SOCKET Accept;
   HANDLE CompletionPort;
   SYSTEM_INFO SystemInfo;
   LPPER_HANDLE_DATA PerHandleData;
   LPPER_IO_OPERATION_DATA PerIoData;
   int i;
   DWORD RecvBytes;
   DWORD Flags;
   DWORD ThreadID;
   WSADATA wsaData;
   DWORD Ret;

   if ((Ret = WSAStartup(0x0202, &wsaData)) != 0)
   {
      printf("WSAStartup failed with error %d\n", Ret);
      return;
   }

   //打开一个空的完成端口

   if ((CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0)) == NULL)
   {
      printf( "CreateIoCompletionPort failed with error: %d\n", GetLastError());
      return;
   }

   // Determine how many processors are on the system.

   GetSystemInfo(&SystemInfo);

   // 开启cpu个数的2倍个的线程

   for(i = 0; i < SystemInfo.dwNumberOfProcessors * 2; i++)
   {
      HANDLE ThreadHandle;

      // Create a server worker thread and pass the completion port to the thread.

      if ((ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, CompletionPort,
         0, &ThreadID)) == NULL)
      {
         printf("CreateThread() failed with error %d\n", GetLastError());
         return;
      }

      // Close the thread handle
      CloseHandle(ThreadHandle);
   }

   //打开一个服务器socket

   if ((Listen = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0,
      WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
   {
      printf("WSASocket() failed with error %d\n", WSAGetLastError());
      return;
   }

   InternetAddr.sin_family = AF_INET;
   InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
   InternetAddr.sin_port = htons(PORT);

   if (bind(Listen, (PSOCKADDR) &InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR)
   {
      printf("bind() failed with error %d\n", WSAGetLastError());
      return;
   }

   if (listen(Listen, 5) == SOCKET_ERROR)
   {
      printf("listen() failed with error %d\n", WSAGetLastError());
      return;
   }

   //开始接收从客户端来的连接

   while(TRUE)
   {
      if ((Accept = WSAAccept(Listen, NULL, NULL, NULL, 0)) == SOCKET_ERROR)
      {
         printf("WSAAccept() failed with error %d\n", WSAGetLastError());
         return;
      }

      // 创建一个关键项用于保存这个客户端的信息,用户接收发送的重叠结构,
      // 还有使用到的缓冲区
      if ((PerHandleData = (LPPER_HANDLE_DATA) GlobalAlloc(GPTR,
         sizeof(PER_HANDLE_DATA))) == NULL)
      {
         printf("GlobalAlloc() failed with error %d\n", GetLastError());
         return;
      }

      // Associate the accepted socket with the original completion port.

      printf("Socket number %d connected\n", Accept);
      PerHandleData->Socket = Accept;

      //与我们的创建的那个完成端口关联起来,将关键项也与指定的一个完成端口关联
      if (CreateIoCompletionPort((HANDLE) Accept, CompletionPort, (DWORD) PerHandleData,
         0) == NULL)
      {
         printf("CreateIoCompletionPort failed with error %d\n", GetLastError());
         return;
      }

      // 投递一次接收,由于接收都需要使用这个函数来投递一个接收的准备

      if ((PerIoData = (LPPER_IO_OPERATION_DATA) GlobalAlloc(GPTR,          sizeof(PER_IO_OPERATION_DATA))) == NULL)
      {
         printf("GlobalAlloc() failed with error %d\n", GetLastError());
         return;
      }

      ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));
      PerIoData->BytesSEND = 0;
      PerIoData->BytesRECV = 0;
      PerIoData->DataBuf.len = DATA_BUFSIZE;
      PerIoData->DataBuf.buf = PerIoData->Buffer;

      Flags = 0;
      if (WSARecv(Accept, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,
         &(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
      {
         if (WSAGetLastError() != ERROR_IO_PENDING)
         {
            printf("WSARecv() failed with error %d\n", WSAGetLastError());
            return;
         }
      }
   }
}
//工作线程
DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID)
{
   HANDLE CompletionPort = (HANDLE) CompletionPortID;
   DWORD BytesTransferred;
   LPOVERLAPPED Overlapped;
   LPPER_HANDLE_DATA PerHandleData;
   LPPER_IO_OPERATION_DATA PerIoData;
   DWORD SendBytes, RecvBytes;
   DWORD Flags;
  
   while(TRUE)
   {
      //完成端口有消息来了
      if (GetQueuedCompletionStatus(CompletionPort, &BytesTransferred,
         (LPDWORD)&PerHandleData, (LPOVERLAPPED *) &PerIoData, INFINITE) == 0)
      {
         printf("GetQueuedCompletionStatus failed with error %d\n", GetLastError());
         return 0;
      }

      //是不是有人退出了

      if (BytesTransferred == 0)
      {
         printf("Closing socket %d\n", PerHandleData->Socket);

         if (closesocket(PerHandleData->Socket) == SOCKET_ERROR)
         {
            printf("closesocket() failed with error %d\n", WSAGetLastError());
            return 0;
         }

         GlobalFree(PerHandleData);
         GlobalFree(PerIoData);
         continue;
      }

      //

      if (PerIoData->BytesRECV == 0)
      {
         PerIoData->BytesRECV = BytesTransferred;
         PerIoData->BytesSEND = 0;
      }
      else
      {
         PerIoData->BytesSEND += BytesTransferred;
      }

      if (PerIoData->BytesRECV > PerIoData->BytesSEND)
      {

         // Post another WSASend() request.
         // Since WSASend() is not gauranteed to send all of the bytes requested,
         // continue posting WSASend() calls until all received bytes are sent.

         ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));

         PerIoData->DataBuf.buf = PerIoData->Buffer + PerIoData->BytesSEND;
         PerIoData->DataBuf.len = PerIoData->BytesRECV - PerIoData->BytesSEND;

         if (WSASend(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &SendBytes, 0,
            &(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
         {
            if (WSAGetLastError() != ERROR_IO_PENDING)
            {
               printf("WSASend() failed with error %d\n", WSAGetLastError());
               return 0;
            }
         }
      }
      else
      {
         PerIoData->BytesRECV = 0;

         // Now that there are no more bytes to send post another WSARecv() request.

         Flags = 0;
         ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));

         PerIoData->DataBuf.len = DATA_BUFSIZE;
         PerIoData->DataBuf.buf = PerIoData->Buffer;

         if (WSARecv(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,
            &(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
         {
            if (WSAGetLastError() != ERROR_IO_PENDING)
            {
               printf("WSARecv() failed with error %d\n", WSAGetLastError());
               return 0;
            }
         }
      }
   }
}

发表在 article | 标签为 | C++ socket 编程已关闭评论

大b和小b的换算关系

在计算机网络、IDC机房中,其宽带速率的单位用bps(或b/s)表示;换算关系为:1Byte=8bit






1B=8b





---------- 1B/s=8b/s(或1Bps=8bps)






1KB=1024B



---------- 1KB/s=1024B/s




1MB=1024KB ---------- 1MB/s=1024KB/s




在实际上网应用中,下载软件时常常看到诸如下载速度显示为128KB(KB/s),103KB/s等等宽带速率大小字样,因为ISP提供的线路带宽使用的 单位是比特,而一般下载软件显示的是字节(1字节=8比特),所以要通过换算,才能得实际值。然而我们可以按照换算公式换算一下:
128KB/s=128×8(Kb/s)=1024Kb/s=1Mb/s即:128KB/s=1Mb/s






理论上:2M(即2Mb/s)宽带理论速率是:256KB/s(即2048Kb/s),实际速率大约为80--200kB/s;(其原因是受用户计算机性 能、网络设备质量、资源使用情况、网络高峰期、网站服务能力、线路衰耗,信号衰减等多因素的影响而造成的)。4M(即4Mb/s)的宽带理论速率 是:512KB/s,实际速率大约为200---440kB/s

上行速率是指用户电脑向网络发送信息时的数据传输速率,下行速率是指网络向用户电脑发送信息时的传输速率。比如用 FTP上传文件到网上去,影响上传速度的就是“上行速率”;而从网上下载文件,影响下载速度的就是“下行速率”。当然,在实际上传下载过程中,线路、设备 (含计算机及其他设备)等的质量也会对速度造成或多或少的影响。宽带网速计算方法.

基础知识:
在计算机科学中,bit是表示信息的最小单位,叫做二进制位;一般用0和1表示。Byte叫做字节,由8个位(8bit)组成一个字节(1Byte),用 于表示计算机中的一个字符。bit与Byte之间可以进行换算,其换算关系为:1Byte=8bit(或简写为:1B=8b);在实际应用中一般用简称, 即1bit简写为1b(注意是小写英文字母b),1Byte简写为1B(注意是大写英文字母B)。
在计算机网络或者是网络运营商中,一般,宽带速率的单位用bps(或b/s)表示;bps表示比特每秒即表示每秒钟传输多少位信息,是bit per second的缩写。在实际所说的1M带宽的意思是1Mbps(是兆比特每秒Mbps不是兆字节每秒MBps)。
建议用户记住以下换算公式:
1B=8b 1B/s=8b/s(或1Bps=8bps)
1KB=1024B 1KB/s=1024B/s
1MB=1024KB 1MB/s=1024KB/s

规范提示:实际书写规范中B应表示Byte(字节),b应表示bit(比特),但在平时的实际书写中有的把bit和Byte都混写为b ,如把Mb/s和MB/s都混写为Mb/s,导致人们在实际计算中因单位的混淆而出错。切记注意!!!

实例:在我们实际上网应用中,下载软件时常常看到诸如下载速度显示为128KBps(KB/s),103KB/s等等宽带速率大小字样,因为ISP提供的 线路带宽使用的单位是比特,而一般下载软件显示的是字节(1字节=8比特),所以要通过换算,才能得实际值。然而我们可以按照换算公式换算一下:
128KB/s=128×8(Kb/s)=1024Kb/s=1Mb/s即128KB/s=1Mb/s。

案例1: 某用户反映,为什么我的网速和我办的带宽不一样? 我办的是4M 的宽带,可为什么我测试却只有2百多K的网速啊? 是不是电信骗了我?没有给我开4M哟 ?
案例分析:尊敬的用户,这只是误会。这可能有几个你不理解的原因:第一,实际网速单位是Mb/s,不是MB/s,而你所说的2百多K,其实际是指2百多 KB/s(即2百多千字节每秒)不是2百多Kb/s(即2百多千比特每秒),通常情况下都是说简称如250KB/s或250Kb/s说成250K。第二, 宽带4Mb/s=512KB/s并且这只是技术上的最大理论值,而不是所达到的实际值,一般正常情况下技术上的最大理论值为4Mb/s的宽带实际值可以达 200KB/s至440KB/s。因为宽带速率要受到很多因素(比如用户计算机性能、资源使用情况、网络高峰期、网站服务能力、信号衰耗、线路衰耗、距离 远近等)的影响,所以导至实际值与技术上的最大理论值有偏差。第三,网络运营商提供的宽带速率单位中,"bps"是指"bit per second"。而实际速度所指的bps是指"Byte per second"。所以要经过换算,而1Byte=8bit,在计算网速的上行速度或下行速度,都必须将数值除以8即把bit转化为Byte。例如:下行速 度(即下载速度)为1Mb/s,其换算成等价值就是128KBps ;换算方法:1Mbps=1024/8(KBps)=128KBps即128KByte/s 。

案例2: 某用户反映, 我办的是4M 的宽带, 为什么我的网速比通常情况下都慢哟,而且还经常掉线?是不是电信骗了我?没有给我开4M哟 ?
案例分析:尊敬的用户,这只是误会。导致网速慢和经常掉线,通常情况下有几种可能的原因:第一、计算机感染病毒较严重;第二:计算机软硬件配置及性能;第 三、上网终端质量、网线质量、线路传输负载;第四、线路接触是否良好、电源电压是否稳定等问题;第五、外界信号干扰、信号衰减、线路衰耗及线路距离长短; 第六、私自或不规范组网;第七,网卡质量不好或没有插好;第八、安装了多种杀毒软件及防火墙或同时运行过多的程序;第九、通信协议设置和防火墙的配置等等 原因;对于本案例中,该用户的情况经查明,该用户网速慢和掉线的原因是:第一、该用户的电脑感染了多种病毒,导致内存被占用,CPU使用率较高,经常达 100%;影响了电脑性能,导致网速慢;第二、该用户办理的是ADSL拨号上网,因不规范的私自组网,导致线路传输负载加重,影响线路传输流量,造成网速 慢并且经常掉线。第三、网线RJ45与HUB的接头接触不良好和电源电压不稳

发表在 article | 大b和小b的换算关系已关闭评论