Study Notes: GNU Linux Programming Guide (version 2): 1

Source: Internet
Author: User
Tags openlog syslog perl script

Directory:

Chapter 1 Linux and Linux programming Overview

Chapter 2 set up a Development System

Chapter 3 Use GNU CC

Chapter 4 Use GNU make to manage projects

Chapter 5 create a portable self-Configuration Software GNU autoconf

Chapter 6 Comparison and merge source code files

Chapter 7 Version Control Using RCS and CVS

Chapter 8 debugging

Chapter 9 error handling

Note: 639 pages of the original book have a wide range of content, making it difficult to quickly locate key points. During my first reading, I will extract the key points and record my experiences to form this note for future reference and study.

Description: $ indicates the terminal to enter the command

Chapter 1 Linux and Linux programming Overview

1. Linux is not Unix. Unix is a registered trademark. It must meet a large number of terms and pay a considerable fee to be licensed for use.
Linux runs similar to Unix in terms of features. All kernel code is manually written by Linus and several core hackers.
Many programs running on Linux are also manually written, of course, also transplanted.

Linux is similar to Unix because it complies with POSIX standards.

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

Chapter 2 configure the development system Chapter 3 Use GNU CC

1. GCC can compile C language variants such as ansi c and traditional C
GCC can compile C, C ++, and Objective C
GNU Compiler Collection
2. Add search path-I <for header files>

gcc hello.c -I /home/fred/include -o hello

3. Add search path-L <for library files>

gcc hello.c -L/home/fred/lib -lnew -o hello

Gcc first searches for the library files under/home/fred/lib, and then searches for the files in the default path.
-L option enables the linked program to use the target code in the specified function library
4. Common usage

gcc hello.c -L/home/fred/lib -I /home/fred/include -lnew -o hello

Tell GCC to link libnew. so, find libnew. so in/home/fred/lib, and find any non-standard header files in/home/fred/include.
5. enabling any debugging option will increase the size of the binary file dramatically.
6. Get the target file using gcc-c filename.

Chapter 4 Use GNU make to manage projects

1. make is a tool for controlling the compilation or repeated compilation of software.
Make can automatically manage the content, methods, and timing of software compilation, so that programmers can focus on coding.
2. Why do I use make?
(1). Projects that contain multiple source files have long and complex command lines during compilation.
(2). Reduce the time required for repeated compilation. (Compile the modified part)
(3). Build a dependency information database and check whether the required files can be found.
(4). Able to build a stable compiling environment
(5) make the compilation process run automatically
3. makefile
(1). database files in text format, including rules that tell make which files to compile, how to compile, and under which conditions to compile
(2). Rules-three parts
<1>. target: the object to be created by make.
<2>. denpendency: contains one or more dependency lists, which are usually other files required to compile the target body.
<3>. command: The command list to be executed to create the target body from the specified dependency.
Target is usually a program, but it can be a text file, a manual, or anything else.
Commands can be compiler commands, shell commands, or commands that can be completed by any command line.
(3). General Form

  target : dependency [denpendency [...]]               command               command                [...]

Note: the first character of each command must be a tab.
4. A makefile file

  sayHelloApp: main.o simple_fun.o simple_fun.hgcc main.o simple_fun.o -o sayHelloApp  simple_fun.o: simple_fun.c simple_fun.hgcc -c simple_fun.c  main.o: main.cgcc -c main.c  .PHONY : clean  clean: rm main.o simple_fun.o

5. pseudo targets
The clean in the above makefile file does not correspond to the actual file, but is a pseudo target.
The pseudo-target specifies the command to be executed by make.
Clean has no dependency body, so its command will not be automatically executed. Use make clean
If you do not use. PHONY, make will find it if there is a clean file,
However, after. PHONY is used, make does not check whether there is a file with a file name that matches the name in the dependent body, and directly runs the command
6. Variables
Definition: VARNAME = some_text
Usage: $ (VARNAME)
In addition to User-Defined variables, make runs environment variables, automatic variables, and pre-defined variables.
(1) environment variable: If the makefile contains the same name, take the environment variable in makefile as the standard.
(2) Automatic variables: make automatically replaces the variables with specific and well-known values. $ (@ F): the part of the target file name ;...
(3) pre-defined variables: used to define the program name or pass the flag and parameters to these programs. CC: C compiled program; RM: file deletion program ;...
7. Pattern rules
One way to extend the implicit rules of make.
Similar to common rules, but its target must have the symbol "%", which can be matched by any non-null string.
The dependency file must also use %
8. Notes
#
9. Command Line
-F file: Specifies the name of The makefile.
-N: print the commands that will be executed, but do not actually execute these commands
-S: the command name is not printed during execution.
-W: If make changes the directory during execution, print the current directory name.
-D: Print debugging information
Chapter 5 create a portable self-Configuration Software GNU autoconf

1. autoconf
It generates a shell script that can automatically configure the source code package, so that the program can be compiled and run on many non-branded UNIX and UNIX-like systems.
These scripts are usually named configure. They check whether certain functions required by the program are provided in the current system and generate makefile.
./Configure
2. configure. in
To generate the configure script, you must create a file named configure. in under the root directory of the source file tree.
It calls a series of autoconf macros to test whether the features required or used by the program exist and the functions of these features.
3. Common formats of configure. in files

AC_INIT # AC_INIT (unique_file_in_source_dir), used to test whether the program is correctly tested in the current directory # one row of test function library for each macro # if more than one row, use [] and \, [] expand the existing parameter test header file # AC_CHECK_HEADERS ([head1.h header2.h \ test type definition # header3.h]) Test Structure Test compiler behavior test Library Function Test System Call AC_OUTPUT # AC_OUTPUT (file) file is a list of output files separated by spaces # used to create an output file named makefile or another name

4. Run autoscan
Autoscan is included in the autoconf package (sudo apt-get install autoconf ),
Is a Perl script
Extract information related to the function call and header file from the source file and output it to the configure. scan file.
5. config. h. in File
Contains all the # define commands required by the program
Run the shell script named autoheader that comes with autoconf.
Autoheader reads configure. in, acconfig. h,
The acconfig. h (that is,./acconfig. h) file used to save the preprocessing symbol is located in the source code root path to generate the config. h. in file.
6../acconfig. h
You only need to include the legally defined C-style preprocessing symbols that can be read and used by autoconf and autoheader.
Set the macro value to 1
7. Process

(1 ). compile the source file and Makefile. in file and acconfig. h file (2 ). run autoscan to get configure. scan (3 ). rename by configure. scan to get configure. in (4 ). run autoheader by acconfig. h and configure. in to get config. h. in (5 ). run autoconf by configure. in to get configure (6 ).. /configure by config. h. in to get Config. h by Makefile. in to get Makefile (7 ). run make to get the app from makefile
Chapter 6 Comparison and merge source code files

1. Differences between diff and patch
If diff is considered to be a differential file generated by subtracting one file from another to generate two files
We can assume that patch uses the difference file and the source file to generate another source file.
2. diff outputs two files side by side

 diff -y -W 80 a.vim b.vim

3. diff3
When two people modify a shared file at the same time, diff3 will play a role.
It compares two sets of modifications made by two people, creates 3rd files, saves the merged output results, and points out the conflicts between the two parties.
Chapter 7 control version with RCS and CVS Chapter 8 debugging

1. gdb gnu DeBugger
One of the main Software tools of the Free Software Foundation (FSF)
2. make progname
Compile the source file main. c
Use make main. c to output cc main. c-o main and obtain the main executable file.
3. Steps for using gdb
(1). Use gcc-g test. c-o test
With the-g option, compiled executable code contains debugging information. Otherwise, gdb cannot load or modify the execution file.
(2). gdb test [core]
Core is an optional file, and memory is transferred to the file to enhance the debugging capability of gdb.
Enter the interactive interface of gdb commands
4. gdb common Debugging commands
(1). l view the Loaded File
Note: You can use the scaling form in gdb:

For example, l Represents list; B Represents brekpoint; p represents print r represents run n represents next c Represents continue

(2). B. set breakpoints

B 6. Set the breakpoint tbreak 6 on Line 1 to set a temporary breakpoint. After running, the ignore 6 will be automatically removed. ignore the breakpoint 6 enable 6 to activate the breakpoint 6 disable 6 to make the breakpoint 6 invalid.

(3). info B. View breakpoints
(4). delete remove a breakpoint
Delete 1 remove a breakpoint with the breakpoint Number 1
(5) run the code
The first line of the Code is run by default.
Run 6 runs from row 6
(6). p: View variable values
P I: view the value of variable I
Result: $1 = 2
'$ 1' indicates variable I.
(7). n \ s single-step operation
When a function is called, s will enter the function, and n will not enter the function.
(8). c continue
C: run until the function ends or the next breakpoint.
Finish: run until the function ends.
5. Other common gdb commands
(1). help
$ Help
$ Help running
Chapter 9 error handling

1. assert

 #include <assert.h> void assert(int expression);

If the expression value is false (0), an error message is printed to stderr, and the program is terminated using the abort function.
2. If
Add the following statement before include <assert. h>.
# Define NDEBUG
The assert macro is not called.
3. Use System Logs
Linux uses two daemon, klogd and syslogd, to provide centralized system log functions.
Syslogd controls the generation of messages from user space programs.
Klogd is used by the kernel and programs running in the kernel space, especially the device driver.
In most Linux systems, system logs are stored in the/var/log directory, including messages, debug, mail, and news.
Other logs may also exist, depending on the log function configuration defined in/etc/syslog. conf (Note: Ubuntu has no files)

The standard console log daemon is syslogd, which maintains these log files.
Messages written to system logs are controlled by their level and function (facility,
Level indicates the message severity or importance, and the function tells the program that the syslogd daemon maintains the system log to send the message.
The level and function of a log message are collectively referred to as its priority ).
4. syslog Log Level

Level severity LOG_EMERG system unavailable LOG_ALERT requires immediate handling of major LOG_CRIT errors, such as hard disk failure LOG_ERR error condition LOG_WARNING warning condition LOG_NOTICE normal but important message LOG_INFO purely Reporting Message LOG_DEBUG debugging or tracking output

5. syslog function value

Function Message source LOG_AUTHPRIV private security and authorization message LOG_CRON Clock daemon (crond and atd) LOG_DAEMON other system daemprocesses LOG_KERN kernel message LOG_LOCAL [0-7] retains the internal message LOG_USER generated by LOG_LPR Printing Subsystem LOG_MAIL mail subsystem LOG_NEWS News news subsystem LOG_SYSLOGsyslog for local/Site Use (default value) user-level message LOG_UUCP uucp Subsystem

Note: When an error occurs, LOG_WARN is sufficient for user-level programs.
LOG_INFO is most suitable for annoying log messages.
LOG_ERR has a possibly fatal system error.
6. System Log Functions
The header file <syslog. h> defines the syslogd interface.
Create a log message and use the syslog function. The prototype is as follows:

#include <syslog.h>void syslog(int priority, char* format,...);     

Priority is the level and function bit logic "or" Value
Format specifies the log writing message and any format description string similar to printf.
% M is replaced by an error message assigned by strerror errno.
7. Simple Example

/*************************************** * ******************* Program code /***************** **************************************** **/# include <stdio. h> # include <syslog. h> int main (int argc, int ** argv) {// syslog (LOG_WARNING | LOG_USER, \ "This is a warning from % s, % s, % m \ n", \ _ FILE __,__ DATE __,__ TIME __); // In ubuntu, LOG_INFO is also written to the/var/log/syslog file. // LOG_USER is the default function-level syslog (LOG_INFO, "This is a normal message from % s \ n" ,__ FILE _); return 1 ;} /*************************************** * ******************** running result /***************** **************************************** ** // * in the syslog file under/var/log, there are two records: Sep 3 16:39:52 jarvischu-Studio-1435 using_syslog: This is a warning from using_syslog.c, Sep 3 2011 16:39:47, SuccessSep 3 16:39:52 jarvischu-Studio-1435 using_syslog: This is a normal message from using_syslog.c */

8. openlog custom log operations, mainly by prefix

#include <syslog.h>void openlog(const char *ident, int option, int facility);

Ident: Specifies the string before the log message.
Option: The bit logical "or" value of multiple options.

LOG_PID contains PID LOG_CONS in each message. If the message cannot be written into the log file, it is sent to the console LOG_NDELAY to open the link immediately (by default, the link is opened when syslog is called for the first time) LOG_PERROR writes messages to log files and outputs them to stderr.

Facility: A value in 5.
Example:

openlog("JarvisChu",LOG_PID,LOG_USER);syslog(LOG_INFO|LOG_USER,"This is a message\n");

The/var/log/syslog file contains the following records:
JarvisChu [1231]: This is a message
9. Other functions
(1). closelog ()
As openlog can be used to disable the file descriptor opened by openlog.
(2). int setlogmask (int priority );
Set the default level of all log messages (that is, the level of messages that can be written to syslogs and those that cannot be written)
The function returns the original priority.
Syslog rejects any priority messages that are not set in the mask.

Same macro:

LOG_MASK (int priority): Creates a mask consisting of only one priority. LOG_UPTO (int priority): Creates a mask consisting of a series of descending priorities.

For example, the mask created by LOG_UPTO (LOG_NOTICE) includes messages of any level from LOG_EMERG to LOG_NOTICE.

LOG_INFO and LOG_DEBUG messages cannot pass

To be continued...

Author: Jarvis Chu

Starter: CSDN Blog

Reprinted please indicate the source: http://blog.csdn.net/jarvischu/article/details/6747420

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.