Improve chapter: Linux (with answers) __linux

Source: Internet
Author: User
Tags chmod epoll message queue semaphore sleep disk usage file permissions
four, Linux basic commands 1. The absolute path is expressed by what symbol. What is represented by the current directory, the top-level directory. What do you mean by the home directory? What commands to switch directories with.

Absolute path: such as/etc/init.d

Current directory and upper level directory:./.. /

Home directory: ~/

Switch Directories: CD 2. How to view the current process. How to perform an exit. How to view the current path.

View Current Process: PS

Execution exit: Exit

View current path: PWD 3. How to clear the screen. How to exit the current command. How to perform sleep. How to view the current user ID. View what commands are specified for help.

Clean screen: Clear

Exit current command: CTRL + C complete exit

Perform sleep: ctrl+z suspend current process FG restore background

View Current User id: "id": view displays the UID and GID and the group and username of the current login account

To view the specified help: such as man adduser this is full and there are examples; Adduser--help this tells you some common parameters; INFOADDUESR 4. what function Ls command performs. What parameters can be taken, and what is the difference.

LS performs the function: Lists the directory in the specified directory, and the file

Which parameters and differences: A All file L details, including size byte number, readable writable executable permissions, etc. 5. Establish soft links (shortcuts), and hard links to commands.

Soft Link: ln-s slinksource

Hard Link: lnlinksource 6. What is the command for directory creation. What commands are used to create a file. What commands are used to copy files.

Create a table of contents: mkdir

Create a file: A typical touch,vi can also create a file, in fact, as long as the output to a non-existent file, will create a file

Copy file: CP 7. What command is used to modify file permissions. What the format is like.

File Permission modification: chmod

The format is as follows:

$chmodu +x file to add execution permissions to the owner of the file

$chmod 751file assigns read, Write, execute (7) permissions to the owner of the file, assigns read, executes (5) permissions to the group where the file is assigned, and assigns permissions to other users for execution (1)

$chmodu another form of the =rwx,g=rx,o=xfile example

$chmod =rfile Assign Read permissions to all users

$chmod 444file in the previous example

$chmoda-wx,a+rfile:

$chmod-ru+rdirectory recursively assigns read permissions to the owner of all files and subdirectories under the directory directory 8. See what commands are available for the contents of the file.

VI FileName # Edit way view, can be modified

Cat FileName # Displays all file contents

More file name # Pagination display file contents

Less file name # Similar to more, better to be able to page forward

Tail filename # View only the tail, and you can specify the number of rows

Head FileName # View only the header, and you can specify the number of rows 9. Write a file command at random. How do I output a string with a space to the screen, such as "Hello World"?

Write file command: VI output a string with a space to the screen: echo Hello World 10. The terminal is which file under which folder. The black hole file is which command under which folder.

Terminal:/dev/tty black hole File:/dev/null 11. Which command to move the file to. which command to rename.

MV MV 12. Which command is used to copy files. If you want to copy it together with the folder. How to need to have a hint function.

CP cp-r .... 13. Which command is used to delete the file. If you need a directory and directory to delete the file piece. What commands to delete an empty folder.

What kinds of wildcard characters are available in the RM rm-r rmdir 14.Linux command. What do you mean, separately?

“。 "To replace a single character.

"*" can replace any number of characters.

The square brackets "[charset]" replaces any single character in the CharSet set, such as [A-Z],[ABABC] 15. What command is used to count the contents of a file. (line number, number of words, number of bytes)

WC command-C counts the number of bytes. -L counts the number of rows. -W counts the number of words. What is the use of the grep command. How to ignore case. How do I find rows that do not contain the string?

is a powerful text search tool that uses regular expressions to search for text and print matching rows. Grep [string string] filename

Grep[^string]filename 17.Linux The status of a process. In the information displayed in PS, the symbols are expressed separately.

(1), non-disruptive state: The process is in a sleep state, but the process is not interrupted at the moment. Non-disruptive, the process does not respond to asynchronous signals.

(2), suspend state/tracking status: Send a sigstop signal to the process, it will be due to the signal to enter the task_stopped state; When the process is being tracked, it is in task_traced this

A special state. "Being tracked" means that the process pauses and waits for the process that tracks it to operate on it.

(3), ready state: The state in the Run_queue queue

(4) State of Operation: the state in the Run_queue queue

(5), interruptible sleep state: The process in this state is suspended because it waits for the occurrence of a certain event (such as waiting for a socket connection, waiting for a semaphore)

(6), Zombie State (zombie): Father did not pass the wait series of system calls will be in the process of the Corpse (Task_struct) also released

(7), exit status 18. How do I make a command run in the background?

Generally use & at the end of the command to allow the program to run automatically. (You can not append a space after the command) 19. How do i show all the processes using PS? How to use PS to view information about a specified process.

Ps-ef (SYSTEMV Output)

PS-AUXBSD format output

Ps-ef|grep PID 20. Which command is used specifically to view background tasks?

Jobs-l 21. Transfer background tasks to the front desk. What commands do you use to perform the task behind the scenes in the background?

Transfer the background tasks to the front office. FG

Carry out the background task in the background BG 22. What is the command for terminating the process? What parameters?

Kill [s < information name or number >][program] or kill [-l < information number]

kill-9 PID 23. How to view all the signals supported by the system.

Kill-l 24. What is the command for the search file? What's the format like?

Find < Specify directory > < specify conditions > < specify action >

Whereis plus parameter and filename

Locate only add filename

Find the disk directly, slower.

Find/-name "string*"

25. See who is currently using the host with what command? Find the terminal information you're in. What command?

Find your terminal information: Who am I

View who is currently using this host: Who 26. What commands do you use to view a list of used commands?

History 27. Use what command to view disk usage space. What about free space?

Df-hl 28. What commands do you use to see if the network is connected?

Netstat 29. Use what command to view IP address and interface information.

Ifconfig 30. View all kinds of environment variables what command?

Env 31. What command do you use to specify a command prompt?

\u Display Current user account

\h Displays the current host name

\w only displays the last directory of the current path

\w Displays the current absolute path (the current user directory is replaced with ~)

$PWD Display current full path

\$ Show command line ' $ ' or ' # ' symbol

\#: The first few orders issued

\d: Represents a date, formatted as Week day month date, for example: "MonAug1"

\ t: Displays a time of 24-hour format, such as: HH:MM:SS

\ t: Display time in 12-hour format

\a: Display time is 24 hour format: hh:mm

Version information for \v:bash

such as export ps1= ' [\u@\h\w\#]\$ ' 32. Where do you find the executable file for the command? How do I set it up and add it?

whereis[-bfmsu][-b< Directory ...] [-m< Directory ...] [-s< Directory ...] [File ...]

Supplemental Note: The WHEREIS directive looks for eligible files in a specific directory. The spirits of these files should be in the original code, binary file, or help file.

-B finds only binary files.

-b< directory > Find binaries only in the set directory.

-F does not display the path name before the file name.

-M to find only the description file.

-m< directory > Find the description file only in the set directory.

-S finds only the original code file.

-s< Directory > Locate the original code file only under the set directory.

-U finds files that do not contain the specified type.

The which directive searches for the location of a system command in the path specified by the path variable and returns the first search result.

-n Specifies the filename length, which must be greater than or equal to the longest text in all files

Part name.

-P is the same as the-n parameter, but the path to the file is included here.

-W Specifies the width of the field when output.

-V Display version information 33. What commands do you use to find an execution command?

which can only search executable files

Whereis can only search binary files, documentation, source files, etc. 34. How to alias a command.

Alias la= ' Ls-a ' v. Linux programming 1. Enumerate several functions related to Linux memory management.

0.11 kernel provided memory management functions most of them are in memery.c, and I divide the functions into three categories: memory allocation and release, page exception handling, and memory initialization. The first category mainly includes the operation of a single physical page and the operation of a page table, and the operation of a single physical page is the application, mapping, and release of a physical page; Page table operations are primarily the release and replication of multiple page tables. The second type is mainly dealing with the interrupt processing function of the fault page anomaly and write protection exception. The third category is a function that is responsible for the initialization of the memory.

I. Allocation and release of memory

1, Get_free_page (): Request a free physical page in the main memory area.

First scan mem_map[], looking forward from the end of the value of 0 elements, find its value into 1, and according to the index of this element in mem_map[] is worth to the address of the physical page, and then the physical page of the 4K byte clear Zero, and finally return the physical address.

2, Free_page (): Releases the physical page at the specified physical address.

After verifying the validity of this address, it translates the corresponding page address according to it: (addr-1m)/4k, and then uses this address value as the index to find the corresponding item in mem_map[], clearing it.

3, Free_page_tables (): Releases a number of page tables starting at the specified linear address and its corresponding physical page.

First, determine if the incoming linear address is valid, that is, on the 4MB boundary, then, even if it takes up the number of page directory entries and the address of the first directory entry, then starting with the first directory entry, the address of the page table is based on the directory entry for the available directory entry (i.e. P=1: there is a corresponding page table). This frees up all the recorded physical pages (free_page) in the page table and zeroes the page table entry, then releases the physical page of the page table itself and zeros out its corresponding page catalog entry. Until the last page directory entry is processed. Finally, the TLB is refreshed.

4, Copy_page_tables (): Copy the specified linear address to start a number of page tables to the specified destination linear address.

This function is used when fork a process, which lets the child process share the physical memory of the parent process. After verifying the boundary of the address, the starting address of the source directory entry and the starting address of the destination directory entry and the number of page directory entries to be copied are converted into the page Catalog Entry table. Then start the copy work: first apply for a page of memory to store the new page table, it then sets the corresponding page catalog entry, then loops through the page table entries in the source page table to the new page table (only the first 160 items are copied for the kernel process, because the kernel module is no more than 640K), and the individual page table entries are set to read-only. Finally, the value of the element corresponding to the page in mem_map[] is added by 1 (representing the reference count plus 1) based on the physical address of each page. It then loops through the replication work until all the page tables have been copied.

5, Put_page (): Map a physical page to the specified linear address space.

That is, the corresponding page table entry is found according to the linear address, and the value in the page table entry is set to the physical address of the physical page. This function is typically used after get_free_page (). After verifying the validity of the address, first the address of the page directory entry is converted according to the high 10 bits of the linear address, the page table address is obtained from the page catalog entry, and the page table entry address is obtained according to the middle 10 digits of the linear address. Finally, you set the physical page address and some page information that it maps to in this page table entry.

6, Get_empty_page (): The combination of get_free_page () and Put_page ().
2. What are the options that GCC compiles only. What are the options for preprocessing only. What are the options for defining macros on the command line?

Gcc-c hello.c-o hello.o gcc-e hello.c-o hello.i 3. The use of Linux static libraries, how to create a static library. How to use a static library. What is the suffix name of the static library file. The naming specification for static libraries.

Create a static library: #gcc-c hello.c-o hello.o # ar cr libmyhello.a

hello.o

Using static libraries: Gcc-ohello main.c-l.-lmyhello

(Note that GCC prefix the static library name with Lib and append the extension. A to the static library

File name to find the static library file. )

Suffix is:. A

Naming specification: prefix "Lib", library name and suffix 3, where the dynamic link library with. So

Most suffixes, a static link library usually has a suffix of. A.

Difference: Static library code is copied at compile time in the application, the advantage is to save the

Translation time.

Dynamic link libraries are loaded when the program calls the library function after it starts running. 4. The role of NM tool, LDD tool.

Nm

#nm Test

08049F10 D _dynamic

08049ff4 D _global_offset_table_

080486F0 T _global__i_main

First column: The address of the current symbol

Second column: The type of the current symbol

Third column: The name of the current symbol

The role of NM:

(1) To determine whether the specified program has defined the specified symbol (the more common way: nm-c test

| grep symbol)

Add-C to make the second column easy to read, such as T _global__i_main----"" Main

(2) Undefinedreference error at compile-time of the resolver, and mutiple

Definition of the error

(3) View the address of a symbol and the approximate location of the process space (BSS, data, text

area, which can be judged by the type of the second column.

LDd

#ldd Test

Linux-gate.so.1 => (0xffffe000)

Libz.so.1 =>/lib/libz.so.1 (0xb7f8c000)

libpthread.so.0 =>/lib/libpthread.so.0 (0xb7f75000)

First column: What library does the program need to rely on

Second column: The library that the system provides for the libraries that the program needs

The third column: The starting address of the Kuga load

The role of LDD:

(1) By comparing the first column and the second column, we can analyze the library and system reality that the program needs to rely on

provided, whether or not to match

(2) By observing the third column, we can know the symbols in the current library in the corresponding process

Start position in the address space

5. The use of Linux dynamic Library, how to create a dynamic library. What is the suffix name of the dynamic library file. How to use a dynamic library. The naming specification for dynamic libraries. The lookup path of the default dynamic library for the system. The dynamic library shows what system libraries are used by the connection. The naming specification for dynamic libraries. The lookup path of the default dynamic library for the system. The dynamic library shows what system libraries are used by the connection.

Create a dynamic library: Gcc-chello.c-o hello.o gcc-shared-fpci-o

Libmyhello.so hello.o

The suffix name of the dynamic library:. So

Using dynamic libraries: Gcc-ohello main.c-l.-lmyhello

Dynamic Library naming specification: prefix "Lib", library name and Suffix 3 part, where the dynamic link library

With. So most suffixes, the static link library usually has a. a suffix.

Default lookup path:/usr/lib/lib (default path for static library is current directory)

Dynamic libraries show the system libraries used by the connection: ..... 6. Linux under Make and makefile. What parameters are used to specify the makefile file. What is the default makefile file.

I can't find the right answer . 7. In which folder there is all the information that the process is running.

/proc Under this folder, there are various PID-named folders, each containing information on each process 8. Which three file devices are opened by default for each program.

STDIN STDOUT STDERR 9. What is the read-write function of the operation file descriptor. Opens a file descriptor and a function that closes the file descriptor.

The Write read open close 10.Fcntl function has several main functions.

int fcntl (int fields, Intcmd,.../* int arg * *);

1. Copy an existing descriptor (cmd = F_DUPFD).

2. Get/Set File descriptor tags (cmd = f_getfd | | F_SETFD).

3. Get/Set File status tag (cmd = F_GETFL | | F_SETFL).

4. Get/Set asynchronous I/o ownership (cmd = F_getown | | F_setown).

5. Get/Set record lock (cmd = f_getlk, F_SETLK | | F_SETLKW). 11. Create several functions of the process, and their respective differences.

The difference between fork and clones:

When the fork () function replicates, the resource of the parent process is duplicated by replicating the data structure

System, and then pass it on to the child process,

So the fork () function takes no parameters;

The Clone () function replicates the data structure of the resources of a part of the parent process, copying which funds

The source is selectable this can be set by parameter, so the Clone () function takes parameters, no replicated funds

The source can be shared by the pointer to the child process;

int clone (int (*FN) (void *), void *child_stack, int flags, VOID*ARG)

FN is the function pointer, which points to a function body, the static program that wants to create the process;

Child_stack is the pointer to the system stack assigned to the child process, and ARG is the parameter passed to the subprocess;

Flags are flags for the resources to be replicated:

The difference between fork () and Vfork ():

1. Fork: Child processes Copy the data segments of the parent process, code Snippets

Vfork: Child processes share data segments with parent process

2. Fork: The execution order of the parent-child process is indeterminate

Vfork ensures that the subprocess runs first and is shared with the parent process data before calling exec or exit

, the parent process may not be scheduled to run until it calls exec or exit. If you are calling these two

A deadlock is caused by a child process that relies on further actions of the parent process before the function. 12. The parent process ends and the child process becomes. The subprocess ends and the child process becomes.

Orphan process Zombie Process 13. How to make a parent process recycle a child process. Related to several functions.

Temporarily stop the execution of the current process until a signal arrives or the child process ends. Status in

The End state (exit (3)) of the child process is stored.

pid_t waitpid (pid_t pid, int *statloc, int options); If successful

Returns the process id,0 (using the Wnohang option), if error returns-1.

Pid:

From the parameter's name PID and type pid_t, you can see that here's what's needed is a

The process ID. But when the PID takes a different value, there are different meanings here.

Pid>0, wait for the process ID equal to the PID child process, no matter how many other children

The process runs at the end of the exit, and as long as the specified subprocess is not finished, Waitpid will wait.

When Pid=-1, wait for any child process to exit without any restrictions, at this time waitpid

And wait are exactly the same.

When pid=0, wait for any child processes in the same process group, if the child process is already joined

The other process group, Waitpid will not take any heed of it.

When pid<-1, wait for any child processes in the specified process group, the ID of the process group

equals the absolute value of the PID.

Options:

Options provide some additional options to control Waitpid, which is currently only

Supports the Wnohang and wuntraced two options, which are two constants,

You can use the "|" Operators to connect them to use, such as:

Ret=waitpid ( -1,null,wnohang | wuntraced);

return value:

When normal returns, WAITPID returns the process ID of the child process that was collected;

The option Wnohang was set, and Waitpid found no child processes exited in the call

Can be collected, returns 0, or 1 if an error occurs in the call, at which point errno is

Set to the appropriate value to indicate where the error occurs, or if the child process indicated by the PID does not exist, or

This process exists, but is not a subprocess of the calling process, and Waitpid returns with an error, which

When the errno is set to Echild;

14. Replication of the memory resources of the parent process at the time of the creation of the child process.

Fork for parent-child sharing:

Open files

Actual user ID, actual group ID, valid user ID, valid group ID

Add Group ID

Process Group ID

Dialog Period ID

Control terminal.

Settings-user-id flags and Settings-group-id flags

Current working directory

root directory

File way to create a masked word

Signal shielding and arranging

Close flag on execution of any open file descriptor

Environment

Connected shared storage segment (shared memory)

Resource constraints

Fork Parent-Child distinction:

return value of fork

Process ID

Different parent Process IDs

Tms_utime,tms_stime,tms_cutime of child processes and tms_ustime

Set to 0

Lock that is set by the parent process, and the child process does not inherit

Pending alerts for child processes are cleared

The pending signal set for the subprocess is set to empty 15. What is a macro that interrupts the signal, terminates the signal, and the timer signal.

SIGINT sigchld SIGALRM 16. What functions to register signals and send signals in a program?

sig_t signal (int signum,sig_t handler); Error return

Sig_err

int sigaction (int signum,const struct sigaction *act, struct

Sigaction *oldact);

int Kill (pid_t pid, int sig);

unsigned int alarm (unsigned int seconds);

int raise (int sig); Signal to itself 17. The meaning of the signal is reliable and unreliable. Which signals are reliable. Which signals are unreliable.

Unreliable signals, expressed in the signal does not support queuing, signal may be lost, such as sending

Multiple times the same signal, the process can only be received once.

Reliable signal, performance in the signal support line, not lost, how many times, you can receive

to how many times.

Signal values in [Sigrtmin,sigrtmax] intervals are reliable signals.

Signal values less than sigrtmin are unreliable signals. 18. What function does the signal shield use? The role of Sigsuspend. The role of sigpending.

int sigprocmask (int how, const sigset_t *restrict set, sigset_t

*restrict oldset);

Sigsuspend: Temporarily replaces a process's signal mask with mask before receiving a signal

Code, and pauses the process execution until the signal is received.

Refer to Sigsuspend. doc

Sigpending:sigpending () returns the set of signals being shelved by the parameter set pointer.

Returns 0 if the return value is successful, or 1 if there is an error.

See Linux reliable and unreliable signals 19. Signal processing functions when processing signals will be interrupted by the signal.

When the signal processing function of a signal executes, if the process receives the signal again, the letter

The number is automatically stored without interrupting the execution of the signal processing function until the signal processing function is completed and the corresponding handler function is called again. But if the process receives other types of signals when the signal processing function executes, the execution of the function is interrupted 20. The latest version of the signal sending and processing functions. With the old version of the Send and data function is what difference. 21.Linux What mode of communication (IPC) the process has.

Signal, pipeline, message queue, shared memory, semaphore, socket, 22. The TCP server programming model.



UDP Server programming model

TCP programming characteristics, because each indefinite length of data arrives, what is the general use of options. don't find the right answer, welcome to add 25.Selected model is what. What is the difference between a multi-process implementation approach. The difference between Selected, Epoll model and poll model.

The essence of select is to use 32 bits of 32 integers, that is, the 32*32= 1024来 identity, and the FD value is 1-1024. When the value of FD exceeds the 1024 limit, the size of the fd_setsize must be modified. This time you can identify the 32*max value range of FD.

For single process multithreading, a select is not appropriate for each thread to handle multiple FD cases.

1. All threads are scanned from the 1-32*max, each thread processing is a section of FD value, this is a bit wasteful

2.1024 Upper limit problem, a process to handle multiple users, the FD value is much greater than 1024

So this time we should adopt poll,

Poll passing is the array header pointer and the length of the array, as long as the length of the array is not very long, performance is very good, because poll once in the kernel request 4K (a page size to store FD), as far as possible control within 4K

Epoll is an optimization of poll, which does not need to traverse all FD after returning, and maintains a list of FD in the kernel. Select and poll are the kernel list maintained in user state and then passed to the kernel. But only in 2.6 of the kernel support.

Epoll more suitable for handling a large number of FD, and active FD is not a lot of cases, after all, FD more or a serial of the exercise

26. What are the common socket options? which function to use to set the socket option.

#include <sys/types.h>

#include <sys/socket.h>

intgetsockopt (int sock, int level, int optname, void *optval,

Socklen_t*optlen);

intsetsockopt (int sock, int level, int optname, const void

*optval,socklen_t Optlen);

Parameters:

Sock: The socket that will be set or get the option.

Level: The protocol layer at which the option resides.

Optname: The option name that needs to be accessed.

Optval: For GetSockOpt (), point to a buffer that returns the value of the option. For

SetSockOpt (), pointing to a buffer containing the new option value.

Optlen: For GetSockOpt (), the maximum length of the option value as the entry parameter. For

The actual length of the option value for the export parameter. For setsockopt (), the length of the current option.

Return Description:

When successfully executed, returns 0. Failure returns -1,errno is set to one of the following values

Ebadf:sock is not a valid file descriptive word

Efault:optval point to memory is not a valid process space

Einval: Optlen is not valid when setsockopt () is invoked

ENOPROTOOPT: The specified protocol layer does not recognize the option

Enotsock:sock is not describing a socket

Parameters Detailed Description:

level specifies the hierarchy of the control sockets. You can take three values:

1) Sol_socket: Universal socket option.

2) ipproto_ip:ip option.

3) ipproto_tcp:tcp option.

Optname Specify the mode of control (the name of the option), we explain in detail below

Optval Gets or sets the socket option. Converts the data type of the option name to 27. How to send and set up Out-of-band (OOB) data. no suitable answer was found
28.Linux What is a multithreaded library. which function to use to create the thread. Use which function to force the end thread. function to be used when the main thread waits for the child thread to end?

End Thread. function to be used when the main thread waits for the child thread to end?

The most common use of Linux is the Pthread line threading, which follows the POSIX standard. The realization of Pthread is

Implemented through system call Clone (), a Linux-specific system call.

extern int pthread_create __p (pthread_t *__thread, __const

pthread_attr_t *__attr,void * (*__start_routine) (void *), void*__arg));

extern void Pthread_exit __p ((void *__retval)) __attribute__

((__noreturn__));

extern int Pthread_join __p (pthread_t __th, void

**__thread_return)); 29. How the thread can do some remedial work when forced to quit. And how to handle it in a Linux-specific way.

The default state of a thread is joinable, if the thread is joinable state, when the thread

function does not release the stack and thread descriptions used by the thread when it returns exit or Pthread_exit

Character (total 8K). These resources will be freed only after you have invoked the Pthread_join.

If the thread of the unjoinable state, these resources are either exited by the thread function or

Pthread_exit will be released automatically.

The Unjoinable property can be specified at pthread_create time, or after the thread is created

Thread Pthread_detach itself, such as: Pthread_detach (Pthread_self ()), will state

Change to unjoinable state to ensure the release of resources. If the thread state is joinable, it needs to be

After the timely call Pthread_join.

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.