嵌入式软件开发面试题interview Questions for firmware engineer(1)

这篇文章详细探讨了进程与线程在资源分配、内存共享、切换开销及优缺点等方面,比较了多进程与多线程的选择,介绍了进程间与线程间通信方法,涵盖了上下文切换、内存溢出预防、变量作用域和生命周期、编译优化以及MMU基础知识。同时讨论了硬实时系统与软实时系统的区别。
摘要由CSDN通过智能技术生成
  1. Processes and Threads (Different System Resource Management Methods)
  2. Difference
    • Process: Basic unit of resource allocation, composed of one or more threads.
    • Thread: Basic unit scheduled by the dispatcher, representing a task.
    • Each process has its independent memory space, and a process can have multiple threads. Process switching has high overhead.
    • Multiple threads share memory, and thread switching has low overhead.
    • A process crash doesn’t affect other processes.
    • A thread crash affects the entire process it belongs to.
  3. Pros and Cons of Multiprocessing and Multithreading
    • Memory usage, data sharing, synchronization, CPU utilization, creation/destruction, and switching speed, reliability, programming and debugging comparisons.
  4. Choosing Between Processes and Threads
    • Choose threads for frequent creation/destruction.
    • Choose threads for tasks requiring significant computation and frequent switching.
    • Choose processes for safety and stability.
    • Choose threads for speed.
  5. Interprocess and Interthread Communication (Synchronization) Methods
    • Interprocess: Named pipes, unnamed pipes (parent-child processes), message queues, semaphores, shared memory, sockets.
  6. Process State Transitions
    • Ready, Blocked, Running.
  7. Parent Process and Child Process
    • After calling fork() in the parent process, a child process is created with identical code, data, and user stack.
    • Typically, the parent process waits for the child process to finish.
  8. Context Switching
    • Process context switching involves saving the values of all CPU registers, stack content, and execution position for later restoration.
    • Interrupt context involves saving the current process’s execution state when an interrupt occurs.
  9. C/C++
  10. new and malloc
    • malloc and free are C/C++ library functions, requiring the stdlib.h header.
    • new and delete are C++ keywords, no header needed, compiler support required.
    • new allocates memory without specifying size; malloc requires size.
    • Results: new returns a typed pointer; malloc returns a void pointer.
  11. Memory Allocation for 1GB (malloc 1.2GB)
    • Possible; malloc allocates virtual address space, not physical memory.
  12. extern “C” Purpose
    • Allows C++ code to call C code, ensuring the compiler compiles according to C language conventions.
  13. Functions Leading to Memory Overflow and Improvement
    • strcat and strcpy can lead to overflow.
    • Improvement: Use strncat, strncpy, or memcpy with specified limits.
  14. Static Usage
    • static for local variables keeps them in the static area; they persist beyond function calls.
    • static for global variables limits their scope to the current file.
    • static for functions restricts their visibility to the current file.
  15. const Usage
    • const makes data read-only.
  16. Volatile Purpose and Usage
    • Prevents compiler optimization, forces reading from memory instead of cached values.
    • Usage: Hardware registers, shared variables in multithreading, variables accessed by interrupt handlers.
  17. const Constants vs. #define Macros
    • #define max 1 replaces during preprocessing, no memory allocation, no type safety.
    • const int max = 1; determines value during compilation, allocates memory, type-safe.
  18. Variable Scope and Lifetime
    • Global variables: File scope, available externally, lasts until program termination.
    • Local variables: Function scope, created on entry, destroyed on exit.
  19. sizeof and strlen
    • sizeof() is an operator, returns the size in bytes during compile time.
    • strlen() is a function, returns the length of a string during runtime, requires <string.h> header.
int main()  
{   
    char *p = "hello";  
    // p is a pointer to a string literal "hello"
    
    char arr1[] = "hello";  
    // arr1 is an array of characters initialized with the string "hello"
    
    char arr2[] = { 'h', 'e', 'l', 'l', 'o' }; 
    // arr2 is an array of characters initialized individually
    
    printf("%d\n", sizeof(p));
    // Result is 4 on 32-bit systems and 8 on 64-bit systems
    // The size of a pointer variable depends on the system's architecture
    
    printf("%d\n", sizeof(arr1));
    // Result is 6 because it includes the null terminator '\0'
    
    printf("%d\n", sizeof(arr2));
    // Result is 5 because it's a character array, not a string, and doesn't include '\0'
    
    printf("%d\n", strlen(p));
    // Result is 5 because strlen calculates the length of the string, excluding the null terminator
    
    printf("%d\n", strlen(arr1));
    // Result is 5 because strlen calculates the length of the string, excluding the null terminator
    
    printf("%d\n", strlen(arr2));
    // The behavior is undefined because arr2 is not null-terminated; it prints a random value
    
    return 0;
}
  1. Memory Alignment in struct and union
    Memory alignment purpose: Facilitates CPU memory access, saves storage space.
    Struct Alignment:
  2. The starting address of a structure variable and its total size are multiples of the largest data type in the structure.
  3. The offset of each member relative to the structure’s starting address is a multiple of the member’s size.
    • Placing members with the same type and larger size first reduces padding characters added by the compiler for alignment.
    • For example, on a 32-bit CPU with 4-byte addressing, if the first member is char, the second is int, and the third is char, it allocates 12 bytes of space.
    Union Alignment:
    • If int b, char a[9] with the largest data member being char a[9], it allocates a total of 12 bytes of space.
    • Preprocessor directive #pragma pack(n) aligns all members based on n bytes.
    • attribute(packed) cancels alignment.
  4. Inline Functions:
    • A space-time trade-off, eliminating the overhead of function calls and returns by directly expanding and running the code.
    • Suitable for functions with fewer statements that are called multiple times, without loops or recursion; otherwise, the compiler may optimize.
    • Declaration and definition should be together to avoid linker errors.
  5. Memory Partition:
    • Stack: Compiler allocates for return values and local variables.
    • Heap: User-managed allocation.
    • Global/Static Area: Global variables, static variables, constants.
    • Code Area: Binary code (ROM).
  6. Determining Endianness in 32-bit Compilation:
    • Big Endian: Most significant byte at the lowest address, least significant byte at the highest address.
    • Little Endian: Most significant byte at the highest address, least significant byte at the lowest address.
    • Check method:
    • Use a union, start storing from the lowest address, and only one member occupies memory at a time.
#include <stdio.h> 
int main() {  
union w{ 
 int a;
 char b;
}c;
 c.a=1;
 if(c.b==1)
  printf("xiaoduan\n");
 else
  printf("daduan\n");
 return 0;
}

Forcefully convert an int to char, and make p point to the low byte of a.

#include <stdio.h>
int main() { 
 int a=1;
 char *p=(char*)&a;
 if(*p==1)
  printf("xiaoduan\n");
 else
  printf("daduan\n");
 return 0;
}
  1. Variable Definition using Variable ‘a’:
    A variable ‘a’ is defined as a pointer to a function. The function takes an integer parameter and returns an integer.
    int (*a)(int);

  2. Operator Precedence:
    Operator precedence follows the order of arithmetic operations, then bitwise shift operations, and finally relational operators.
    Three. Network Programming:

  3. OSI Model:
    • OSI stands for Open System Interconnection Reference Model.
    • Physical Layer: Defines data transmission media (e.g., optical fibers) and MAC addresses.
    • Data Link Layer: Encapsulates data (e.g., Ethernet).
    • Network Layer: Handles path selection (e.g., IP).
    • Transport Layer: Establishes end-to-end connections (e.g., TCP, UDP).
    • Session Layer: Manages session connections between presentation layer entities.
    • Presentation Layer: Ensures data format compatibility.
    • Application Layer: Provides software interfaces (e.g., HTTP, SSH, FTP, SMTP).

  4. TCP, UDP:
    TCP (Transmission Control Protocol):
    • TCP is a connection-oriented and reliable byte-stream service.
    • Programming is complex, but it offers reliability (no errors, no loss, no duplication, in order), stability, low efficiency, and high resource usage.
    • It involves connection establishment before transmission, acknowledgment mechanisms, retransmission mechanisms, congestion control, and a three-way handshake.
    • Suitable for scenarios requiring high signal quality and integrity, such as sending emails.
    UDP (User Datagram Protocol):
    • UDP is a connectionless and unreliable datagram service.
    • Programming is simple, it offers high efficiency but is less reliable.
    • It operates without maintaining connection state, making it prone to packet loss.
    • Suitable for scenarios where quality requirements are not stringent, and speed is crucial, such as video calls.

  5. Three-Way Handshake, Four-Way Handshake:
    Three-Way Handshake:
    • The process of establishing a TCP connection involves a three-way handshake.

  6. SYN (Synchronize): The client sends a SYN packet to the server, indicating its intention to establish a connection.

  7. SYN-ACK (Synchronize-Acknowledge): The server responds with a SYN-ACK packet, acknowledging the client’s request and expressing its own readiness.

  8. ACK (Acknowledge): The client sends an ACK packet, confirming the establishment of the connection.
    Four-Way Handshake:
    • The process of terminating a TCP connection involves a four-way handshake.

  9. FIN (Finish): The initiator sends a FIN packet to the other end, indicating its desire to close the connection.

  10. ACK (Acknowledge): The other end acknowledges the FIN packet with an ACK.

  11. FIN (Finish): The other end also sends a FIN packet when it’s ready to close the connection.

  12. ACK (Acknowledge): The initiator acknowledges the FIN packet, and the connection is fully closed.

Four. Common Algorithms:
Stable, Unstable, Internal Sorting, External Sorting, Time Complexity, Space Complexity:
Bubble Sort:
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
• Stability: Stable (maintains the relative order of equal elements).
• Sorting Type: Internal Sorting (sorting data entirely in the computer’s main memory).
• Time Complexity: O(n²) in the worst case.
• Space Complexity: O(1) as it requires only a constant amount of additional memory.

#include <stdio.h>
void Swap(int *a , int *b)
{
 int tmp = *a;
 *a = *b;
 *b = tmp;
}
void BubbleSort(int* a, int n)
{
 for (int i = n-1; i >= 0; i--){
  for ( int j = 0; j < i; j++){
   if (a[i]>a[j + 1])
    Swap(&a[i], &a[j + 1]);
  }
 }
}
int main() 
{ 
 int a[5] = {8,5,8,7,6};
 BubbleSort(a , 5);
 for(int i = 0 ; i < 5 ;i++)
  printf("%d\n",a[i]);
}

快速排序:

#include <stdio.h>

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];  // Choose the rightmost element as the pivot
    int i = (low - 1);  // Index of smaller element

    for (int j = low; j <= high - 1; j++) {
        // If the current element is smaller than or equal to the pivot
        if (arr[j] <= pivot) {
            i++;  // Increment index of smaller element
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quicksort(int arr[], int low, int high) {
    if (low < high) {
        // Partitioning index
        int pi = partition(arr, low, high);

        // Separately sort elements before and after partition
        quicksort(arr, low, pi - 1);
        quicksort(arr, pi + 1, high);
    }
}

int main() {
    int arr[] = {12, 4, 5, 6, 7, 3, 1, 15};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    quicksort(arr, 0, n - 1);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
 
  1. Linux Operating System:

  2. Linux Kernel:
    • Responsible for process scheduling, memory management, virtual file system, network interfaces, and inter-process communication.
    • Link to source
    Feel free to ask if you have any more questions or need further clarification!

  3. Components of the Linux System:
    • Kernel, Shell, File System, Application Programs

  4. Communication between User Space and Kernel:
    • Using mmap system call: Maps kernel space address to user space.
    • Netlink.
    • Using APIs.
    • Files.
    • Using the /proc file system.

  5. Differences between System Calls and Regular Function Calls:
    • System Calls:
    • Use INT and RET instructions; different stacks for kernel and applications.
    • Depends on the kernel, not guaranteed to be portable.
    • Involves a significant overhead due to context switching between user and kernel space.
    • Serves as an entry point to the operating system.
    • Regular Functions:
    • Use CALL and RET instructions; no stack switching during function calls.
    • Highly portable.
    • Low overhead as it operates in the user space.
    • Typical function call.

  6. Kernel Mode vs. User Mode:
    • Kernel Mode: Runs system programs, highest privilege level (Ring 0).
    • User Mode: Runs user programs, privilege level Ring 3.

  7. Bootloader, Kernel, Root File:
    • Boot sequence: Bootloader -> Kernel -> Root file -> Application.
    • Bootloader initializes hardware, loads kernel and root file into RAM, sets up necessary parameters, and starts the application.

  8. Bootloader Two Stages:
    • Stage 1:
    • Basic hardware initialization (disable watchdog and interrupts, set CPU frequency).
    • Prepare RAM space for loading Stage 2.
    • Copy kernel and file system images to RAM.
    • Set the stack pointer (SP).
    • Jump to Stage 2 entry.
    • Stage 2:
    • Initialize hardware needed for this stage (serial ports, network cards).
    • Detect system memory mapping.
    • Load kernel and file system images.
    • Set kernel’s boot parameters.
    • Call the kernel.

  9. Commands to Check Memory Status:
    • top
    • free
    • cat /proc/meminfo
    • vmstat

  10. Program Execution Process:
    • Preprocessing (.i): Handle preprocessing directives, macro replacement, conditional compilation, include headers, remove comments, add line numbers and file name identifiers.
    • Compiling (.s): Lexical, syntax, semantic analysis, optimization, generate assembly code.
    • Assembling (.o): Convert assembly code to machine-executable instructions, generate object files.
    • Linking (.exe): Integrate various object files, address and space allocation, relocation, symbol resolution.

  11. Heap, Stack, Memory Leaks, and Overflow:
    • Heap: Managed by programmers for dynamic allocation.
    • Stack: Managed by the compiler for local variables.
    • Memory Leak: Allocated memory not freed, persists until program termination (e.g., malloc without free).
    • Memory Overflow: Requested memory exceeds the system’s allocation capacity, risking boundary violations and type safety.
    • Memory Overrun: Using memory beyond the system’s allocated range, such as accessing specific arrays.

  12. Causes and Conditions of Deadlocks:
    • Causes: Resource competition, inappropriate process execution order.
    • Necessary conditions:
    • Mutual exclusion.
    • Hold and wait.
    • No preemption.
    • Circular wait.

  13. Hard Links vs. Soft Links:
    • To address file sharing.
    • Hard Links: ln source target, similar to Windows shortcuts.
    • Soft Links: ln -s source target, similar to cp -p with synchronization updates.

  14. 32-bit and 64-bit Computers:
    • Larger addressing space (2⁴⁸).
    • Support for more extensive memory.
    • Capability to address in 64-bit format, with 64-bit general registers and arithmetic units.

  15. Interrupts and Exceptions:
    • External Interrupts: Triggered by external device events.
    • Internal Interrupts (Exceptions): Result from CPU internal events, like program errors (illegal instructions, address overflow).
    • Exceptions are due to the execution of the current instruction, while interrupts are due to external events.

  16. Interrupt Handling Process:
    • Request interrupt.
    • Respond to interrupt.
    • Disable interrupt.
    • Save context.
    • Identify interrupt source.
    • Protect context.
    • Execute interrupt service routine.
    • Restore context.
    • Enable interrupt.
    • Return.

  17. Commands for Suspending, Sleeping, and Shutting Down:
    • Shutdown: halt, init 0, poweroff, shutdown -h time.
    • Reboot: reboot, init 6, shutdown -r time.
    • Suspend: sudo pm-suspend.
    • Hibernate: sudo pm-hibernate.

  18. GCC Compilation Optimization:
    • Use gcc -O for optimization.

  19. DMA Data Link in the Presence of Data Cache:
    • Peripheral -> DMA -> DDR -> Cache -> CPU.

  20. Linux Commands: (Missing specific commands; please provide them for translation.)

  21. Hard Real-Time Systems vs. Soft Real-Time Systems:
    • Hard Real-Time Systems: Strict, inflexible time constraints, no tolerance for errors beyond deadlines (e.g., FreeRTOS, uC/OS).
    • Soft Real-Time Systems: Flexible time constraints, can tolerate occasional deadline breaches (e.g., Windows, Linux).

  22. MMU Basics:
    • Modern operating systems adopt virtual memory management with the support of Memory Management Unit (MMU).
    • Some embedded processors lack MMU and cannot run operating systems relying on virtual memory management.
    • Operating systems with MMU: Windows, Linux, macOS, Android.
    • Operating systems without MMU: FreeRTOS, uC/OS.
    • CPUs with MMU: Cortex-A, ARM9.
    • CPUs without MMU: Cortex-M.

  • 15
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值