http://www.wildpackets.com/resources/compendium/wireless_lan/wlan_packets#wp1002033
http://www.revolutionwifi.net/2011/05/wireshark-wlan-traffic-statistics-and.html
http://www.revolutionwifi.net/2011/04/using-wireshark-coloring-rules-to.html
2014年7月11日星期五
2014年5月9日星期五
关于gcc优化
Introduction
What are CFLAGS and CXXFLAGS?
CFLAGS and CXXFLAGS are environment variables that are used to tell the GNU Compiler Collection,
GCC , what kinds of switches to use when compiling source code. CFLAGS are for code written in C, while CXXFLAGS are for code written in C++.
They can be used to decrease the amount of debug messages for a program, increase error warning levels, and, of course, to optimize the code produced. The GCC manual maintains a complete list of available options and their purposes.
How are they used?
CFLAGS and CXXFLAGS can be used in two ways. First, they can be used per-program with Makefiles generated by automake.
However, this should not be done when installing packages found in the Portage tree. Instead, set your CFLAGS and CXXFLAGS in /etc/portage/make.conf. This way all packages will be compiled using the options you specify.
[Collapse]
CodeCFLAGS in /etc/portage/make.conf
CFLAGS="-march=athlon64 -O2 -pipe"
CXXFLAGS="${CFLAGS}"
Important
While it is possible to have multiple lines in USE flags, doing the same in CFLAGS can and will result in problems with programs such as
CMake. Make sure your CFLAGS declaration is on a single line, with as little whitespace as possible to avoid those issues. See bug #500034 as an example.
As you can see, CXXFLAGS is set to use all the options present in CFLAGS. This is what you'll want almost without fail. You shouldn't ever need to specify additional options in CXXFLAGS.
Misconceptions
While CFLAGS and CXXFLAGS can be very effective means of getting source code to produce smaller and/or faster binaries, they can also impair the function of your code, bloat its size, slow down its execution time, or even cause compilation failures!
CFLAGS are not a magic bullet; they will not automatically make your system run any faster or your binaries to take up less space on disk. Adding more and more flags in an attempt to optimize (or "rice") your system is a sure recipe for failure. There is a point at which you will reach diminishing returns.
Despite the bragging you'll find on the internet, aggressive CFLAGS and CXXFLAGS are far more likely to harm your programs than do them any good. Keep in mind that the reason the flags exist in the first place is because they are designed to be used at specific places for specific purposes. Just because one particular CFLAG is good for one bit of code doesn't mean that it is suited to compiling everything you will ever install on your machine!
Ready?
Now that you're aware of some of the risks involved, let's take a look at some sane, safe optimizations for your computer. These will hold you in good stead and will endear you to developers the next time you report a problem on Bugzilla. (Developers will usually request that you recompile a package with minimal CFLAGS to see if the problem persists. Remember, aggressive flags can ruin code.)
Optimizing
The basics
The goal behind using CFLAGS and CXXFLAGS is to create code tailor-made to your system; it should function perfectly while being lean and fast, if possible. Sometimes these conditions are mutually exclusive, so we'll stick with combinations known to work well. Ideally, they are the best available for any CPU architecture. We'll mention the aggressive flags later so you know what to look out for. We won't discuss every option listed on the
GCC manual (there are hundreds), but we'll cover the basic, most common flags.
Note
Whenever you're not sure what a flag actually does, refer to the relevant chapter of the GCC manual . If you're still stumped, try Google, or check out the
GCCmailing lists .-march
The first and most important option is
-march. This tells the compiler what code it should produce for your processor architecture (or arch); it says that it should produce code for a certain kind of CPU. Different CPUs have different capabilities, support different instruction sets, and have different ways of executing code. The -march flag will instruct the compiler to produce code specifically for your CPU, with all its capabilities, features, instruction sets, quirks, and so on.
Even though the CHOST variable in /etc/portage/make.conf specifies the general architecture used,
-march should still be used so that programs can be optimized for your specific processor. x86 and x86-64 CPUs (among others) should make use of the -march flag.
What kind of CPU do you have? To find out, run the following command:
user $ cat /proc/cpuinfo
To get more details, including march and mtune values, use:
user $ gcc -c -Q -march=native --help=target
Now let's see
-march in action. This example is for an older Pentium III chip:
Here's another one for a 64-bit AMD CPU:
If you still aren't sure what kind of CPU you have, you may just want to use
-march=native. When this flag is used, GCC will detect your processor and automatically set appropriate flags for it. However, this should not be used if you intend to compile packages for a different CPU!
So if you're compiling packages on one computer, but intend to run them on a different computer (such as when using a fast computer to build for an older, slower machine), then do notuse
-march=native. "Native" means that the code produced will run only on that type of CPU. The applications built with -march=native on an AMD Athlon 64 CPU will not be able to run on an old VIA C3 CPU.
Also available are the
-mtune and -mcpu flags. These flags are normally only used when there is no available -march option; certain processor architectures may require -mtune or even -mcpu. Unfortunately, GCC's behavior isn't very consistent with how each flag behaves from one architecture to the next.
On x86 and x86-64 CPUs,
-march will generate code specifically for that CPU using all its available instruction sets and the correct ABI; it will have no backwards compatibility for older/different CPUs. If you don't need to execute code on anything other than the system you're running Gentoo on, continue to use -march. You should only consider using -mtunewhen you need to generate code for older CPUs such as i386 and i486. -mtune produces more generic code than -march; though it will tune code for a certain CPU, it doesn't take into account available instruction sets and ABI. Don't use -mcpu on x86 or x86-64 systems, as it is deprecated for those arches.
Only non-x86/x86-64 CPUs (such as Sparc, Alpha, and PowerPC) may require
-mtune or -mcpu instead of -march. On these architectures, -mtune / -mcpu will sometimes behave just like -march (on x86/x86-64)... but with a different flag name. Again, GCC's behavior and flag naming just isn't consistent across architectures, so be sure to check the GCC manualto determine which one you should use for your system.
Note
For more suggested
-march / -mtune / -mcpu settings, please read chapter 5 of the appropriate Gentoo Installation Handbook for your arch. Also, read the GCC manual's list ofarchitecture-specific options, as well as more detailed explanations about the differences between -march, -mcpu, and -mtune.-O
Next up is the
-O variable. This controls the overall level of optimization. This makes the code compilation take somewhat more time, and can take up much more memory, especially as you increase the level of optimization.
There are seven
-O settings: -O0, -O1, -O2, -O3, -Os, -Og, and -Ofast. You should use only one of them in /etc/portage/make.conf.
With the exception of
-O0, the -O settings each activate several additional flags, so be sure to read the GCC manual's chapter on optimization options to learn which flags are activated at each -O level, as well as some explanations as to what they do.
Let's examine each optimization level:
-O0: This level (that's the letter "O" followed by a zero) turns off optimization entirely and is the default if no-Olevel is specified in CFLAGS or CXXFLAGS. This reduces compilation time and can improve debugging info, but some applications will not work properly without optimization enabled. This option is not recommended except for debugging purposes.
-O1: This is the most basic optimization level. The compiler will try to produce faster, smaller code without taking much compilation time. It's pretty basic, but it should get the job done all the time.
-O2: A step up from-O1. This is the recommended level of optimization unless you have special needs.-O2will activate a few more flags in addition to the ones activated by-O1. With-O2, the compiler will attempt to increase code performance without compromising on size, and without taking too much compilation time.
-O3: This is the highest level of optimization possible. It enables optimizations that are expensive in terms of compile time and memory usage. Compiling with-O3is not a guaranteed way to improve performance, and in fact in many cases can slow down a system due to larger binaries and increased memory usage.-O3is also known to break several packages. Therefore, using-O3is not recommended.
-Os: This option will optimize your code for size. It activates all-O2options that don't increase the size of the generated code. It can be useful for machines that have extremely limited disk storage space and/or have CPUs with small cache sizes.
-Og: In GCC 4.8, a new general optimization level,-Og, has been introduced. It addresses the need for fast compilation and a superior debugging experience while providing a reasonable level of runtime performance. Overall experience for development should be better than the default optimization level-O0. Note that-Ogdoes not imply-g, it simply disables optimizations that may interfere with debugging.
-Ofast: New in GCC 4.7, consists of-O3plus-ffast-math,-fno-protect-parens, and-fstack-arrays. This option breaks strict standards compliance, and is not recommended for use.
As previously mentioned,
-O2 is the recommended optimization level. If package compilation fails and you aren't using -O2, try rebuilding with that option. As a fallback option, try setting your CFLAGS and CXXFLAGS to a lower optimization level, such as -O1 or even -O0 -g2 -ggdb (for error reporting and checking for possible problems).-pipe
A common flag is
-pipe . This flag actually has no effect on the generated code, but it makes the compilation process faster. It tells the compiler to use pipes instead of temporary files during the different stages of compilation, which uses more memory. On systems with low memory, GCC might get killed. In that case, do not use this flag.-fomit-frame-pointer
This is a very common flag designed to reduce generated code size. It is turned on at all levels of
-O (except -O0) on architectures where doing so does not interfere with debugging (such as x86-64), but you may need to activate it yourself by adding it to your flags. Though the GCC manual does not specify all architectures it is turned on by using -O, you will need to explicitly activate it on x86. However, using this flag will make debugging hard to impossible.
In particular, it makes troubleshooting applications written in Java much harder, though Java is not the only code affected by using this flag. So while the flag can help, it also makes debugging harder; backtraces in particular will be useless. However, if you don't plan to do much software debugging and haven't added any other debugging-related CFLAGS such as
-ggdb, then you can try using -fomit-frame-pointer.
Important
Do not combine
-fomit-frame-pointer with the similar flag -momit-leaf-frame-pointer. Using the latter flag is discouraged, as -fomit-frame-pointeralready does the job properly. Furthermore, -momit-leaf-frame-pointer has been shown to negatively impact code performance.-msse, -msse2, -msse3, -mmmx, -m3dnow
These flags enable the SSE, SSE2, SSE3, MMX, and 3DNow! instruction sets for x86 and x86-64 architectures. These are useful primarily in multimedia, gaming, and other floating point-intensive computing tasks, though they also contain several other mathematical enhancements. These instruction sets are found in more modern CPUs.
Important
Be sure to check if your CPU supports these by running
cat /proc/cpuinfo. The output will include any supported additional instruction sets. Note that pni is just a different name for SSE3.
You normally don't need to add any of these flags to /etc/portage/make.conf as long as you are using the correct
-march (for example, -march=nocona implies -msse3). Some notable exceptions are newer VIA and AMD64 CPUs that support instructions not implied by -march (such as SSE3). For CPUs like these you'll need to enable additional flags where appropriate after checking the output of cat /proc/cpuinfo.
Note
You should check the list of x86 and x86-64-specific flags to see which of these instruction sets are activated by the proper CPU type flag. If an instruction is listed, then you don't need to specify it; it will be turned on by using the proper
-march setting.Optimization FAQs
But I get better performance with -funroll-loops -fomg-optimize!
No, you only think you do because someone has convinced you that more flags are better. Aggressive flags will only hurt your applications when used system-wide. Even the
GCCmanual says that using -funroll-loops and -funroll-all-loops makes code larger and run more slowly. Yet for some reason, these two flags, along with -ffast-math, -fforce-mem, -fforce-addr, and similar flags, continue to be very popular among ricers who want the biggest bragging rights.
The truth of the matter is that they are dangerously aggressive flags. Take a good look around the Gentoo Forums and Bugzilla to see what those flags do: nothing good!
You don't need to use those flags globally in CFLAGS or CXXFLAGS. They will only hurt performance. They may make you sound like you have a high-performance system running on the bleeding edge, but they don't do anything but bloat your code and get your bugs marked INVALID or WONTFIX.
You don't need dangerous flags like these. Don't use them. Stick to the basics:
-march, -O, and -pipe.What about -O levels higher than 3?
Some users boast about even better performance obtained by using
-O4, -O9, and so on, but the reality is that -O levels higher than 3 have no effect. The compiler may accept CFLAGS like -O4, but it actually doesn't do anything with them. It only performs the optimizations for -O3, nothing more.
Need more proof? Examine the
code source code:
[Collapse]
Code-O source code
if (optimize >= 3)
{
flag_inline_functions = 1;
flag_unswitch_loops = 1;
flag_gcse_after_reload = 1;
/* Allow even more virtual operators. */
set_param_value ("max-aliased-vops", 1000);
set_param_value ("avg-aliased-vops", 3);
}
As you can see, any value higher than 3 is treated as just
-O3.What about redundant flags?
Oftentimes CFLAGS and CXXFLAGS that are turned on at various
-O levels are specified redundantly in /etc/portage/make.conf. Sometimes this is done out of ignorance, but it is also done to avoid flag filtering or flag replacing.
Flag filtering/replacing is done in many of the ebuilds in the Portage tree. It is usually done because packages fail to compile at certain
-O levels, or when the source code is too sensitive for any additional flags to be used. The ebuild will either filter out some or all CFLAGS and CXXFLAGS, or it may replace -O with a different level.
The Gentoo Developer Manual outlines where and how flag filtering/replacing works.
It's possible to circumvent
-O filtering by redundantly listing the flags for a certain level, such as -O3, by doing things like:
However, this is not a smart thing to do. CFLAGS are filtered for a reason! When flags are filtered, it means that it is unsafe to build a package with those flags. Clearly, it is not safe to compile your whole system with
-O3 if some of the flags turned on by that level will cause problems with certain packages. Therefore, you shouldn't try to "outsmart" the developers who maintain those packages. Trust the developers. Flag filtering and replacing is done for your benefit! If an ebuild specifies alternative flags, then don't try to get around it.
You will most likely continue to run into problems when you build a package with unacceptable flags. When you report your troubles on Bugzilla, the flags you use in /etc/portage/make.confwill be readily visible and you will be told to recompile without those flags. Save yourself the trouble of recompiling by not using redundant flags in the first place! Don't just automatically assume that you know better than the developers.
What about LDFLAGS?
The Gentoo developers have already set basic, safe LDFLAGS in the base profiles, so you don't need to change them.
Can I use per-package flags?
Warning
Using per-package flags complicates debugging and support. Make sure you mention in your bug reports if you make use of this feature and what the changes are you made.
Information on how to use per-package environment variables (including CFLAGS) is described in the Gentoo Handbook, "Per-Package Environment Variables".
Resources
The following resources are of some help in further understanding optimization:
- Chapter 5 of the Gentoo Installation Handbooks
man make.conf
- The Gentoo Forums
Acknowledgements
We would like to thank the following authors and editors for their contributions to this guide:
- nightmorph
2014年2月20日星期四
restructured Text
http://forrestyu.net/art/math-in-restructuredtext/
https://github.com/mcepl/reStPlugin
https://github.com/mcepl/reStPlugin
2014年2月7日星期五
Arduino - ButtonStateChange加入debounce
Arduino - ButtonStateChange
/*
State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
and on to off.
The circuit:
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* LED attached from pin 13 to ground (or use the built-in LED on
most Arduino boards)
created 27 Sep 2005
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/ButtonStateChange
*/
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
int reading = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (reading != lastButtonState) {
// reset the debouncing timer
//Serial.println("state changed");
lastDebounceTime = millis();
}
if( (millis() - lastDebounceTime) > debounceDelay ) {
if (buttonState != reading) {
buttonState = reading;
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
//Serial.println((millis() - lastDebounceTime));
}
else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = reading;
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
/*
State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
and on to off.
The circuit:
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* LED attached from pin 13 to ground (or use the built-in LED on
most Arduino boards)
created 27 Sep 2005
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/ButtonStateChange
*/
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
int reading = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (reading != lastButtonState) {
// reset the debouncing timer
//Serial.println("state changed");
lastDebounceTime = millis();
}
if( (millis() - lastDebounceTime) > debounceDelay ) {
if (buttonState != reading) {
buttonState = reading;
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
//Serial.println((millis() - lastDebounceTime));
}
else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = reading;
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
2013年12月21日星期六
万年历程序
#include
#include
#include
int week(int y,int m,int d);//函数声明
void main()
{
//初始化月份的天数
int monthday[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int y,w,i,m=1,d=1;
printf("请输入一个年份yyyy:\n");
scanf("%d",&y);
//如果是闰年,修改第二个月天数
if ( (y % 4 == 0 && y % 100 != 0)|| y % 400 == 0 ){
monthday[1]=29;
}
for(m=1;m<=12;m++){
//循环打印每个月
printf("\n %d年,%d月\n",y,m);
printf(" 日 一 二 三 四 五 六 \n");
for (d=1;d<=monthday[m-1];d++){
//获取对应的星期
w=week(y,m,d);
if(d==1){
//打印每月第一天前面的空格
for (i=0;i printf("%3c ",' ');
}
}
printf("%3d ",d);
//每星期换行
if(w==6) printf(" \n");
}
printf("\n\n输入任意字符继续\n");
getch();
}
system("pause");
}
int week (int y,int m,int d)
{
//http://hi.baidu.com/wlzqi/blog/item/65b16b606403df44ebf8f8a2.html
int w;
if((m==1)||(m==2)){
y--;
m+=12;
}
w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1)%7;
return w;
}
#include
#include
int week(int y,int m,int d);//函数声明
void main()
{
//初始化月份的天数
int monthday[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int y,w,i,m=1,d=1;
printf("请输入一个年份yyyy:\n");
scanf("%d",&y);
//如果是闰年,修改第二个月天数
if ( (y % 4 == 0 && y % 100 != 0)|| y % 400 == 0 ){
monthday[1]=29;
}
for(m=1;m<=12;m++){
//循环打印每个月
printf("\n %d年,%d月\n",y,m);
printf(" 日 一 二 三 四 五 六 \n");
for (d=1;d<=monthday[m-1];d++){
//获取对应的星期
w=week(y,m,d);
if(d==1){
//打印每月第一天前面的空格
for (i=0;i
}
}
printf("%3d ",d);
//每星期换行
if(w==6) printf(" \n");
}
printf("\n\n输入任意字符继续\n");
getch();
}
system("pause");
}
int week (int y,int m,int d)
{
//http://hi.baidu.com/wlzqi/blog/item/65b16b606403df44ebf8f8a2.html
int w;
if((m==1)||(m==2)){
y--;
m+=12;
}
w=(d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1)%7;
return w;
}
2013年12月10日星期二
grep 用法
我本不想写这篇文章,首先我觉得这些东西大家肯定都知道,其次就算真不知道还有手册。
直到那天面试的时候我碰到一个哥们,我问他grep你都知道哪些选项?他告诉我,只有-r。我当时就乐了,既然grep是你常用的命令,你凭什么只 知道-r?他回答说,他只想把精力放到内核上,没有时间来学习这些东西。我笑,正是因为你没有时间,所以你才应该提高你的工作效率,而熟悉命令行显然是 Linux上一种提高工作效率的方式。有句老话说得好:“磨刀不误砍柴功。”
有的同学可能觉得我在提倡死记硬背了,事实上我比你更反对中国教育的那种死记硬背。我的观点很简单:既然你用得多,那么有些东西,比如grep的一些选项,自然而然就应该记住了,无须刻意去背。
所以,我在这里以grep为例来展示一下。注意,以下内容没有参考一眼grep的手册。
grep最常用的选项可能是-i,-n和-r了,至少于我如此。-i是忽略大小写,-n可以告诉你找到的东西在文件的哪一行。-r或者-R(看你愿不愿意多按个shift键了),可以去递归一个目录。
-A和-B,你可能就用的比较少了,前者制定显示匹配到的那一行之后的几行,后者指定之前的,比如grep -A 3 -B 4就是说也要显示匹配到的那一行之前的4行和之后的3行,可见A是After,B是Before。用得着刻意去记嘛?显然不用。
-I(大写i)可能用得就更不多了,可惜啊,它非常有用。比如你编译出的内核二进制和你的源代码在同一个目录时,你grep一些字符串的时候会发现一些.o文件中也可以找到,很明显它不是我们想要的,这时候-I就派上用场啦!它告诉grep去忽略二进制文件。
这让我想到了另一个--exclude(我记得似乎没有短选项与之对应),顾名思义,它是用来排除一些文件。比如你编译的内核目录下还有*.cmd这种文件的话,它不是二进制,所以-I排除不掉,这时候你就可以用--exclude "*.cmd"了。
-H,这个用得更少了,你一般不会需要它,因为grep默认就会输出文件名。然而,当grep与find联手的时候就不会了(至于为什么,留给你作 为课后作业),这时候你就要用到-H了。比如,我在内核源代码目录下查找CONFIG_DEBUG_KMEMLEAK定义在哪,我通常这么做:find . -iname 'kconfig*' -exec grep -Hwn DEBUG_KMEMLEAK '{}' \;
我上面用到了另一个选项-w,看见了嘛?它可能是另外一个被严重忽视了的选项,仅次于-I啊!它的意思是告诉grep我所查找的是一个完整的单词, 也就是说,当你找DEBUG_KMEMLEAK的时候它不会给你找出DEBUG_KMEMLEAK_EARLY_LOG_SIZE,你懂的。这可以省去你 手工去加\b了。
噢,我差点儿忘了亲爱的-e,多数情况下你也不需要它,因为grep后面接的就是一个regrex嘛!-e神马时候派上用场呢?我建议你在这里仔细 想想,一个很特殊的情况——我要搜索的字符串以"-"开头时!比如我要搜索"-wangcong"这个字符串,直接grep "-wangcong"显然是不行滴!grep会认为那是"-w -a -n -g -c -o -n -g",无论你怎么加引号!一种解决方法是加反斜线,而另一种方法就是-e "-wangcong"了。顺便说一句,使用多次-e就相当于进行一个“或”操作,所以grep "vmx\|svm"就等价于grep -e vmx -e svm。
-o我估计用的人也不多,它的意思是只输出匹配到的东西,同一行的其它东西不输出。例如,我想搜索printk.c中全部的C语言字符串时,我会这 么做:grep -o '".*"' kernel/printk.c,有点儿类似于strings kernel/printk.o。
-b,知道这个人的灰常少了吧?如果你知道,恭喜你晋级grep高手级别了!我承认我只用过它一次,是在一个脚本中,我想知道某个“字符串”出现在 文件的第几个字节。我印象中这里是有bug的,因为我当时总得不到正确的结果,当然也有可能是我理解不对,没看手册而且没有再次实验,所以这个问题就留给 你了。:-)
-q嘛,大家都知道,脚本中常用。
-c嘛,比如统计CPU个数:grep -c '^processor' /proc/cpuinfo,实在没必要多一个管道去 grep '^processor' /proc/cpuinfo | wc -l。
好了,我就想起来这么多了,欢迎补充。我觉得一个好的Linux程序员应该对他/她敲出的每一行命令的每一个选项都精益求精,不多不少。
我知道有些人对此不屑一顾,嗤之以鼻,我只想告诉这些人一句话:“天下大事必做于细,天下难事必做于易。”你要是认为我这是在教育你,你就错大了,我对教育人,尤其是教育你这种人,没任何兴趣!你倒找给我钱我都不会稀罕去教育你!有他妈的多远给我滚他妈的多远!
附我窜改的《见与不见》:
你知,或者不知它/命令就在那里/不悲不喜
你看,或者不看它/手册就在那里/不来不去
你爱,或者不爱它/程序就在那里/不吵不闹
你用,或者不用它/二进制就在你的机器上/不亢不卑
去了解它们/或者/让它住进你的心里
人机合一/融为一体
直到那天面试的时候我碰到一个哥们,我问他grep你都知道哪些选项?他告诉我,只有-r。我当时就乐了,既然grep是你常用的命令,你凭什么只 知道-r?他回答说,他只想把精力放到内核上,没有时间来学习这些东西。我笑,正是因为你没有时间,所以你才应该提高你的工作效率,而熟悉命令行显然是 Linux上一种提高工作效率的方式。有句老话说得好:“磨刀不误砍柴功。”
有的同学可能觉得我在提倡死记硬背了,事实上我比你更反对中国教育的那种死记硬背。我的观点很简单:既然你用得多,那么有些东西,比如grep的一些选项,自然而然就应该记住了,无须刻意去背。
所以,我在这里以grep为例来展示一下。注意,以下内容没有参考一眼grep的手册。
grep最常用的选项可能是-i,-n和-r了,至少于我如此。-i是忽略大小写,-n可以告诉你找到的东西在文件的哪一行。-r或者-R(看你愿不愿意多按个shift键了),可以去递归一个目录。
-A和-B,你可能就用的比较少了,前者制定显示匹配到的那一行之后的几行,后者指定之前的,比如grep -A 3 -B 4就是说也要显示匹配到的那一行之前的4行和之后的3行,可见A是After,B是Before。用得着刻意去记嘛?显然不用。
-I(大写i)可能用得就更不多了,可惜啊,它非常有用。比如你编译出的内核二进制和你的源代码在同一个目录时,你grep一些字符串的时候会发现一些.o文件中也可以找到,很明显它不是我们想要的,这时候-I就派上用场啦!它告诉grep去忽略二进制文件。
这让我想到了另一个--exclude(我记得似乎没有短选项与之对应),顾名思义,它是用来排除一些文件。比如你编译的内核目录下还有*.cmd这种文件的话,它不是二进制,所以-I排除不掉,这时候你就可以用--exclude "*.cmd"了。
-H,这个用得更少了,你一般不会需要它,因为grep默认就会输出文件名。然而,当grep与find联手的时候就不会了(至于为什么,留给你作 为课后作业),这时候你就要用到-H了。比如,我在内核源代码目录下查找CONFIG_DEBUG_KMEMLEAK定义在哪,我通常这么做:find . -iname 'kconfig*' -exec grep -Hwn DEBUG_KMEMLEAK '{}' \;
我上面用到了另一个选项-w,看见了嘛?它可能是另外一个被严重忽视了的选项,仅次于-I啊!它的意思是告诉grep我所查找的是一个完整的单词, 也就是说,当你找DEBUG_KMEMLEAK的时候它不会给你找出DEBUG_KMEMLEAK_EARLY_LOG_SIZE,你懂的。这可以省去你 手工去加\b了。
噢,我差点儿忘了亲爱的-e,多数情况下你也不需要它,因为grep后面接的就是一个regrex嘛!-e神马时候派上用场呢?我建议你在这里仔细 想想,一个很特殊的情况——我要搜索的字符串以"-"开头时!比如我要搜索"-wangcong"这个字符串,直接grep "-wangcong"显然是不行滴!grep会认为那是"-w -a -n -g -c -o -n -g",无论你怎么加引号!一种解决方法是加反斜线,而另一种方法就是-e "-wangcong"了。顺便说一句,使用多次-e就相当于进行一个“或”操作,所以grep "vmx\|svm"就等价于grep -e vmx -e svm。
-o我估计用的人也不多,它的意思是只输出匹配到的东西,同一行的其它东西不输出。例如,我想搜索printk.c中全部的C语言字符串时,我会这 么做:grep -o '".*"' kernel/printk.c,有点儿类似于strings kernel/printk.o。
-b,知道这个人的灰常少了吧?如果你知道,恭喜你晋级grep高手级别了!我承认我只用过它一次,是在一个脚本中,我想知道某个“字符串”出现在 文件的第几个字节。我印象中这里是有bug的,因为我当时总得不到正确的结果,当然也有可能是我理解不对,没看手册而且没有再次实验,所以这个问题就留给 你了。:-)
-q嘛,大家都知道,脚本中常用。
-c嘛,比如统计CPU个数:grep -c '^processor' /proc/cpuinfo,实在没必要多一个管道去 grep '^processor' /proc/cpuinfo | wc -l。
好了,我就想起来这么多了,欢迎补充。我觉得一个好的Linux程序员应该对他/她敲出的每一行命令的每一个选项都精益求精,不多不少。
我知道有些人对此不屑一顾,嗤之以鼻,我只想告诉这些人一句话:“天下大事必做于细,天下难事必做于易。”你要是认为我这是在教育你,你就错大了,我对教育人,尤其是教育你这种人,没任何兴趣!你倒找给我钱我都不会稀罕去教育你!有他妈的多远给我滚他妈的多远!
附我窜改的《见与不见》:
你知,或者不知它/命令就在那里/不悲不喜
你看,或者不看它/手册就在那里/不来不去
你爱,或者不爱它/程序就在那里/不吵不闹
你用,或者不用它/二进制就在你的机器上/不亢不卑
去了解它们/或者/让它住进你的心里
人机合一/融为一体
shell中if的相关参数
[ -a FILE ] 如果 FILE 存在则为真。
[ -b FILE ] 如果 FILE 存在且是一个块特殊文件则为真。
[ -c FILE ] 如果 FILE 存在且是一个字特殊文件则为真。
[ -d FILE ] 如果 FILE 存在且是一个目录则为真。
[ -e FILE ] 如果 FILE 存在则为真。
[ -f FILE ] 如果 FILE 存在且是一个普通文件则为真。
[ -g FILE ] 如果 FILE 存在且已经设置了SGID则为真。
[ -h FILE ] 如果 FILE 存在且是一个符号连接则为真。
[ -k FILE ] 如果 FILE 存在且已经设置了粘制位则为真。
[ -p FILE ] 如果 FILE 存在且是一个名字管道(F如果O)则为真。
[ -r FILE ] 如果 FILE 存在且是可读的则为真。
[ -s FILE ] 如果 FILE 存在且大小不为0则为真。
[ -t FD ] 如果文件描述符 FD 打开且指向一个终端则为真。
[ -u FILE ] 如果 FILE 存在且设置了SUID (set user ID)则为真。
[ -w FILE ] 如果 FILE 如果 FILE 存在且是可写的则为真。
[ -x FILE ] 如果 FILE 存在且是可执行的则为真。
[ -O FILE ] 如果 FILE 存在且属有效用户ID则为真。
[ -G FILE ] 如果 FILE 存在且属有效用户组则为真。
[ -L FILE ] 如果 FILE 存在且是一个符号连接则为真。
[ -N FILE ] 如果 FILE 存在 and has been mod如果ied since it was last read则为真。
[ -S FILE ] 如果 FILE 存在且是一个套接字则为真。
[ FILE1 -nt FILE2 ] 如果 FILE1 has been changed more recently than FILE2, or 如果 FILE1 exists and FILE2 does not则为真。
[ FILE1 -ot FILE2 ] 如果 FILE1 比 FILE2 要老, 或者 FILE2 存在且 FILE1 不存在则为真。
[ FILE1 -ef FILE2 ] 如果 FILE1 和 FILE2 指向相同的设备和节点号则为真。
[ -o OPTIONNAME ] 如果 shell选项 “OPTIONNAME” 开启则为真。
[ -z STRING ] “STRING” 的长度为零则为真。
[ -n STRING ] or [ STRING ] “STRING” 的长度为非零 non-zero则为真。
[ STRING1 == STRING2 ] 如果2个字符串相同。 “=” may be used instead of “==” for strict POSIX compliance则为真。
[ STRING1 != STRING2 ] 如果字符串不相等则为真。
[ STRING1 < STRING2 ] 如果 “STRING1” sorts before “STRING2” lexicographically in the current locale则为真。
[ STRING1 > STRING2 ] 如果 “STRING1” sorts after “STRING2” lexicographically in the current locale则为真。
[ ARG1 OP ARG2 ] “OP” is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true if “ARG1” is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to “ARG2”, respectively. “ARG1” and “ARG2” are integers.
源于:http://hi.baidu.com/piaoliuzaiwai/blog/item/2000f3fc9ec960fcfc037f7f.html
[ -b FILE ] 如果 FILE 存在且是一个块特殊文件则为真。
[ -c FILE ] 如果 FILE 存在且是一个字特殊文件则为真。
[ -d FILE ] 如果 FILE 存在且是一个目录则为真。
[ -e FILE ] 如果 FILE 存在则为真。
[ -f FILE ] 如果 FILE 存在且是一个普通文件则为真。
[ -g FILE ] 如果 FILE 存在且已经设置了SGID则为真。
[ -h FILE ] 如果 FILE 存在且是一个符号连接则为真。
[ -k FILE ] 如果 FILE 存在且已经设置了粘制位则为真。
[ -p FILE ] 如果 FILE 存在且是一个名字管道(F如果O)则为真。
[ -r FILE ] 如果 FILE 存在且是可读的则为真。
[ -s FILE ] 如果 FILE 存在且大小不为0则为真。
[ -t FD ] 如果文件描述符 FD 打开且指向一个终端则为真。
[ -u FILE ] 如果 FILE 存在且设置了SUID (set user ID)则为真。
[ -w FILE ] 如果 FILE 如果 FILE 存在且是可写的则为真。
[ -x FILE ] 如果 FILE 存在且是可执行的则为真。
[ -O FILE ] 如果 FILE 存在且属有效用户ID则为真。
[ -G FILE ] 如果 FILE 存在且属有效用户组则为真。
[ -L FILE ] 如果 FILE 存在且是一个符号连接则为真。
[ -N FILE ] 如果 FILE 存在 and has been mod如果ied since it was last read则为真。
[ -S FILE ] 如果 FILE 存在且是一个套接字则为真。
[ FILE1 -nt FILE2 ] 如果 FILE1 has been changed more recently than FILE2, or 如果 FILE1 exists and FILE2 does not则为真。
[ FILE1 -ot FILE2 ] 如果 FILE1 比 FILE2 要老, 或者 FILE2 存在且 FILE1 不存在则为真。
[ FILE1 -ef FILE2 ] 如果 FILE1 和 FILE2 指向相同的设备和节点号则为真。
[ -o OPTIONNAME ] 如果 shell选项 “OPTIONNAME” 开启则为真。
[ -z STRING ] “STRING” 的长度为零则为真。
[ -n STRING ] or [ STRING ] “STRING” 的长度为非零 non-zero则为真。
[ STRING1 == STRING2 ] 如果2个字符串相同。 “=” may be used instead of “==” for strict POSIX compliance则为真。
[ STRING1 != STRING2 ] 如果字符串不相等则为真。
[ STRING1 < STRING2 ] 如果 “STRING1” sorts before “STRING2” lexicographically in the current locale则为真。
[ STRING1 > STRING2 ] 如果 “STRING1” sorts after “STRING2” lexicographically in the current locale则为真。
[ ARG1 OP ARG2 ] “OP” is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true if “ARG1” is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to “ARG2”, respectively. “ARG1” and “ARG2” are integers.
源于:http://hi.baidu.com/piaoliuzaiwai/blog/item/2000f3fc9ec960fcfc037f7f.html
订阅:
博文 (Atom)