APUE chapter I basic knowledge of Unix

Source: Internet
Author: User

Pre-language: I am halfway decent do programmers, in fact, to deal with the usual work of business can also, but the basic knowledge is weak, of course, also with the Chinese computer education has a relationship, usually chat with colleagues, in fact, even if it is trained, for the computer itself know very little, so when the graduation two anniversary, To determine the future of the technical learning direction, but also decided to add the basic part, special to CSDN Open this topic, to learn the programmer Bible-like book-"UNIX Advanced Environment Programming", which is often mentioned by a colleague, books thicker, but not too hasty, But also do not expect to be able to learn through a one-time learning, nothing back to see, there is always a harvest, encourage each other.


I. UNIX architecture

Operating system is to run on top of the program to provide services, from the strict meaning of the operating system can be regarded as a software, it is responsible for controlling the computer hardware resources, the provider run environment, from this point of view, in fact, it is relatively easy to understand the concept of operating system, for example, you want to read a file, It is necessary to read the disk this hardware resources to complete, although we usually write code may only need to perform the next open or read function can complete the file read, but the real situation is not so simple, simple understanding can think that when we execute the aforementioned function, actually is to launch a task to the operating system , the statement may not be rigorous enough, but it is easier to understand when the task returns the result after the task has been completed. At this time the concept of the kernel comes out, and the kernel and the external program intermediary is the system call , when we learn to write C language code, there will be a lot of packaged library functions, these common function libraries are mainly built in the system call the first, The application can call the Public function library or call the system call directly, in the UNIX system, there is a special application called Shell program, this program is user interface with the system, through the shell we can execute other applications, these parts of the architecture diagram are as follows:




Ii. Documents

This chapter before the book also mentions the login and the shell, these two parts I do not speak here, the main reason is that the user this piece of the biggest impact is actually the authority problem, the other chapters in the book will be related to this piece, speak more than here, so skip. This part of the file is important to Unix, and perhaps many people know that one of the tenets of UNIX is that everything is file, that is, whether it is device interaction, file read, network connection can be regarded as or abstract as a file treatment, this piece in later learning by understanding the API can know, Too many UNIX interfaces are very similar and alike, and the reason is here.

This part of the book tells a few concepts, that is, the concept of understanding, first of all, there will be a special section of the chapter to specifically explain. Unix's file system is a hierarchical structure where the starting point is the "/" root directory. There may be a concept here that is not a good idea, that is, UNIX file system contains directories and files, but in Unix, the directory is actually a file containing directory entries, corresponding to all of the above files. Logically, each directory entry is a struct that contains a file name and also contains information about the properties of the document. The file attribute contains a collection of attributes for this file, one of which indicates the file type, indicating whether the file is a directory or an ordinary file.

Each name in the directory becomes a file name, and only the slash and null characters cannot appear in the file name, because the slash is used to separate the path, and the null character is used to terminate a path name, and when a new directory is created, two file names are created in that directory, respectively. and ".", respectively, to indicate to the current directory and parent directory, of course, at the highest level of the root directory, they both point to the current directory. One or more of the filenames separated by a slash is the path name, which begins with "/" and is called the absolute path name, otherwise it is the relative pathname. For example, "/usr/local/bin", in which the Usr,local,bin is actually the file name, although they are in the actual system is a folder (directory), but in this system, is the file name. The "/usr/local" is the path name, and the absolute path, as for "Local/bin" is relative to the/usr/relative path name. The book provides a simple version of the LS command code, to understand the directory level, you can see the output, I have the original header file to remove the book, so no matter who want to just look at this code effect, do not need to go to the book with the source download, the code is as follows:

#include <stdlib.h> #include <stdio.h> #include <dirent.h>int main (int argc, char* argv[]) {    DIR     *DP;    struct dirent *dirp;    if (argc! = 2) {        printf ("Usage:ls directory_name");        return 0;    }    if (DP = Opendir (argv[1)) = = NULL) {        printf ("Can ' t open%s", argv[1]);        return 0;    }    while ((DIRP = Readdir (DP)) = NULL) {        printf ("%s\n", dirp->d_name);    }    Closedir (DP);    Exit (0);}
When we log into the system, it will actually go to the user's own default directory, this is called the starting directory, this part in the password file can be seen, and when we run the program will have a working directory, which is why when we put a file in the path of the execution file can be read, Of course we can also modify our working directory in the program, this section will be highlighted when we introduce the process later.

Iii. Input and output

Input and output of the computer system is too important, but also the most direct and basic functions, the use of a wide range of UNIX systems, especially, whether it is the pipeline, terminal, or file, socket, are inseparable from the category of input and output. This part also has several important concepts need to understand, this is very important for further in-depth study, the first is the file descriptor, which is used by the kernel to identify a particular process is accessing the file, note, here is very clear, is that the file descriptor is process-related, different processes operate the same file, The file descriptor is not necessarily the same, when the kernel opens an existing or create a new file, it will return a file descriptor, and all the other actions are for this file descriptor.

But there are exceptions, for all programs, when running the program, the shell will open 3 file descriptors for this program (0,1,2), the standard input, standard output and standard error, if not done, these three descriptors are linked to the terminal, of course, if you want to, can completely through "<" or ">" redirects the three to a file, such as ls > 1.txt, and outputs the result of LS to a 1.txt file.

Finish the file, then say is the operation of the file, in fact, basically are read and write operations, I/O operations are divided into non-buffered IO and buffered Io, these two parts will have a specific chapter after the detailed narration, the following code just let you understand the process of IO operation:

#include <stdlib.h> #include <stdio.h> #include <unistd.h> #define Buffsize 4096int Main (void) {    int     N;    Char    buf[buffsize];    while ((n = Read (Stdin_fileno, buf, buffsize)) > 0) {        if (write (Stdout_fileno, buf, n)! = N) {            printf ("Write ER Ror!\n ");        }    }    if (n < 0) {        printf ("Read error!\n");    }    Exit (0);}

Iv. Procedures and processes

This is probably the most familiar part of us, is also the most common thing we do, write a code, run a bit. Write the code is the program, the program is actually an executable file, stored in the disk somewhere, when we want to run, through the kernel to read the file into memory, and then follow the instructions in the file execution, an instance of execution is called the process, That is, if you execute two of the same program at the same time, there are two processes, each process will have a unique encoding, called the process ID, the program can get its own current process ID through the GETPID function. Just mentioned, the kernel will read the program files into memory, and then execute, in fact, this process is the EXEC function execution process, exec is a Process control function, the process control function is not many, mainly 3, is used to execute the program exec function, Create the fork function of the process and the Waitpid function, which is followed by several chapters to highlight.

#include <stdlib.h> #include <stdio.h> #include <unistd.h>int main (void) {    printf ("Hello World From process ID%ld\n ", (long) getpid ());    Exit (0);}

The next thing to say about the thread, usually, a process has only one control thread, but if there is a time to have more than one control thread to do other things, then the ability to solve the problem is much better, in fact, the concept of threading is not the beginning, so the threading model implementation and the process model is very similar in many cases , this later chapter introduces the thread, and also mentions that even the function that controls the thread is similar to the function that controls the process. All threads in a process share the same address space, file descriptors, stacks, and process-related properties, which provides the possibility for multiple tasks to handle the same event, as well as some implementation difficulties, that is, how multiple threads can access shared data while maintaining data consistency, This is also the root cause of the lock that the programmer headaches.

Wu, error handling

When you call the Linux library functions are familiar, especially the read function, if the error will return a negative value to inform the user of the error, while the integer variable errno will be set to the value of a specific message, the value can not only know the current error type, but also to get the description of the current error, This piece only need to pay attention, that is the implementation of errno in multi-threaded program, this part can be searched for relevant technical posts to understand, that is, how the system ensures that the same process when two threads at the same time error is guaranteed to output the corresponding error.

#include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h>int main (int argc, Char *argv[]) {    fprintf (stderr, "eacces:%s\n", Strerror (eacces));    errno = ENOENT;    Perror (Argv[0]);    Exit (0);}

VI. Signal

The signal is used to notify the process that a situation has occurred. In this section, remember that the signal is actually the only way that the system is connected to the process . This is very important, in fact, in many open source software has been applied to this technology, such as if a service program configuration items modified, if very elegant update, restart is not suitable, timing acquisition, this time involves the interval problem, or how quickly effective, this time the signal can be done silently, So whenever you interact with the process, you can think about the signal.

The process has three signal processing methods:

1) ignore the signal.

2) default processing, such as Kill program.

3) Customize the signal capture function, which is also the implementation of the method previously mentioned to interact with the process. This section will also have a section dedicated to this.


The whole article actually simply introduced the UNIX system some basic concepts, these concepts actually constituted the system external function frame, the follow-up may also have the network communication and so on further display, because I also just began to study, many knowledge understanding is also relatively shallow, so the introduction is not clear and rigorous, I hope we all criticize and make progress together!

APUE chapter I basic knowledge of Unix

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.