Summary of questions on Linux C-plane

Source: Internet
Author: User
Tags goto integer numbers processing instruction volatile

1, the difference between process and thread, and comparison of pros and cons

The main difference between processes and threads is that they are different ways to manage operating system resources. The process has a separate address space, and after a process crashes, it does not affect other processes in protected mode, and the thread is just a different execution path in a process. Thread has its own stack and local variables, but there is no separate address space between the threads, a thread dead is equal to the entire process dead, so the multi-process program is more robust than multithreaded programs, but in the process of switching, the cost of large resources, efficiency is worse. But for some concurrent operations that require simultaneous and shared variables, only threads can be used, and processes cannot be used.

1) In short, a program has at least one process, and a process has at least one thread.
2) The thread partition scale is smaller than the process, which makes the multi-thread procedure high concurrency.
3) In addition, the process has a separate memory unit during execution, while multiple threads share memory, which greatly improves the efficiency of the program operation.
4) threads are still different from the process in the execution process. Each separate thread has a program run entry, sequence of sequence execution, and exit of the program. However, threads cannot be executed independently, and must be dependent on the application, which provides multiple threads of execution control.
5) from a logical point of view, the meaning of multithreading is that in an application, there are multiple execution parts that can be executed concurrently. However, the operating system does not consider multiple threads as separate applications to implement scheduling and management of processes and resource allocation. This is the important difference between processes and threads.
1.3 Advantages and Disadvantages:
Threads and processes have advantages and disadvantages in use: the overhead of thread execution is small but not conducive to the management and protection of resources, while the process is the opposite. At the same time, threads are suitable for running on SMP machines, while processes can be migrated across machines.


A thread is an execution unit within a process and a scheduler within a process.
Differences from the process:
(1) Dispatch: The thread acts as the basic unit of dispatch and allocation, and the process as the basic unit of resources
(2) Concurrency: Not only can concurrent execution between processes, but also concurrent execution between multiple threads of the same process
(3) Owning a resource: a process is an independent unit that owns resources, and threads do not own system resources, but they can access resources that belong to the process.
(4) Overhead: When you create or revoke a process, the cost of the system is significantly greater than the cost of creating or revoking a thread, because the system allocates and reclaims resources for it


2. Can local variables have duplicate names with global variables?

Answer: Yes, the local will block the overall. To use global variables, you need to use "::"


Local variables can have the same name as global variables, and when referenced within a function, local variables of the same name are used instead of global variables. For some compilers, multiple local variables with the same name can be defined within the same function, such as a local variable with the same name defined in the two loop body, and the scope of that local variable is within that loop body.


3. How do I reference a global variable that has already been defined?

Answer: extern


You can refer to the header file, you can also use the extern keyword, if you use a reference header file to refer to a global variable declared in the header file, assuming that you write the error, then the compilation will be an error, if you use the extern way to reference, assuming you made the same mistake, There will be no error during compilation and an error during connection.
4, global variables can be defined in multiple. C file included in the header file? Why?

A: Yes, you can declare a global variable of the same name in a different C file in static form.
1. What is the function of the keyword static?
Few people can answer this simple question completely. In the C language, the keyword static has three distinct effects:
1). In the function body, a variable declared as static maintains its value during the call of this function.
2). Within the module (but outside the function body), a variable declared as static can be accessed by the function used within the module, but not by other functions outside the module. It is a local global variable.
3). Within the module, a function declared as static can only be called by other functions within this module. That is, this function is restricted to the local scope of the module that declares it.
Most candidates are able to answer the first part correctly, and part of them can answer the second part correctly, with very few people able to understand the third part. This is a serious drawback for a candidate because he obviously does not know how to localize the number
and the benefits and importance of the code scope.


5. What is the difference between a "reference" and a pointer? A, 1) the reference must be initialized, and the pointer does not have to.
2) The reference initialization cannot be changed and the pointer can change the object being referred to.
3) There is no reference to a null value, but there is a pointer to a null value.
The pointer indirectly operates on the variable it points to after it points to an object through a pointer variable. The use of pointers in the program, the readability of the program, and the reference itself is the alias of the target variable, the operation of the reference is the operation of the target variable.
Reference is recommended for the stream operator << and >>, the return value of the assignment operator =, the parameter of the copy constructor, the parameter of the assignment operator =, and other cases
6. What is a balanced binary tree? A: The left and right sub-tree are balanced binary tree and the left and right sub-tree depth difference is not greater than 1 absolute value.


7. What causes the stack overflow? Answer: 1. No recycling of garbage resources
2. Recursive invocation with too deep hierarchy
8. What is precompilation and when does it need to be precompiled? A: Pre-compilation is also called Preprocessing, is to do some code text replacement work. The instructions to process the beginning of #, such as the copy # include file code, #define宏定义的替换, conditional compilation, etc., is the preparatory work for the compilation of the stage, mainly processing the # start of the pre-compilation instructions, pre-compilation instructions to the program before the formal compilation by the compiler to do the operation, Can be placed anywhere in the program.
C compilation system before the normal compilation of the program, the first preprocessing. The following three kinds of preprocessing functions are provided by C: 1) macro definition 2) file contains 3) conditional compilation

9. What is the meaning of the keyword volatile and give three different examples. A: A variable defined as volatile means that the variable may be unexpectedly changed so that the compiler does not assume the value of the variable. Precisely, the optimizer must carefully re-read the value of the variable each time it uses the variable, rather than using the backup stored in the register. Here are a few examples of volatile variables:
1). Hardware registers for parallel devices (e.g., status registers)
2). Non-automatic variables that are accessed in an interrupt service subroutine (non-automatic variables)
3). Variables shared by several tasks in multi-threaded applications
24. Three basic data models
A: The data model is divided into hierarchical model, mesh model, and relational model according to the different types of structure.


10, structure and union have and difference? Answer: (1). Structs and unions are made up of a number of different data type members, but at any one time, the union only holds a selected member (all members share a single address space), and all members of the struct exist (different member's storage address).
(2). For the different member assignments of the Union, the other members will be overridden, the original member value will not exist, and for the different members of the structure of the assignment is not affected
, write out bool,int,float, the pointer type of the variable A and the "0" comparison statement.
Answer: Bool:if (!a) or if (a)
Int:if (A = = 0)
Float:const EXPRESSION EXP = 0.000001
if (A < EXP && a >-exp)
Pointer:if (a = null) or if (a = = null)


11, how to determine whether a program is compiled by C compiler or C + + compiler program? Answer: #ifdef __cplusplus
cout<< "C + +";
#else
cout<< "C";
#endif
Two stacks to implement a queue function? Ask for the algorithm and ideas!
A, set 2 stack for A, a, a, initially empty.
Team:
Push the new element into stack A;
Out team:
(1) Determine whether stack b is empty;
(2) If not empty, then all elements in stack a pop out and push to stack B;
(3) Pop out the top element of stack B;

This achieves the team in the team and the team's split-level complexity is still O (1), better than the above several methods


1. Declare a constant with pre-processing instruction # define to indicate how many seconds are in 1 (ignoring leap year issues)
#define SECONDS_PER_YEAR (* * 365) UL
I want to see a few things here:
& #8226;; Basic knowledge of #define grammar (e.g., cannot end with semicolons, use of parentheses, etc.)
& #8226;; Knowing that the preprocessor will calculate the value of a constant expression for you, so write directly how you calculate the year
How many seconds instead of calculating the actual value is clearer and has no cost.
& #8226;; Realize that this expression will overflow the integer number of a 16-bit machine-so use the long symbol L to tell
Codec
This constant is the number of long integers.
& #8226;; If you are using UL (for unsigned long integers) in your expression, then you have a good starting point
。 Remember, first impressions are important.
2. Write a "standard" macro MIN, this macro enters two parameters and returns the smaller one.
#define MIN (A) (A) <= (B)? (A): (B))
This test is designed for the following purposes:
& #8226;; Identifies the basic knowledge that a # define is applied in a macro. This is important because until the embedded (inline) operation
As part of standard C, macros are the only way to generate embedded code, and for embedded systems to
To achieve the required performance, embedding code is often a necessary method.
& #8226;; Knowledge of the triple conditional operator. This operator exists in the C language because it allows the compiler to generate
Than
If‐then‐else more optimized code, it is important to understand this usage.
& #8226;; Be careful to enclose parameters in parentheses in a macro.
& #8226;; I also use this issue to start discussing the side effects of macros, such as: What happens when you write the following code

least = MIN (*p++, b);
3. What is the purpose of the preprocessor identity #error?
If you don't know the answer, see reference 1. This question is very useful for distinguishing between a normal guy and a nerd.
Of Only nerds can read the appendix to the C language textbook to find answers like this. Of course, if you're not looking for a
A nerd, then the candidate better hope he doesn't know the answer.
Dead Loop (Infinite loops)
4. An infinite loop is often used in embedded systems, how do you write a dead loop in C?
This problem is solved with several solutions. My preferred solution is to:
while (1)
{
?}
Some programmers prefer the following scenarios:
for (;;)
{
?}
This implementation is embarrassing for me because the syntax doesn't exactly say what's going on. If a candidate gives this
As a scheme, I will use this as an opportunity to explore the fundamentals of how they do this. If their basic answer is
is: "I was taught to do this, but never thought of why." "It will leave a bad impression on me.
The third option is to use a goto
Loop:
...
Goto Loop;
The candidate gives the above scenario, which means that he or she is an assembly language programmer (which may be a good thing) or that he is
A Basic/fortran programmer who wants to enter a new field.
Data statement (declarations)
5. Use variable A to give the following definition
A) An integer number (an integer)
b) A pointer to the integer number (a pointer to an integer)
c) A pointer to a pointer that points to an integer number (a pointer to a pointer to
An intege) r
d) An array of 10 integers (an arrays of ten integers)
e) An array of 10 pointers that point to an integer number. (An array of ten pointers to
integers)
f) A pointer to the array of 10 integer numbers (a pointer to an array of ten integers)
g) A pointer to a function that has an integer parameter and returns an integer number (a pointer to a func-
tion that takes an integer as a argument and returns an integer)
h) An array of 10 pointers pointing to a function that has an integer parameter and returns an integral type
Number
(An array of ten pointers to functions that take an integer argument and retur
n an integer)
The answer is:
a) int A; An integer
b) int *a; A Pointer to an integer
c) int **a; A pointer to a pointer to an integer
d) int a[10]; An array of ten integers
e) int *a[10]; An array of ten pointers to integers
f) Int (*a) [10]; A pointer to an array of ten integers
g) Int (*a) (int); A pointer to a function A, takes an integer argument an
D returns an integer
h) int (*a[10]) (int); An array of ten pointers to functions a integ
Er argument and return an integer
I agree that there are a number of questions that people often claim are the kind of questions that need to be answered by flipping a book. When I write
This article, in order to determine the correctness of the grammar, I did check the book. But when I was interviewed, I expected
Asked the question (or similar question). Because at the time of the interview, I'm sure I know the problem.
The answer. If the candidate does not know all the answers (or at least most of the answers), then there is no
Prepare, and if the interviewer does not prepare for the interview, then why should he be prepared?
Static
6. What is the role of the keyword static?
Few people can answer this simple question completely. In the C language, the keyword static has three distinct effects:
& #8226;; In the function body, a variable declared as static maintains its value in the process of the function being called.
& #8226;; Within the module (but outside the function body), a variable declared as static can be visited by a function in the module
But cannot be accessed by other functions outside the module. It is a local global variable.
& #8226;; Within the module, a function declared as static can only be called by other functions within this module. That's
, this function is restricted to the local scope of the module that declares it.
Most candidates are able to answer the first part correctly, and part of them can answer the second part correctly, with very few people able to understand the third
Part. This is a serious drawback for a candidate because he clearly does not understand the benefits of localized data and code scope and is heavily
to sex.
Const
7. What is the meaning of the keyword const?
As soon as I heard the interviewee say "Const means constant", I knew I was dealing with an amateur.
Last year Dan Saks has completely summed up all the usages of const in his article, so ESP (translator: Embedded Sy
Stems programming) Each reader should be very familiar with what const can and cannot do. If you never
Read the article, as long as you can say that const means "read only" on it. Although the answer is not a complete answer
, but I accept it as a correct answer. (If you want to know more about the answer, read Saks's article carefully.)
it. )
If the candidate can answer the question correctly, I will ask him an additional question:
What does the following statement mean?
const int A;
int const A;
const int *a;
int * const A;
int const * a const;
/******/
The first two functions are the same, a is a constant integer number. The third means that a is a pointer to a constant integer number (also
On
Yes, the integer number is non-modifiable, but the pointer can). The fourth meaning a is a constant pointer to the integer number (also
This means that the integer number pointed to by the pointer can be modified, but the pointer is non-modifiable. The last one means that A is a
A constant pointer to a constant number (that is, the number of integers pointed to by the pointer is not modifiable, and the pointer is not repairable
Change). If the candidate can answer these questions correctly, then he leaves a good impression on me. Incidentally,
Perhaps you may ask, even without the keyword const, it is easy to write the function of the correct program, then I
What's so important about the keyword const? I also have the following several reasons:
& #8226;; The purpose of the keyword const is to convey very useful information to the person who is reading your code, in fact, declaring a
The parameter is a constant to tell the user the purpose of the application of this parameter. If you've spent a lot of time cleaning up someone else's
Rubbish, you will soon learn to thank for this superfluous information. (Of course, programmers who know how to use Const are seldom left behind.)
Rubbish is made to be cleaned by others. )
& #8226;; By giving some additional information to the optimizer, using the keyword const may produce more compact code.
& #8226;; The use of the keyword const allows the compiler to naturally protect those parameters that do not want to be changed, prevent
Inadvertently modified code. In short, this can reduce the occurrence of bugs.
Volatile
8. What does the keyword volatile mean? and gives three different examples.
A variable that is defined as volatile means that the variable may be unexpectedly changed so that the compiler will not go false
Set the value of this variable. Precisely, the optimizer must carefully reread this variable every time it is used
Instead of using a backup stored in the register. Here are a few examples of volatile variables:
& #8226;; Hardware registers for parallel devices (e.g., status registers)
& #8226;; A non-automatic variable that is accessed in an interrupt service subroutine (non‐automatic variables)
& #8226;; Variables shared by several tasks in multi-threaded applications
The person who cannot answer the question will not be hired. I think it's a distinction between C programmers and embedded system programmers.
The basic question. Embedded guys often deal with hardware, interrupts, RTOS, and so on, all of which require
To
Volatile variable. The content that does not understand volatile will bring disaster.
Assuming that the interviewee answered the question correctly (well, wondering if that would be the case), I'll dig a little deeper and look at a
This guy is not exactly aware of the importance of volatile.
& #8226;; Can a parameter be either const or volatile? explain why.
& #8226;; Can a pointer be volatile? explain why.
& #8226;; What is wrong with the following function:
int square (volatile int *ptr)
{
return *ptr * *PTR;
}
Here's the answer:
& #8226;; Yes. An example is a read-only status register. It is volatile because it can be unexpectedly changed
Change. It is const because the program should not attempt to modify it.
& #8226;; Yes. Although this is not very common. An example is when a service subroutine fixes the one that points to a buf
Fer the pointer.
& #8226;; This piece of code is a bit perverted. The purpose of this code is to return the pointer *ptr to the square of the value, but the
When *ptr points to a volatile parameter, the compiler will produce code similar to the following:
int square (volatile int *ptr)
{
int A, B;
A = *ptr;
b = *ptr;
return a * b;
}
Because the values of the *ptr can be unexpectedly changed, A and B may be different. As a result, this code may be returned without
Is
The square value you expect! The correct code is as follows:
Long Square (volatile int *ptr)
{
int A;
A = *ptr;
Return a * A;
}
Bit operation (bit manipulation)
9. The embedded system always wants the user to perform bit operation on the variable or register. Given an integer variable A, write a two-segment code,
The first one sets a bit 3, the second clears the bit 3 of a. In the above two operations, keep the other bits intact.
There are three basic reactions to this problem.
& #8226;; Don't know how to do it. The quilt cover has never done any embedded system work.
& #8226;; Use bit fields.
Bit fields is something that is thrown into the C-language corner, which guarantees that your code is in a different
The translator is not portable, and it ensures that your code is not reusable. I've recently been unlucky to see Infineo
n A driver written for its more complex communication chip, it uses bit fields so it's totally useless to me because my
Compilers implement bit fields in other ways. From the moral: never let a non-embedded guy stick Solid
Edge of the inter-hardware.
& #8226;; Operate with #defines and bit masks. This is a highly portable approach that should be used
to the method. The best solution is as follows:
#define BIT3 (0x1 << 3)
static int A;
void Set_bit3 (void) {
a |= BIT3;
}
void Clear_bit3 (void) {
a &= ~bit3;
}
Some people like to define a mask for setting and clearing values and defining some description constants, which is acceptable. I
Want to see a few points: Description constants, |=, and &=~ operations.
Access to fixed memory locations (accessing fixed locations)
10. Embedded systems often have features that require programmers to access a particular memory location. In a project, it is required to set
The value of an integer variable with an absolute address of 0x67a9 is 0xaa66. The compiler is a purely ANSI compiler. Write generation
Code
To complete the task.
This question tests whether you know that in order to access an absolute address an integral number is cast (typecast) as a pointer
is legal. The way this problem is implemented varies with individual style. A typical similar code looks like this:
int *ptr;
PTR = (int *) 0x67a9;
*ptr = 0xaa55;
A more obscure approach is:
One of the more obscure methods is:
* (int * const) (0X67A9) = 0xaa55;
Even if your tastes are closer to the second option, I suggest you use the first option in your interview.
Interrupt (interrupts)
11. Interrupts are an important part of the embedded system, which leads to a number of compiler developers providing an extension-let the standard
C support interrupts. The fact that it is represented is that a new keyword __interrupt has been produced. The following code uses the __in
Terrupt the keyword to define an interrupt service subroutine (ISR), please comment on this piece of code.
__interrupt Double Compute_area (double radius)
{
Double area = PI * radius * RADIUS;
printf ("\narea =%f", area);
return area;
}
There are so many mistakes in this function that you don't know where to start:
& #8226;; The ISR cannot return a value. If you do not understand this, then you will not be employed.
& #8226;; The ISR cannot pass parameters. If you do not see this, your chances of being employed are equal to the first item.
& #8226;; In many processors/compilers, floating-point is generally non-reentrant. Some processors/compilers require
The registers on the forehead are stacked, and some processors/compilers are not allowed to do floating-point operations in the ISR. In addition, the ISR should
is short and efficient, it is unwise to do floating-point operations in the ISR.
& #8226;; With the 3rd same strain, printf () often has re-entry and performance problems. If you lose the third and
4th, I will not be too difficult for you. Needless to say, if you can get after two o'clock, then your employment prospects are getting more and more light
Know.
*****
Example code examples
12. What is the output of the following code and why?
void foo (void)
{
unsigned int a = 6;
int b =‐20;
(A+b > 6)? Puts ("> 6"): Puts ("<= 6");
}
This question tests whether you understand the principle of automatic conversion of integers in C, and I find that some developers know very little about these east
Xi. However, the answer to this unsigned integer question is that the output is ">6". The reason is that when there are symbols in an expression
Types and unsigned types, all operands are automatically converted to unsigned types. So ‐20 became a very big
Of
is a positive integer, so the expression evaluates to a result greater than 6. This is the case for nested data types that should be used frequently for unsigned
In-system is very important. If you answer the wrong question, you will not get to the edge of the job.
13. Evaluate the following code snippet:
unsigned int zero = 0;
unsigned int compzero = 0xFFFF;
/*1 ' s complement of zero */
For an int type that is not a 16-bit processor, the above code is not correct. Should be prepared as follows:
unsigned int compzero = ~0;
This problem really reveals whether the test taker understands the importance of processor word length. In my experience, a good embedded process
The sequencer has a very accurate understanding of the hardware details and its limitations, whereas PC programs often use hardware as an unavoidable
Of
Trouble.
At this stage, candidates are either completely depressed or confident. If obviously the candidate is not very
OK, so this test is over here. But if obviously the candidate does a good job, then I'll throw out the following append
Problem, these problems are more difficult, I think only very good candidates can do well. To raise these questions, I hope
Look for more ways to see candidates coping with problems than answers. No matter what, you should be the entertainment bar ...
Dynamic memory allocation (allocation)
14. Although not as common as non-embedded computers, embedded systems have a dynamic allocation of memory from the heap
Process. So what are the possible problems with the dynamic allocation of memory in an embedded system?
Here, I expect the candidate to refer to memory fragmentation, fragmentation collection issues, variable time-of-hold, and so on. This topic has been
has been extensively discussed in the ESP magazine (mainly P.J Plauger, his explanation is far more than I can mention here
Any explanation), all go back and look at these magazines! Let the test taker enter a false sense of safety after I take
Out of such a small show:
What is the output of the following code fragment and why?
Char *ptr;
if (ptr = (char *) malloc (0)) = =
NULL)
Else
Puts ("Got a null pointer");
Puts ("Got a valid pointer");
This is an interesting question. Recently, a colleague of mine accidentally passed the 0 value to the function malloc and got a
The law of the pointer, I only thought of this question. This is the code above, the output of this code is "Got a valid PO
Inter ". I use this to start discussing such a problem and see if the interviewee thinks the library routine is doing the right thing.
。 It's important to get the right answer, but the solution to the problem is more important than the rationale for your decision.
Typedef
:
In C, the Typedef is frequently used to declare a synonym for a data type that already exists. You can also use a preprocessor
Do something like that. For example, consider the following example:
#define DPS struct S *
typedef struct S * tPS;
The intent of both of these cases is to define DPS and TPS as a pointer to the struct S. Which method is better?

If so, why?
This is a very delicate question, and anyone who answers the question correctly (for the right reason) should be congratulated. The answer is:
typedef better. Consider the following example:
DPS P1,P2;
TPS P3,P4;
The first extension is a
struct S * p1, p2;
.
The code above defines P1 as a pointer to a struct, p2 as an actual structure, which may not be what you want. The
Two
An example correctly defines the P3 and P4 two pointers.
The Obscure grammar
16. C language agree to some shocking structure, the following structure is legal, if it is what it does?
int a = 5, B = 7, C;
c = a+++b;
This question will be done as a happy ending to this quiz. Whether you believe it or not, the above example is perfectly grammatical.
Of The question is how does the compiler handle it? A low-level compilation author actually argues this problem, based on the most processed original
, the compiler should be able to handle as many legitimate usages as possible. Therefore, the above code is processed into:
c = a++ + b;
Therefore, this code is held after a = 6, B = 7, c = 12.
If you know the answer, or guess the right answer, do it well. If you don't know the answer, I don't think of it as a problem.
I found the biggest benefit of this problem is that it is a code writing style, code readability, code modification
A good topic.

Linux C-Plane question summary

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.