Linux programming Basics

Source: Internet
Author: User
Experiment 2 Linux programming Basics

I. Tutorial Purpose
Familiar with the C language programming method in Linux. By using the process control system calling function in programming, You can intuitively understand the concurrent execution of processes in Linux.

Ii. Lab questions
Use VI to edit the C language source program, analyze the example program, use man commands to familiarize yourself with relevant system calls, compile the program for concurrent execution of processes, and compile the program using tools such as GCC and make; execute the compiled execution file and analyze the result.

Iii. Background materials
Because the Linux environment used in the experiment is dominated by character interfaces, while the Linux character interface is not widely used in integrated development environments, the typical C language development mode still uses the text editing software to compile the source program, then use the GCC and make tools to compile the link and generate executable files. Different text editing tools can be used in the editing of source programs. For example, you can use gedit or kedit on the graphic user interface, and VI, emacs, and nano editors on the Character interface; it can be edited in other environments and uploaded through FTP.
(1) Use of editor vi
VI or Vim is a classic text editing tool in Linux. It is widely used in system management and program development on the Character interface. This experiment requires you to be familiar with the basic operations of vi. You can use VI for text editing.
1. Call vi
The most common command mode is: VI filename
2. Three Modes of vi
Command mode, used to input commands;
Insert mode, used to insert text;
Visual mode for visual highlighting and text selection.
3. Save and exit the file
Command mode is the default mode of vi. If it is in another mode, you need to switch it through the ESC key, and then enter the number, VI will wait for the command to be entered at the bottom of the screen;
: W save;
: W filename is saved as filename;
: WQ! Save and exit;
: WQ! Filename Note: Save the file name as filename and exit;
: Q! Do not save and exit;
Save and exit. Function and: WQ! Same
4. move the cursor;
After you Press ESC to Enter command mode, you can use the following key bits to move the cursor;
J. Move a row down;
K. Move a row up;
H: move one character to the left;
L move one character to the right;
CTRL + B Move the screen up;
CTRL + F move one screen down;
Move up arrow up;
The downward arrow moves down;
Move to the left arrow;
The right arrow moves to the right;
For keys J, K, L, and H, you can add numbers before these commands, such as 3j, to move three rows down.
5. Enter the insert mode.
I insert before the cursor;
A is inserted after the cursor;
I insert at the beginning of the row where the cursor is located;
A is inserted at the end of the row where the cursor is located;
O insert a row above the row where the cursor is located;
O insert a row under the row where the cursor is located;
S. delete a character after the cursor and enter the insert mode;
S. Delete the row where the cursor is located and enter the insert mode;
6. delete text content
X deletes a character;
# X delete several characters, # indicates a number, for example, 3x;
DW deletes a word;
# DW deletes several words. # It is represented by numbers. For example, 3dw deletes three words;
Dd deletes a row;
# Dd deletes multiple rows and # represents numbers. For example, 3DD deletes the cursor row and the cursor's next two rows;
D $ Delete the content from the cursor to the end of the line;
J. Clear the space between the row where the cursor is located and the previous line, and link the cursor row with the previous line;
7. Visual Mode
In the latest Linux release version, VI provides the visual mode. Press ESC, and then press V to enter the visual mode. Exit the visual mode, or press ESC. The visual mode allows you to select a text range to highlight the text.
8. Copying and pasting
Copy: You can copy the selected text in visual mode by Y; by YY, you can copy the row where the current cursor is located. In addition, deletion also means cutting. When we delete the text, the corresponding content will be automatically copied;
Paste: you can move the cursor somewhere and press P or SHIFT + P to paste it. P sticks the post after the cursor; Shift + P sticks the post before the cursor.
9. row number
You can enter set number in command mode to display the row number. Enter set number to disable the display of the row number.
10. Search
In command mode, enter/or? You can search;
/Search Note: Forward search, press the n key to move the cursor to the next qualified place;
? Search Note: For reverse search, press SHIFT + n to move the cursor to the next qualified
11. Replacement
Press ESC to enter the command mode;
: S/search/replace/G note: Replace the search words in the row where the current cursor is located with replace and highlight all the search words;
: % S/search/replace Note: replace all search files with replace;
: #,# S/search/replace/G note: # represents a number, indicates the number of rows to the number, and replaces search with replace;
Note: In the command, G indicates global search. In addition to the specified replacement range, search is highlighted.

(2) Use of GCC and make
For C language programs edited in Linux, you need to use the GCC compilation tool (which can be called through the CC alias in Linux) to compile the connection and generate executable files. For complex applications, multiple source programs may be compiled separately and finally connected to form an execution file. to effectively manage such projects, the make code maintenance tool can be used to define a series of rules to manage the compilation connection process.
[Note] in Linux, the executable files do not have special extensions, but are differentiated by setting the "executable" attribute. In addition, in Linux, the default search path for execution files does not include the current directory. Therefore, the compiled execution file must display the specified file path for execution.
1. Use of GCC
(1) Easy to use
Assume that a C language source program named demo. C is used to generate an execution File Based on the file. The simplest command is:
GCC hello. c
This command generates an execution file named A. Out by default. If you want to generate an execution file with different names, you can specify the following parameters in the command:
Gcc-O hello. c
This command generates an execution file named demo.
(2) decomposition and use
In fact, the work done by GCC includes multiple links, including pre-compilation, compilation, and connection. The above simple usage implies calls to these links. If you need to call them separately, you can specify different command line parameters:
The GCC-e hello. C-O hello. I-e parameter is specified for pre-compilation, and the pre-processing macro definition is inserted into Hello. I;
The GCC-C hello. I-O hello. O-C parameter specifies that the compilation is the target code hello. O, which can also be directly generated through the source file (GCC-C hello. C );
GCC hello. o-O hello will generate an executable file. If multiple source program files are generated, multiple target code modules need to be specified during production, for example: GCC hello. O e1.o s2.o-O hello
(3) Common Parameters
Common GCC command line parameters are as follows:
-C: Notify GCC to cancel the link, that is, compile the source code and generate the target file at the end;
-Dmacro defines the specified macro so that it can be verified by # ifdef in the source code;
-E is delivered to the standard output without compiling the output of the Preprocessing Program;
-G3 gets detailed information about the debugging program, which cannot be used together with the-O option;
-Idirectory: add the specified directory at the start point of the file search path;
-The llibrary prompts that the linked program contains the specified library when creating the final executable file;
-O,-O2, and-O3 enable the optimization status. This option cannot be used together with the-G option;
-S requires the Compilation Program to generate the assembler output from the source code;
-V starts all alarms;
-Wall cancels the compilation operation when an alert is generated, which indicates that the alert is regarded as an error;
-Werror: cancel the compilation operation when an alarm occurs, that is, the alarm is treated as an error;
-W: Disable all alarms.
2. Use of make
(1) make tool Introduction
Make is a code maintenance tool that automatically maintains and generates targets in large and medium-sized projects based on updates to various modules of the program. We can achieve "Not much, no weight, no leakage ":
• Not many: Only update the files to be updated, but not those that are not outdated;
• No duplicates: When make updates a file, it will only be updated once even if many files are out of date;
• No leakage: it means that it will not leak any files that should be updated.
Make has a series of rules. It will explain the configuration script based on these rules to achieve the design purpose. The default name of the configuration script is makefile or makefile. You can also specify other file names in the command line. Usage:
Make [Option] [macrodef] [target]
Option indicates the action of make. For details about the parameters, refer to the man manual page.
(2) Write makefile
The key to using the make tool is to compile an efficient, concise, and correct makefile, which requires learning and practice. Although the use of make tools has a high threshold, once mastered, it brings much more flexibility and convenience than the management functions provided by general ide.
The actual MAKEFILE file compilation involves a lot of knowledge and has the most specific topic. Here is just an overview. A simple example is used to describe that a project "hello" depends on "hello. o, e1.o, e2.o, and hello. O depends on hello. c. Hello. h, e1.o depends on e1.c, hello. h, e2.o depends on e2.c; in this way, a dependency tree is formed, and the parent node is dependent on the child node. When you use make for maintenance, the tree will be traversed once. If you find that the time when the child node is formed is later than the time when the parent node is formed, you will start to call the specified command in makefile for maintenance. The makefile example for this example is as follows:
Hello: Hello. O e1.o e2.o
Gcc-O hello. O e1.o e2.o
Main. O: Hello. c hello. h
Gcc-C hello. c
E1.o: e1.c hello. h
Gcc-C e1.c hello. h
E2.o: e2.c
Gcc-C e2.c
Makefile is placed in the same directory as the project source program file. Execute the make hello or make command in this directory (the first target of makefile is used by default when the command line does not have a target ), according to the dependencies defined in makefile, commands are compiled and connected sequentially to generate the hello execution file.
Makefile of the actual project uses a large number of macros, conditional variables, and default rules, which is hard for beginners to understand. For general open-source projects, when compiling makefile, the naming of target follows some predefined rules. Common usage includes:
Make all compile all the actual targets in the project
Make install
Make clean clear all intermediate files
(3) default rules and simple usage
The default make rule is a system or custom rule. The full name is not specified during the definition, but a type of dependency and related commands are defined according to the file extension. For example, the C language-related default rules include:
. C:
$ (CC) $ (flags)-o $ @ $
# Include
# Include

Int main (void)
{
Int X, I;

Printf ("input a initial value for I :");
Scanf ("% d", & I );
While (x = fork () =-1 );
If (x = 0)/* child run */
{
Printf ("when child runs, I = % d/N", I );
Printf ("input a value in Child :");
Scanf ("% d", & I );
Printf ("I = % d/N", I );
}
Else/* parent run */
{
Wait ();
Printf ("after child runs, in parent, I = % d/N", I );
}
}
(2) execution results of the prediction program
Read the program and, based on your understanding, expect the results after the program is executed.
(3) actual execution Result Analysis
Compile and generate the execution file, and record the results after execution, indicating whether the results are consistent with the expected results. Analyze why this is the result.

2. Analysis of parent-child Process Execution Process
(1) Programming Based on the given framework
Compile the source program according to the following program framework:
// ①
PID = fork ();
// ②
If (pid = 0)
{
Sleep (3 );
Printf ("Child: pid = % d, ppid = % d/N", getpid (), getppid ());
}
Else
{
Printf ("parent: child = % d, pid = % d, ppid = % d/N", PID, getpid (), getppid ());
Wait ();
Printf ("after child ends./N ");
}
Printf ("in which process? /N "); // ③
(2) execution results of the prediction program
Read the program and, based on your understanding, expect the results after the program is executed.
(3) actual execution Result Analysis
Compile and generate the execution file, and record the results after execution, indicating whether the results are consistent with the expected results. Analyze why this is the result.
(4) modify the program and analyze the execution result
Move the output Statement (position 3) at the last sentence in the program framework to positions ① and ② respectively. What is the expected output result? What are the actual execution results? Analyze the cause.
(5) modify the program to verify the parent-child process relationship
Modify the program so that the parent process is executed first to verify that the child process will terminate together? If not, does the parent process number of the child process change? Record and analyze the results.

V. lab report writing requirements
The following items should be described in the lab report:
1. The text editor used;
2. Compile the command for generating the execution file;
3. The name and storage location of relevant programs, so as to instruct instructors to spot check;
4. Results of Experiment 1: including expected results, actual execution results, and result analysis;
5. Results of Experiment 2: including the expected results and actual execution results, analysis of the results; the expected results, actual results and analysis after modification as required.

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.