Friday, June 25, 2010

Linux 系统 C++ 开发工具概述

本文转自 http://www.linuxidc.com/Linux/2009-02/18381.htm


概述
就C++开发工具而言,与Windows下微软(VC, VS2005等)一统天下相比,Linux/Unix下C++开发,可谓五花八门,各式各样。Emacs, vi, eclipse, anjuta,kdevelop等层出不穷。
Windows下,开发工具多以集成开发环境IDE的形式展现给最终用户。例如,VS2005集成了编辑器,宏汇编ml,C /C++编 译器cl,资源编译器rc,调试器,文档生成工具, nmake。它们以集成方式提供给最终用户,对于初学者而言十分方便。但是,这种商业模式,直接导致用户可定制性差,不利于自动化,集成第三方工具的能力 弱。例如,无法定制一些宏来处理一些重复操作;体会不到自动化makefile一步到位快感;无法远程登录到服务器上进行开发;无法使用某种”粘合剂”来 把第三方工具(例如,文本工具,字符串工具)有效地调用起来。可以说,良好的商业支持和傻瓜式开发,是它们主要的优点。
在Linux下, 开发工具被切割成一个个独立的小工具。各自处理不同的问题。例如,编辑器(emacs, vim)用来进行编辑程序的,调试器(gdb)用来调试程序,编译器(GCC)用来编译和链接程序的,性能分析工具(gcov, gprof)用来优化程序的,文档生成器(doxygen)用来生成文档的。同时,还有一些系统工具和系统知识,我们是很有必要了解的:程序自动化机制 makefile,系统粘合剂shell,系统查找工具grep, locate, find。其它的工具(例如ctags, OCI公司的MPC等等),一旦熟练掌握,它们将成为你手中的利器。
本文主要是一些针对Linux下开发工具使用的经验之谈。由于,工具品种繁多,我们没有能力也没有必要一一介绍。对于Linux下IDE工具,例如 eclipse, anjuta等,它们虽然也很实用,但是使用起来比较简单,而且目前还算不上主流。所以,它们将不被着重介绍。同时,本文也不打算写成各个工具的操作手 册,只着眼于介绍各个工具的想要解决的问题、运行机理和主要特性。



编辑器
要进行开发,第一件事情就是选择一个合适的编辑器。编辑器选择有几个要素:
1)减少不必要的编辑动作,减少编辑的时间。
一切能够无二义性描述出来的编辑任务,都可以而且应该能被自动化。例如,每一个C++程序都会有一个main函数;我们在定义.h文件时,都希望加入一些 预处理指令#define来帮我们解决重复引用同一个头文件而带来的麻烦。鼠标操作总是比键盘操作要慢的。这方面EMACS做得可算是到了极致。所以, EMACS用户经常会吹嘘:他们编辑的速度等同于他们思考的速度。

2)可扩展性高。
程序员预期的编辑器应该能提供一些编程的帮助,例如,语法高亮,自动补齐,自动排版,语法检查等等。留心观察一下gedit, vim, emacs, ultraEdit,就会发现它们提供的远不是windows 记事本,写字板提供的那么简陋的功能。对于一种新的语言,新的语法,它们应该能很方便地提供支持,而不停留在一种或几种固定的语言上。
3)用户可定制性高。
如果想长期从事研发,特别是Linux/unix下研发的话,那么你很有必要学好一个功能足够的编辑器。有这么一句话:Linux下程序员分为三种,使用emacs的,使用vi的,还有其它。
EMACS是Stallman用lisp语言写的一个GPL的编辑器。我们这里所说的emacs指的是GNU emacs,而非Xemacs。由于它的开放性,我们可以把它打造成一个功能强大的IDE。我们在安装好CGYwin之后,也可以在Windows系统下 使用 EMACS。CGYwin和MINGW是第三方写的一个在Windows系统上模拟POSIX系统的工具。
EMACS与其说的是一个编辑器,倒不如说它是一个操作系统。我们可以用它来写编程,写wiki,收发邮件等等。EMACS主要是通过两种方式来进行扩 展:el脚本(elisp是lisp的一种方言)和第三方扩展包。EMACS的入门成本很高。由于是纯键盘操作,所以需要记忆大量的快捷键;功能强大是通 过用户添加一些扩展包,lisp脚本来实现的。如何正确配置和修改是很需要耐心和技巧的。


编译器
编译器首选GCC(GNU COMPILER COLLECTION)。原因有两个,它是GNU开源的,同时它对标准C++的 支持度高达96.15%。而VC++6.0的支持度只有83.43%。 GCC不仅是通常意义上的C或C++的编译器,它还可以编译java等其它语言。gcc是gnu c的编译器,g++是gnu c++的编译器, 而EGCS(Enhanced GNU Compiler Suite)可以认为是gcc的改进版。

编译语言从源程序到目标代码会经过如下几个阶段:源程序->汇编程序->编译成obj程序->链接成最终可执行程序。我们可以通过一条编译指令来完 成所有步骤。也可以分步执行。gcc有三个重要选项-E(只进行预处理), -S(生成汇编代码), -g(生成带原代码调试符号的可执行文件,如果想用gdb调试的话,就应该在编译时打开这个选项)。
GCC可以看作一个软件包,除了编译工具,它还集成了调试器gdb,性能分析工具gcov, gprof。只要我们装好了GCC,这些强大工具就可以直接使用了。
通过gcov,我们可以查看一个程序,源代码中每行代码的运行次数。我们优化运行次数最多的代码,那么就可以大大优化程序。使用gcov时,需要打开 GCC的fprofile-arcs和ftest-coverage两个选项。gcov中常用的选项有-b分支统计信息。
通过gprof工具,我们可以查看函数之间的调用顺序,及各个函数运行的时间。我们可以将gprof理解为Linux/unix自带工具time的加强版。使用gprof时,需要打开GCC的pg选项。
gcov和 gprof的共同点是在编译程序时,加入自己的一些辅助信息,由此来进行程序诊断。除了,这些优化手段,我们还可以使用一些内存泄漏工具,来减少野指针,未释放的内存空间。



调试器
GDB即GNU的调试器,它是GCC附带的一个性能优质的调试器。通过GDB和脚本结合,我们可以很好的实现回归测试。
GDB可以运行于CLI和GUI两种模式。默认GDB是CLI模式的,我们可以去下载和安装GUI模式的GDB,例如xxgdb, ddd等。一个更好的方式是在 EMACS中使用GDB。GDB包括visual studio工具的所有调试功能,还 包括它没有的功能。它除了支持,我们一般的设置断点,单步跟踪,step in, step out, step over等,还有一些强大的功能。在gdb中,我们可以有以下几种暂停方式:断点(BreakPoint)、观察点(WatchPoint)、捕捉点 (CatchPoint)、信号(Signals)、线程停止(Thread Stops)。

下面列举几个让我印象深刻的功能。1)通过 watch指令,可以让程序在某个变量的值发生变化时,暂停下来。2)通过print指令,在程序运行时,设置变量的值,运行一个程序自身支持的一个方 法。3)通过until指令,我们可以让程序在运行到某个程序时暂停下来。4)通过break.. if指令,使得程序在满足某个bool表达式时,暂停下来。

粘合剂
我想通过”粘合剂”这个词来表达将多个工具粘合起来的”胶水”。例如,通过shell脚本,我们可以把OS命令,sed指令,awk指令,其它脚本文件等 串联起来,发挥它们的合力。在Linux C++编程中,我们不可避免地会使用makefile文件。通过,它我们可以把编译指令,生成文档操作,清除操作等等串联起来。从某种意义上来看,它也相 当于一个粘合剂。

makefile的出发点是,维护好一个项目中众多文件的依赖关系,由此得到一个源程序的拓扑图。当我们只修改图中某个结点时,重新编译时就只需要将拓扑 图中关联的链路进行编译就好了。由此,大大缩短了编译的时间。make有两大概念:dependencies和rules。规则rule即针对每一个依赖 关系 dependency定义一个操作规则。这个细粒度的分离,就可以使我们可以定制软件构建的行为。例如,修改使用的编译器,修改includepath, 修改libpath, 修改编译选项等等。我们常见的VC中的nmake,功能和make是类似的。
make使用的重点和难点是编写Makefile文件。Makefile的语法相对其它语言来说是很不一样的,我们要特别注意TAB键和空格键的区别。有 很多工具可以用来帮助我们生成Makefile。最出名的就是GNU的autoconf了。一个GNU程序的编写,需要autoscan, aclocal, autoconf, automake这四个工具。
我们知道GNU软件安装的三步曲是:./configure, make, make install。其中./configure就是根据autoconf, alocal等工具生成一个makefile文件。make指令就是调用make指令来根据makefile文件的规则来编译源程序。而make install就是执行makefile中的install规则指出的操作(一般是copy操作)。而make clean就是执行makefile中的clean规则指出的操作(一般是rm操作)。我们用Eclispe+CDT开发Managed C++ Project时,它就是通过objects.mk,subdir.mk,sources.mk三个文件来生成Makefile。我们注意观察编译时的输 出信息,就可以看到显示的Makefile文件的内容。
可以说,如果想编译出跨平台的C++程序,那么makefile是一种最方便的机制。
OCI公司为Douglas C.Schmidt的ACE,TAO开源社区编写了一段伟大的perl脚本--MPC。它由平台信息,一个规则文件,源代码,生成用户想要的工程文件,例 如Make, Nmake, Visual C++ 6, Visual C++ 7等等。Google Web Tookit, Celtix做的事情与之类似,不过它们是针对JAVA的,而MPC是针对C++的。


结束语
国内资料太多的低层次的重复,经常是一个网页被多次转载,而且回答问题时深度不够。个人找资料的顺序是:查看quick start或how to文档->自带的帮助(如果看起来不太吃力话)->百度查一下中文网页,来理清一下基本概念->google查一下->几个大的,相关的网站查下资料 ->看自带帮助。再者,面对面的交流是十分重要的,大家可以相互理一下概念,交流一下心得。可惜,我身边这种氛围还是不够。

Linux下开发还可以更友好一些。个人感觉, Linux开发要在国内普通程序员中大规模普及,还有一段很长的路要走。Ubuntu火 爆的主要原因,就是它帮用户搭好一些默认配置。用户如果想新加一些 服务,它们提供了良好,有效地支持。所以,我想我们可以在IDE和现在Linux这种一个个小部件的这两种状态之间,取一个折衷。也就是针对几种主要需求 的用户,发布一些配置好的环境。尤其是emacs的各种el脚本(例如界面主题的color-theme, C/C++语言编辑策略,代码样式设置脚本,各种emacs系统设置), 第三方扩展包(模板template, 编程支持包cedet等)。每一个用户浪费时间来进行这些配置是十分没有意义的!工具始终只是工具,我们不能沦为工具的奴隶,不能把一大部分精力浪费在配 置工具上。
值得注意的是现在方兴未艾的eclipse有向这方面迈进的趋势。但是,现在emacs已经做得很好了,ecilpse能否超越它,我们还有待观察。我们 可以通过在eclipse上安装SDT插件来进行C++开发。但是,它目前还不支持调试功能,而且不太稳定,功能不够强。例如,有时会无故死掉;如果想通 过eclipse来转向函数原型的话,那么迎接你的将是一个漫长、焦急的等待。
由于本人缺少在Linux下进行实际大规模程序的开发经验,对很多工具和机制的理解还比较肤浅。对它们的熟悉程度离真正实用,还有一段很长的路要走。

Tuesday, May 25, 2010

Scheduling Jobs in Linux

Scheduling one-time jobs
If you want to run one or more commands at a later time, you can use the at command. The atd daemon --- a program designed to process jobs submitted using at --- runs you commands at the specified time and mails the output to you.

Before you try the at command, you need to know that the following configuration files control which users can schedule tasks using the at command:

  • /etc/at.allow contains the names of the users who may submit joibs using the at command.
  • /etc/at.deny contains the names of the users not allowed th submit jobs using the at command.
If these file aren't present or if you find an empty /etc/at.deny file, any user can submit jobs by using the at command. The default in Linux is an empty /etc/at.deny file; with this default in place, anyone can use the at command.

To use at to schedule a one-time job for execution at a later time, follow these steps:

1. Run the at command with the date or time when you want your commands executed.
    When you press Enter, the at> prompt appears, as follows:
        at 21:30
        at>

    Simply specify the time in a 24-hour format. In this case, you want to execute the commands at 9:30pm. tonight ( or tomorrow, if it's already past 9:30pm.). 

2. At the at> prompt, type the commands you want to execute as if typing at the shell prompt. After each command, press Enter and continue with the next command. When you finish entering the commands you want to execute, press Ctrl+D to indicate the end.

Here's an example showing how to execute the ps command at a future time:

at> ps
at>
job 1 at 2010-05-24 21:30

After you press Ctrl+D, the at command responds with a job number and the date and time when the job will execute.


Formats for the Time of Execution with the at Command
CommandWhen the Job will Run
at nowImmediately
at now + 15 minutes15 minutes from current time
at now + 4 hours4 hours from the current time
at now + 7 days7 days from the current time
at noonAt noontime today(or tomorrow,if already past noon)
at now next hourExactly 60 minutes from now
at now next dayat the same time tomorrow
at 17:00 tomorrowat 5pm. tomorrow
at 4:45pmAt 4:45pm. today(or tomorrow, if it's already past 4:45pm)
at 3:00 Dec 28,2008At 3:30am on December 28,2008

atq command uses to view current list of scheduled jobs:

The output looks similar to the following:

4         2006-12-28   03:00    a    root
5         2006-12-26   21:57    a    root
6         2007-10-26   16:45    a    root

The first field on each line shows the job number --- the same number that the a command displays when you submit the job. The next field shows the year, month, day, and time of execution. The last filed shows the jobs pending in the a queue.

If you want to cancel a job, use the atrm command to remove that job from the queue. When removing a job with the atrm command, refer to the job by its number, as fllows:

atrm 4


Scheduling recurring jobs


crontab command : used to schedule

You schedule recurring jobs by placing job information in a file with a specific format and submitting this file with the crontab command. The cron daemon --- crond ---- checks the job information every minute and executes the recurring jobs at the specified times. Because the cron daemon processes recurring jobs, such jobs are also referred to as cron jobs.

Any output from a cron job is mailed to the user who submits the job. (In submitted job-information file, you can specify a different recipient for the mailed output.)

Two configuration files control who can schedule cron jobs using crontab:


  • /etc/cron.allow contains the names of the users who may submit jobs using the crontab command.
  • /etc/cron.deny contains the names of users not allowed to submit jobs using the crontab command.
If the /etc/cron.allow file exists, only users listed in this file can schedule cron jobs. If only the /etc/cron.deny file exists, users listed in this file can't schedule cron jobs. If neither file exists, the default Linux setup enables any user to submit cron jobs.

To submit a cron job, follow these steps:

1. Prepare a shell script (or an executable program in any programming language) that can perform the recurring task you want to perform.
    You can skip this step if you want to execute an existing program periodically.

2. Prepare a text file with information about the times when you want the shell script or program (from Step 1) to execute and then submit this file by useing crontab.
    You can submit several recurring jobs with a single file. Each line with timing information about a job has a standard format with six fields --- the first five specify when the job runs, and the sixth and subsequent fields constitute the actual command that runs. For example, here's a line that executes the myjob shell script in a user's home directory at five minutes past midnight each day:
     5 0 * * *  $HOME/mujob
Next table shows the meaning of the first five fields.

3. Suppose the text file jobinfo (in the current directory) contains the job information. Submit this information to crontab with the following command:
    crontab jobinfo
That's it! You're set with the cron job. From now on, the cron job runs at regular intervals ( as specified in the job information file), and you receive mail messages with the output from the job.

Format for the Time of Execution in crontab Files
Field NumberMeaning of FieldAcceptable Range of Values*
1Minute0-59
2Hour of the day0-23
3Day of the month0-31
4Month1-12 or the names of month using the first three letters
5Day of the week0-6 or the three-letter abbreviations of weekdays
*An asterisk in a field means all possible values for that field. For example, if an asterisk in the third field,the job is executed avery day.

To Vereify that the job is indeed scheduled, type the following command:

crontab  -1

The output of the crontab -1 command shows the cron jobs currently installed in your name. To remove you cron jobs, type crontab -r.

Wednesday, May 19, 2010

巴菲特2010年第二季度完全持股名单


  新浪财经讯 “股神”巴菲特旗下的伯克希尔哈萨韦公司(Berkshire Hathaway)刚刚披露了截至2010年3月31日的最新持股名单。这是我们能够了解到的巴菲特最新的持股数据,尽管个别持仓3月份以来可能略有变化。下面这个名单是按照字母顺序从A-Z排列的。
  美国运通(American Express)(AXP) 超过1.5160亿股,与上一季度相同。
  美国银行(Bank of America)(BAC) 500万股,与上一季度相同。
  Becton Dickinson(BDX) 增持至174.4万股,上一季度为150万股,两个季度前为120万股。
  CarMax(KMX) 减持至772.5万股,上一季度为800万股,两个季度前为900万股。
  可口可乐(Coca Cola)(KO) 刚好2亿股,与上一季度相同。
  Comcast(CMCSA) 1200万股,与上一季度相同。
  Comdisco Holdings(CDCO) 大约150万股,与上一季度相同。
  康菲石油(ConocoPhillips)(COP) 减持至3417.9万股,上一季度为3770万股,两个季度前为5743万股,去年6月底为6248.5万股。
  好市多(Costco Wholesale)(COST) 减持至433.3363万股,上一季度为525.4万股。
  埃克森美孚(Exxon Mobil)(XOM) 42.18万股,与上一季度相同,这是两个季度前的新头寸,当时持股为127.6万股。
  Gannett(GCI) 减持至174.0231万股,上一季度为220.2万股,两个季度前为344.7万股。
  通用电气(General Electric)(GE) 777.7万股,与上一季度相同,但没有包括2008年年底的巨额优先股投资。
  高盛(Goldman Sachs)(GS) 高盛不在名单之上,不过这是因为伯克希尔持有的并非高盛普通股,而是优先股和认股权证。巴菲特说他依然持有这些优先股和认股权证。
  葛兰素史克(GlaxoSmithKline PLC)(GSK) 151万股,与上一季度相同。
  哈雷戴维森(Harley-Davidson)(HOG) 不是普通股,但巴菲特仍持有其优先股和认股权证。
  家得宝(Home Depot)(HD) 275.7万股,与上一季度相同。
  英格索兰(Ingersoll-Rand)(IR) 63.66万股,与上一季度相同,但三个季度前为778万股。
  Iron Mountain(IRM) 增持至779.48万股,上一季度为700万股,两个季度前为337.22万股。
  强生(Johnson & Johnson)(JNJ) 减持至2390万股左右,上一季度为2700万股多一点,两个季度前为3691万股,而2008年一度持股高达6200万股。
  卡夫食品(Kraft Foods)(KFT) 减持至1.067亿股,上一季度为超过1.38亿股。巴菲特对于卡夫收购吉百利的交易一直持批评态度。
  Lowe's Companies(LOW) 650万股,与上一季度相同。
  M&T Bank(MTB) 减持至556.3万股,上一季度为671万股。
  穆迪(Moody's)(MCO) 连续减持至3083万股,上一季度为3180万股,两个季度前为3920万股,再往前一个季度则达到4800万股。
  Nalco Holding(NLC) 900万股,与上一季度相同。
  雀巢(Nestle)美国存托凭证(ADR) 340万股,与上一季度相同。
  耐克(Nike)(NKE) 764.1万股,与上一季度相同。
  宝洁(Procter & Gamble)(PG) 连续减持至7831.7万股,上一季度大约为8750万股,两个季度前为9630万股。
  Republic Services(RSG) 增持至1082.7万股,上一季度为829万股。该股为巴菲特两个季度前跟随比尔·盖茨的投资步伐开始持有。
  赛诺菲-安万特(Sanofi Aventis)(SNY) 超过390万股,与上一季度相同。
  蒂芙尼(Tiffany & Co)(TIF) 不是普通股,但巴菲特依然持有其优先股和认股权证。
  Torchmark(TMK) 大约282万股,与上一季度相同。
  US Bancorp(USB) 大约6900万股,与上一季度相同。
  USG Corp(USG) 1707.2万股,与上一季度相同。
  United Parcel Service(UPS) 142.9万股,与上一季度相同。
  沃尔玛(Wal-Mart Stores)(WMT) 略超3900万股,与上一季度相同,上一季度增持之前为3780万股,远高于3个季度之前的1990万股。
  华盛顿邮报(Washington Post)(WPO) 超过172万股,与上一季度相同。
  富国银行(Wells Fargo)(WFC) 大约3.195亿股,与上一季度基本不变,两个季度前为3.133亿股,三个季度前为3.02亿股,再往前一个季度为2.9亿多股。
  Wesco Financial(WSC) 570.3万股,与上一季度相同。
  Sun Trust Bank(STI) 全部出清。上一季度为将近240万股,两个季度前为307.9万股,三个季度前超过320万股。
  Travelers Cos(TRV) 全部出清。不过此前也仅少量持有27336股。
  United Health(UNH) 全部出清。上一季度为117.5万股,此前已经连续三四个季度不断减持。
  Wellpoint(WLP) 全部出清。清仓之前的上一季度为持有134.3万股。
  注:原文来自24/7 Wall St。

Recovering from a forgotten root password

1.Reboot the PC (select Reboot as you log out of the GUI screen) or power up as usual.

Soon you see the graphical GRUB boot loader screen that shows the names of the operating systems you can boot. If your system runs the LILO boot loader, press Ctrl+X and at the boot: prompt, type linux single and press Enter. Then proceed to Step 4.

2.If you have more than one operating system installed, use the arrow key to select Linux as your operating system and then press the A key.

GRUB prompts you for commands to add to its default boot command.

3.Press the spacebar, type the following, and press Enter:
       single
   Linux starts up as usual but runs in a single-user mode that doesn't require you to log in. After Linux starts, you see the following command-line prompt that ends with a hash mark(#), similar to the following:
     sh-3.00#

4.Type the passwd command to change the root password as follows:
    sh-3.00# passwd
    Changing password for user root.
    New password:

5.Type the new root password that you want to use (it doesn't appear on-screen) and then press Enter.

   Linux asks for the password again, like this:
      Retpye new password:

6.Type the password again and press Enter.
    If you enter the same password both times, the passwd command changes the root password.

7.Now type reboot to reboot the PC.
   After Linux starts, it displays the familiar login screen. Now you can log in as root with the new password.

In SUSE Linux, in Step 3, type single init=/bin/sh (instead of single) and before proceeding to Step 4, type mount /-n-0 remount,rw. Then perform Steps 4 through 6 to change the root password. After Changing the password, type mount /n -o remount,ro. Then continue to Step 7 and reboot the PC.

Tuesday, May 18, 2010

Text Editing with ed and vi

Using ed

When you use ed, you work in command mode or text input mode:

  • Command mode is what you get by default. In this mode, anything that you type is interpreted as a command.
  • Text input mode is for type text. You can enter input mode with the commands a (append), c (change), or i (insert). After entering lines of text you can leave input mode by entering a period (.) on a line by itself.
To practice editing a file, copy the /etc/fstab file to you home directory by issuing the following commands:

cd
cp /etc/fstab .

Now you have a file named fstab in you home directory. Type ed -p: fstab to begin editing a file in ed. The editor responds:

878
:

This Expamle uses the -p option to set the prompt to the colon character (:) and opens the fstab file (in the current directory, which is you home directory) for editing.  The ed editor opens the file, reports the number of characters in the file (878), displays the prompt(:), and waits for a command.

When you're editing with ed, make sure that you always turn on a prompt character ( use the -p option). Without the prompt, distinguishing whether ed is in iuput mode or command mode is difficult.

After ed opens a file for editing, the current line is the last line of the file. To see the current line number (the current line is the line to which ed applies you command), use the .= command like this:

:.=
9

This output tells you that the fstab file has nine lines. (Your system's /etc/fstab file may have a different number of lines).

You can use the 1,$p command to see all lines in a file, as the following example shows:

:1,$p
# /etc/fstab: static file system information.
#
# Use 'blkid -o value -s UUID' to print the universally unique identifier
# for a device; this may be used with UUID= as a more robust way to name
# devices that works even if disks are added and removed. See fstab(5).
#
#            
proc            /proc           proc    defaults        0       0
# / was on /dev/sda1 during installation
UUID=2d09f69e-b3b9-4f77-bd34-728bc5d5b97e /               ext4    errors=remount-ro 0       1
# swap was on /dev/sda5 during installation
UUID=896133ec-9044-4ea4-a341-e0033120076f none            swap    sw              0       0
/dev/scd1       /media/cdrom0   udf,iso9660 user,noauto,exec,utf8 0       0
/dev/scd0       /media/cdrom1   udf,iso9660 user,noauto,exec,utf8 0       0
/dev/fd0        /media/floppy0  auto    rw,user,noauto,exec,utf8 0       0
:

To go to a specific line, type the line number:

:15

The editor responds by displaying that line:

/dev/scd1       /media/cdrom0   udf,iso9660 user,noauto,exec,utf8 0       0
:

Suppose you want to delete the line that contains cdrom. To search for a string, type a slash(/) followed by the string that you want to locate:

:/cdrom
/dev/scd1       /media/cdrom0   udf,iso9660 user,noauto,exec,utf8 0       0
:

The editor locates the line that contains the string and then displays it. That line becomes the current line.

To delete the current line, use the d command as follows:

:d
:

To replace a string with another, use the s command. To replace cdrom with the string cd, for example, use this command:

:s/cdrom/cd
:

To insert a line in front of the current line, use the i command:

:i
      (type the line you want to insert)
.     (type a single period to indicate you're done)
:

You can enter as many lines as you want.  After the last line, enter a period (.) one a line by itself.

When you're happy with the changes, you can write them to the file with the w command. If you want to save the changes and exit, type wq to perform both steps at the same time:

:wq
857

If you want to quit the editor without saving any changes, use the Q command.




Commonly Used ed Commands
CommandDoes the following
!commandExecutes a shell command.
$Goes to the last line in the buffer
%Applies a command that follows to all lines in the buffer. For example, %p prints all lines.
+Goes to next line
+nGoes to the nth next line (where n is a number you designate)
,Applies a command that follows to all lines in the buffer. (For example, ,p prints all lines.) This is similar to %.
-Goes to the preceding line
-nGoes to the nth previous line
.Refers to the current line in the buffer
/text/Searches forward for the specified text
;Refers to a range of lines---current through last line in the buffer
=Prints the line number
?text?Searches backward for the specified text
^Goes to the preceding line. (See also the - command)
^nGoes to the nth previous line
aAppends the current line
cChanges the specified lines
dDeletes the specified lines
iInserts text before the current line
nGoes to line number n
Press EnterDisplays the next line and makes that line current
qQuits the editor
QQuits the editor without saving changes
r fileReads and inserts the contents of the file after the current line
s/old/new/Replaces an old string with a new one
uUndoes the last command
W fileAppends the contents of the buffer to the end of the specified file
w fileSaves the buffer in the specified file. (If no file is named, it saves in the default file ---- the file whose contents ed is currently editing.

Using vi

The vi editor loads the file into memory and displays the first few lines in a text screen and positions the cursor on the first line.

The last line shows the pathname of the file as well as the number of lines (21) and the number of characters(771) in the file.Later, the last line in the vi display functions as a command entry area. The rest of the lines display the file. If the file contains fewer lines than the screen, vi displays the empty lines with a tilde(~) in the first column.

The current line is marked by the cursor, which appears as a small black rectangle. The cursor appears on top of a character.

When using vi, you work in one of three modes:

  • Visual command mode is what you get by default. In this mode, anyting that you type is interpreted as a command that applies to the line containing the cursor. The vi commands are similar to the ed commands.
  • Colon command mode is for reading or writing files, setting vi options, and quitting vi. All colon commands start with a colon(:). When you enter the colon, vi positions the cursor on the last line and waits for you to type a command. The command takes effect when you press Enter.
  • Text input mode is for typing text. You can enter input mode with the command a (insert after cursor), A (append at end of line), or i (insert after cursor). After entering lines of text, you have to press Esc to leave input mode and re-enter visual command mode.
One problem with all these modes is that you can't easily tell the current mode taht vi is in. You may begin typing only to realize that vi isn't in input mode, which can be frustrating(令人沮丧的).

If you want to make sure that vi is in command mode, just press Esc a few times. (Press Esc more than once doesn't hurt.)

To view online help in vi, type :help while in colon command mode. When you are done with help, type :q to exit the Help screen and return to the file you're editing.
Cursor Movement Commands in vi
KeyDoes the following
Move the cursor one line down
Move the cursor one line up
Move the cursor one character to the left
Move the cursor one character to the right
WMove the cursor one word forward
BMove the cursor one word backward
Ctrl+DMoves down half a screen
Ctrl+UScrolls up half a screen

To search for a string, first type a slash(/). The vi editor displays the slash on the last line of the screen. Type the search string and then press Enter. The vi editor locates the string and positions the cursor at the beginning of that string. 

Commonly Used vi Commands
CommandDoes the following
Insert Text
aInserts text after the cursor
AInserts text at the end of the current line
IInserts text at the beginning of the current line
iInserts text before the cursor
Delete Text
DDeletes up to the end of the current line
ddDeletes the current line
dGDeletes from the current line to the end of the file
dwDeletes from the cursor to the end of the following word
xDeletes the character on which the cursor rests
Change Text
CChanges up to the end of the current line
ccChanges the current line
JJoins the current line with the next one
rxReplaces the character under the cursor with x(where x is any character)
Move Cursor
h or ←Moves one character to the left
j or ↓Moves one line down
k or ↑Moves one line up
LMoves to the end of the screen
l or →Move one character to the right
wMoves to the beginning of the following word
bMoves to the beginning of the previous word
Scroll Text
Ctrl+DScrolls forward by half a screen
Ctrl+UScrolls backward by half a screen
Refresh Screen
Ctrl+LRedraws screen
Cut and Paste Text
yyYanks(copies) current line into an unnamed buffer
PPuts the yanked line above the current line
pPuts the yanked line below the current line
Colon Commands
:!commandExecutes a shell command
:qQuits the editor
:q!Quits without saving changes
:r filenameReads the file and inserts it after the current line
:w filenameWrites a buffer to the file
:wqSaves changes and exits
Search Text
/stringSearches forward for a string
?stringSearches backward for a string
Miscellaneous
uUndoes the last command
EscEnds input mode and enters visual command mode
UUndoes recen changes to the current line

Monday, May 17, 2010

Commands for mounting and unmounting

Start by looking at the /etc/fstab file for clues to the name of the CD-ROM device. For example, some Linux distributions use the device name /dev/cdrom to refer to CD/DVD-ROM drives, whereas others may use device names such as /dev/hdc, /dev/cdroms/cdrom0, or /dev/cdrecorder( for a DVD/CD-R drive). The entry in /etc/fstab file also tells you the directory where that distribution expects the CD/DVD to be mounted. Some distributions use /media/cdrom as mount point, whereas others use /media/cdrom0, or /media/cdrecorder.

It is customary to use the cdrom term to mean both CD-ROM and DVD-ROM.

Log in as root ( or type su - to become root), insert the DVD-ROM in the DVD drive, and then type the following command:

mount  /dev/hdc /media/cdrom0

This command mounts the file system on the device named /dev/hdc (an IDE DVE/CD-ROM drive) on the /media/cdrom0 directory ( which is also called the mount point) in the Linux file system.

After the mount command successfully completes its task, you can access the files on the DVD-ROM by referring to the /media/cdrom0 directory as the top-level directory of the disc. In other words, to see the contents of the DVD-ROM, type

ls -F /media/cdrom0

When you're done using the DVD-ROM and before you eject it from the drive, you have to unmount the disc drive with the following umount command:

umount  /dev/hdc


You can mount devices on any empty directory on the file system. However, each distribution has customary locations with directories meant for mounting devices. For example, some distributions use directories in /mnt whereas others use the /media directory for the mount points.

Linux 常见目录

The Linux file system has a well-defined set of top-level directories,and some of these directories have specific purposes.

Top-level Direcotries in Linux File System

DirectoryDescription
/This root directory forms the base of the file system.All files and directories are contained logically in the root directory,regardless of their physical locations.
/binContains the executable programs that are part of the Linux operating system. Many Linux commands, such as cat, cp, ls, more, and tar, are located in /bin.
/bootContains the Linux kernel and other files that the LILO and GRUB boot managers need. (The kernel and other files can be anywhere, but placing them in the /boot directory is customary.
/devContains special files that represent devices attached to the system.
/etcContains most system configuratoin files and the initialization scripts(in the /etc/tc.d subdirectory)
/homeConverntional location of the home directories of all users. User edulaney's home directory, for example, is /home/edulaney.
/libContains library files for all programs stored in /sbin and /bin directories (including the loadable driver modules) needed to start Linux.
/lost+foundDirectory for lost files. Every disk partition has a lost+found directory.
/mediaA directory for mounting file systems on removable media, such as CD/DVD-ROM drives, floppy disks, and Zip drives. Contains the /media/floppy directory for mounting floppy disks and /media/cdroom or /media/cdroom0 directory for mounting the CD/DVD-ROM drive. if you have a CD/DVD recorder, you find a /media/cdrecorder directory instead of /media/cdrom and may also find /media/DVD.
/mntA directory for temporarily mounted file systems
/optProvides a storage area for large application software packages. For example, some distributions install the OpenOffice.org Office suite in the /opt directory.
/procA speical directory that contains various information about the processes running in the Linux system.
/rootThe home directory for root user.
/sbinContains executable files representing commands typically used for system-administration tasks and used by the root user. Commands such as halt and shutdown reside in the /sbin directory.
/srvContains data for services( such as Web and FTP ) offered by this system.
/sysA special directory that contains information about the devices, as seen by the Linux kernel.
/tmpA temporary directory that any user can use as a scratch directory, meaning that the contents of this directory are considered unimportant and usually are deleted every time the system boots.
/usrContains the subdirectories for many important programs, such as the X Window System( in the /usr/X11R6 directory ) and the online manual.
/varContains various system files(such as logs), as well as directories for holding other information, such as files for the Web server and anonymous FTP server.

Important /usr Subdirectories
SubdirectoryDescription
/usr/X11R6Contains the X Window System software
/usr/binContains executable files for many more Linux commands,including utility programs that are commonly available in Linux but aren't part of the core Linux operating system.
/usr/gamesContains some old Linux games
/usr/includeContains the header files (file names ending in .h) for the C and C++ programming languages; also includes the X11 header files in the /usr/include/X11 directory and the Linux kernel header files in the /usr/include/linux directory.
/usr/libContains the libraries for C and C++ programming languages; also contains many other libraries, such as database libraries and graphical libraries.
/usr/localContains local files. The /usr/local/bin directory, for example, is supposed to be the location for any executable program developed on your system
/usr/sbinContains many administrative commands, such as commands for electronic mail and networking.
/usr/shareContains shared data, such as default configuration files and images for many applications. For example, /usr/share/gnome contains various shared files for the GNOME desktop, and /usr/share/doc has the documentation files for many Linux applicaions (such as the bash shell, the Sawfish window manager, and The GIMP image-processing program).
/usr/share/manContains the online manual (which you can read by using the man command)
/usr/srcContains the source code for the Linux kernel (the core operating system)


Important /var Subdirectories
SubdirectoryDescription
/var/cacheStorage area for cached data for applications
/var/libContains information relating to the current state of applications
/var/lockContains locked files to ensure that a resource is used by one application only
/var/logContains log files organized into subdirectories. The syslogd server stores its log files in /var/log, with the exact content of the files depending on the syslogd configuration file /etc/syslog.conf. For example, /var/log/messages is the main system log file; /var/log/secure contains log messages from secure services (such as sshd and xinetd); and /var/log/mainlog contains the log of mail messages.
/var/mailContains user mailbox files
/var/optContains variable date for packages stored in /opt directory
/var/runContains data describing the system since it was booted
/var/spoolContains data that's waiting for some kind of processing
/var/tmpContains temporary files preserved between system reboots
/var/ypContains Network information Service(NIS) database files

Wednesday, May 12, 2010

Common Linux commands by category

Help and Abbreviations
Command NameAction
aproposFinds online manual pages for a specified keyword
infoDisplays online help information about a specified command
manDisplays online help information
whatisSimilar to apropos but searches for complete words only
aliasDefines an abbreviation for a long command
typeShows the type and location of a command
unaliasDeletes an abbreviation defined using alias

Managing Files and Directories
Command NameAction
cdChanges the current directory
chmodChanges file permissions
chownChanges file owner and group
cpCopies files
lnCreates symbolic links to files and directories
lsDisplays the contents of a directory
mkdirCreates a directory
mvRenames a file as well as moves a file from one directory to another
rmDeletes files
rmdirDeletes directories
pwdDisplays the current directory
touchUpdates a file's time stamp

Find Files
Command NameAction
findFinds files based on specified criteria,such as name and size
locateFinds files using a periodically updated filename database.(The database is created by the updatedb program.)
whereisFinds files based in the typical directories where executable (also known as binary)files are located
whichFinds files in the directories listed in the PATH enviroment variable

Processing Files
Command NameAction
catDisplays a file on standard output (can be used to concatenate several files into one big file)
cutExtracts specified sections from each line of text in a file
ddCopies blocks of data from one file to another(used to copy data from devices)
diffCompares two text files and finds any differences
expandConverts all tabs into spaces
fileDisplays the type of data in a file
foldWraps each line of text to fit a specified width
grepSearches for regular expressions within a text file
lessDisplays a text file one page at a time(can go backward,also)
lprPrints files
moreDisplays a text file,one page at a time(goes forward only)
nlNumbers all nonblank lines in a text file and prints the lines to standard output
pasteConcatenates corresponding lines from several files
patchUpdates a text file using the differences between the original and revised opy of the file
sedCopies a file to standard output while applying specified editing commands
sortSorts lines in a text file
splitBreaks up a file into several smaller files with specified size
tacReverses a file(last line first and so on)
tailDisplays the last few lines of a file
trSubstitutes one group of characters for another throughout a file
uniqEliminates duplicate lines from a text file
wcCounts the number of lines,words,and characters for another throughout a file
zcatDisplays a compressed file (after decompressing)
zlessDisplays a compressed file one page at a time(can go backward also)
zmoreDisplays a compressed file one page at a time

Archiving and Compressing Files
Command NameAction
compressCompresses files
cpioCopies files to and from an archive
gunzipDecompresses files compressed with GNU Zip(gzip)
gzipCompresses files using GNU Zip
tarCreates an archive of files in one or more directories(originally meant for archiving on tape
uncompressDecompresses files compressed with compress

Managing System
Command NameAction
bgRuns an interrupted process in the background
fgRuns a process in the foreground
freeDisplays the amount of free and used memory in the system
haltShuts down Linux and halts the computer
killSends a signal to a proces(usually used to terminate a process)
lddDisplays the shared libraries needed to run a program
niceRuns a process with lower priority(referred to as nice mode)
psDisplays a list of currently running processes
printenvDisplays the current enviroment variables
pstreeSimilar to ps bu shows parent-child relationships clearly
rebootStops Linux and then restart the computer
shutdownShuts down Linux
topDisplays a list of most processor-and memory-intensive processes
unameDisplays information about the system and the Linux kernel

Managing Users
Command NameAction
chshChanges the shell(command interpreter)
groupsPrints the list of groups that include a specified user
idDisplays the user and group ID for a specified user name
passwdChanges the password
suStarts a new shell as another user or root(when invoked without any argument)

Managing the File System
Command NameAction
dfSummarizes free and available space in all mounted
duDisplays disk usage information
fdformatFormats a diskette
fdiskPartitions a hard disk
fsckChecks and repairs a file system
mkfsCreates a new file system
mknodCreates a device file
mkswapCreates a swap space for Linux in a file or a hard drive partition
mountMounts a device(for example,the CD-ROM)on a directory in the file system
swapoffDeactivates a swap space
swaponActivates a swap space
syncWrites buffered(saved in memory) date to files
ttyDisplays the device name for the current terminal
unmountUnmounts a device from the file system

Dates and Times
Command NameAction
calDisplays a calendar for a specified month or year
dateShows the current date and time or sets a new date and time

Search This Blog