Location>code7788 >text

Linux final exam questions (2)

Popularity:105 ℃/2025-05-06 17:01:45

Linux final exam questions

1. Multiple choice questions (30 points in total, 2 points for each question)

1. The following statement about free software is correct (D

A. Free software is a kind of copyrighted software. B. Modifying free software should obtain the permission of the original author.

C. Microsoft's Office software is free software, and free software is not necessarily free.

answer:

Free software does have copyright protection (usually based on copyright law or similar legal frameworks), but it gives users specific freedoms through specific licenses (such as GPL, MIT, etc.). Therefore, free software is copyrighted, but this protection is to ensure that users enjoy the freedom of free software, rather than restricting users' use.

One of the core principles of free software is that users can freely modify the software without obtaining the permission of the original author in advance. Users are free to modify and distribute the software as long as they comply with the corresponding free software license terms (such as providing modified source code).

Microsoft's Office software is proprietary software, and its source code is not disclosed, and users do not have the right to use, modify and distribute freely.

The "freedom" of free software refers to the freedom users enjoy to run, copy, distribute, learn, modify and improve the software, rather than the price of the software. Free software is available for free or can be charged (for example, some companies may provide technical support or additional services for free software and charge). The key is whether the user enjoys the above freedoms, not whether the software is free.

2. Use which of the following commands can display all files and subdirectories in the directory (D)

A、ls -l B、dir -all C、ls -a D、ls -R

answer:

ls -lUsed to list files and subdirectories in the current directory in a long format (details), but it does not recursively display the contents in the subdirectories.

diris a command used in certain systems (such as Windows' CMD) to list the contents of the directory. In Unix/Linux systems,dirUsuallylsalias, but-allnodirorlsvalid option. Therefore, this option is not applicable in Unix/Linux systems.

ls -aUsed to list all files and subdirectories in the current directory, including hidden files (files starting with dots). However, it does not recursively display the contents in the subdirectory.

ls -RUsed to recursively list files and subdirectories in the current directory and all its subdirectories.

3. Which of the following commands can find content in the file (C)。

A、pause B、cat C、grep D、 more

answer:

pauseNot a standard command in Unix/Linux systems. In some environments (such as Windows batch scripts),pauseUsed to pause script execution and wait for the user to press a key, but it has nothing to do with file content search.

catThe command is used to display the entire content of a file, but it does not have the search function.

grepis a powerful text search tool designed for finding lines in files that match specific patterns (strings or regular expressions).

oreIt is a command to view file contents by page. Users can browse file contents page by page, but it does not provide search function itself.

4. Which of the following environment variables represents the search path of the command (A)。

A、PATH B、PWD C、HOME D、PSI

answer:

PATHIs an environment variable that defines the directory in which the system looks for executable commands. When the user enters a command in the terminal, the system will followPATHThe directories listed in search of the executable files for the command in sequence.echo $PATHThe command search path of the current system will be output.

PWD(Print Working Directory) is an environment variable that represents the absolute path to the current working directory. It has nothing to do with the search path of the command.

HOMEis an environment variable that represents the home directory path of the current user. It is usually used to store user's personal files and configurations, regardless of the search path of the command.

PSINot a common environment variable, nor is it a variable used to define the command search path. In some contexts,PSIIt may have other meanings (such as process state interface), but it has nothing to do with this question.

5. By default, the administrator creates a user and will be (BCreate a user home directory under the ) directory.

A、/usr B、/ home C、/root D、/boot
answer:

/usrDirectories are usually used to store system software and program resources, such as executable files, library files, and documents.

/homeIt is the standard storage location of the user's home directory in Linux system. By default, when the administrator creates a new user, the system will/homeCreate a subdirectory named after the user as its home directory under the directory.

/rootIt is the exclusive home directory of the system administrator (root user).

/etcDirectories are used to store system configuration files, such as user account information, network configuration, service configuration, etc.

Which command can be used to save the file(A)。

A、:w B、:save C、:q D、:r

answer:

:wyesviCommands in the editor to write (save) the contents of the current buffer into a file. If the file already exists, overwrite the original file; if the file does not exist, create a new file.

:savenovistandard command.viThere is no direct name in:saveThe command to save the file.

:qyesviCommands in the editor to exit the editor. But if the file is not saved, use it directly:qWill cause an error (unless used:q!Forced exit).

:ryesviCommands in the editor to read the file contents and insert it into the current cursor position.

In which file is stored in the following file (C)。

A、/etc/sudoers B、/etc/ passwd C、/etc/shadow D、/etc/inittab

answer:

/etc/sudoersFiles for configurationsudoThe permissions of the command define which users or user groups can be used as other users (usuallyroot) executes the command.

/etc/passwdFiles are files used to store user account information in Linux system, including username, user ID, group ID, home directory, login shell, etc. However, for security reasons, modern Linux systems usually do not store encrypted user passwords in this file, but use a placeholder (e.g.xor*)replace.

/etc/shadowFiles are files in Linux systems that are specially used to store encrypted user passwords. It can only berootReading by the user includes information such as the user's encryption password, password final modification time, password validity period, etc.

/etc/inittabFiles (may have beensystemdReplace) is used to configure the initialization process of the system, define the system operation level, start scripts, etc.

The command to display the file type in it is (C)。

A、whereis B、list C、file D、cat

answer:

whereisUsed to find the location of binary files, source files, and man pages.

lsUsed to list directory contents, but do not display file types (unless combined-For-lOptions such as view some type information, but do not directly display the file type description).

fileIs a command in Linux that determines the type of file. It will read the contents of the file and try to identify the format of the file (such as text files, binary files, executable files, picture files, etc.), and output the corresponding description.

catThe command is used to display the entire contents of a file, but it does not provide information about the file type. It just outputs the file contents to the terminal.

is a directory, when the "rm -rf dirl" command is executed, the Linux system will (B)。

A. After confirmation by the user, delete dirl B. Directly delete all files under dirl and dirl

C. Only delete files under dirl and keep the directory dirl D. Only when dirl is not empty can it be deleted

answer:

rmis a command used to delete files or directories.

-r(or-R) option means recursive deletion, i.e. deleting a directory and all its contents (including subdirectories and files).

-fThe option indicates forced deletion, that is, the user does not prompt for confirmation, and directly deletes the file or directory (even if the file is read-only or the user does not have write permissions, it will try to delete it unless the permission is completely denied).

10. Execute the "cp -s" command to (D)。

A. Copy the file B. Copy the directory C. Create a hard link to a file D. Create a symbolic link to a file

answer:

cpis a command used to copy files or directories.

The -s option is used in the cp command to create symbolic links (also known as soft links), rather than copying file contents.

A symbolic link is a special file pointing to another file or directory, similar to a shortcut in Windows. If the source file is deleted or moved, the symbolic link will be invalid (becomes a "dangling link").

cpThe basic function of the command is to copy files, but-sThe option changes the default behavior, instead of making actual copy, instead creating symbolic links.

cpThe command can be used-ror-ROption recursively copy the directory.

Hard link is throughlnCommand (without-sOptions) Created, the hard link is another name of the file, sharing the same inode and data blocks as the original file.

11. Which of the following commands can rename the file(C)。

A、chown B、chname C、mv D、chmod

answer:

hownCommands are used to change the owner (i.e., users or user groups) of a file or directory. Its basic syntax ischown [Options] New Owner File

chnameNot a standard command in Linux. In common Linux distributions, this command is not used for file renaming.

mvCommands are used to move files or directories, and can also be used to rename files or directories. Its basic syntax ismv [Options] Source file or directory Target file or directory. If the target path and the source path are in the same directory but have different names, it is equivalent to renaming.

chmodCommands are used to change permissions to files or directories (i.e. read, write, and execute permissions). Its basic syntax ischmod [Options] Permissions File

12. Use the gcc command to compile a C language program. The executable program that needs to be output has debugging information. It should (B)

A、gcc -o B、gcc -g C、gcc -E D、gcc -c

answer:

-oOptions are used to specify the name of the output file. For example,gcc -o myprogram The compiled executable file will be namedmyprogram. but-oDebug information is not added by itself.

-gOptions are used to generate debug information at compile time. These debugging information (such as symbol table, line number information, etc.) will be embedded in the executable file for the debugger (such asgdb)use.

gcc -EUsed to preprocess only the source file and output the preprocessing results to standard output (or save to the file via redirection). It does not generate executable programs and does not add debug information.

-cOptions are used to compile only the source file and generate the target file (.ofile), without linking. It does not generate the final executable program, nor does it add debug information to the executable program (because the executable program is not generated at all).

13. What are the following contents in the inode of the file?A)。

A. File name B. File access permissions C. File links D. File data block location

answer:

inode is a data structure used in Linux file system to store file metadata.

The information contained in inode usually includes:

  • File type (such as normal files, directories, symbolic links, etc.).
  • Access permissions to files (such as read, write, and execute permissions).
  • The number of hard links to the file (i.e. the number of directory entries pointing to the inode).
  • The user ID and group ID of the file owner.
  • The size of the file in bytes.
  • A pointer to the file data block (i.e. where the file data is stored on disk).
  • Time stamps such as file creation time, modification time, access time, etc.

The information not included in inode is the file name. The file name is stored in the directory item, which maps the file name to the corresponding inode number.

14. In order to achieve the permissions of the owner and the same group of users to read (r), write (w) and execute (x), while other users have read (r) execution permissions (x), when setting the permission value of the file, it should be set to (C)。

A、665 B、774 C、775 D、654

answer:

Read (r): 4 Write (w): 2 Execute (x): 1

Principal authority: 4+2+1=7

User permissions in the same group: 4+2+1=7

Other user permissions: 4+1=5

Therefore, when setting the permission value, it should be set to 775

When programming, the meaning of the expression [ $a = $b ] is (B)

A. Assign the value of variable b to variable a B. Test whether the string a and string b are equal

C. Test whether integer a and integer b are equal. D. Assign the value of variable b to variable a and return the value of b

answer:

=exist[ ]is used for string comparison (not assignment).

If variable$aand$bThe string value of the same, the expression returns true (exit status is 0), otherwise it returns false (non-0).

=exist[ ]It is not an assignment operation, and assignment is used in the shell=Complete directly (e.g.a=$b

Test whether integers are equal and should be used-eq(like[ $a -eq $b ]

[ ]It is a conditional test, no value is assigned or returned.

2. Short answer questions (40 points in total, 10 points in each question)

1. What are the pipeline function and input/output redirection function of Linux? Give examples how to use this function.

answer:Linux pipeline functions (|) is used to use the output of one command as the input of another command to realize data transfer between commands; input/output redirection is through symbols (such as>>><) Redirect the input/output of the command from the default device (such as the keyboard/screen) to a file or other device. For example:

  • pipeline:ls -l | grep ".txt"Willls -lThe output ofgrep, only display contains.txtfile.
  • Output redirection:echo "Hello" > WillechoThe output redirects to(cover the original content),>>Add content.
  • Enter redirection:grep "word" < fromRead input and search"word"

2. Please list the main directory of the Linux operating system and explain what the function of this directory is. (Note: Please list at least 10 directories)

answer:

Here are some descriptions of at least 10 main directories and their functions in Linux operating systems:

  1. /(Root directory)
    The starting point of the entire file system, all other directories and files are located in the root directory or in its subdirectories, and are the highest level of the Linux file system.
  2. /bin
    Store basic commands required for system startup and daily operations, such aslscpmvandcatetc. These commands can be used without additional permissions.
  3. /sbin
    Store key commands, most of these instructions are designed for root users, such as partitioning tools,ifconfig(Network Configuration Tool) andshutdown(Shut down command) etc.
  4. /etc
    Store the system configuration files, almost all system service settings files are placed in this directory, covering settings from user account (such as/etc/passwd) to network settings (e.g./etc/network), and system startup related settings (such as/etc/hostname) and many other aspects.
  5. /dev
    Store device files. These files are not used to store data, but serve as a bridge for the operating system to communicate with various hardware devices. Through these device files, we can identify and operate hardware such as hard disks, keyboards, mouses, optical drives, etc.
  6. /proc
    A virtual file system reflects the status information of the system running in real time. Users can obtain process, memory, CPU, hardware status and other data through files in this directory.
  7. /var
    Store frequently changing files in the system, such as system logs, caches, emails and print queues. As these files continue to increase, administrators need to maintain and clean them regularly.
  8. /tmp
    It is used to store temporary files, whether they are temporary files generated when the program is run or temporary data generated by user operations, they will be stored here. The files in this directory are usually valid for a short period of time.
  9. /usr
    An area for storing common files and user applications, including many applications, library files and documents.
  10. /home
    The root directory where all the personal profiles of ordinary users are stored. Each user has an exclusive subdirectory named after their username, where their personal files, settings and documents are stored. Users can independently manage their home directory contents, while system administrators have permission to access and manage the home directory of all users.

3. What is a memory leak? What impact does a memory leak have on the system? How to avoid memory leaks when programming.

answer:Memory leak refers to the program failing to correctly release the memory that is no longer used after dynamically allocating memory, resulting in this part of the memory being permanently occupied and cannot be recycled by the system;

Its impact on the system includes gradually exhausting available memory, causing program or system performance degradation (such as lag, slow response), and even causing system crashes (especially in long-term running processes or environments with limited memory resources);

Methods to avoid memory leaks during programming include: timely release memory that is no longer used, adopting automatic memory management languages ​​(such as Java/Python garbage collection mechanism), using tools to detect leaks, and developing good programming habits to avoid repeated allocation of unfreed memory in loops.

4. The system administrator needs to complete the following repetitive tasks every day. Please use the crontab command to compile these tasks according to the following requirements:

(1) Display the current time on the screen every hour (every hour);

0 * * * * echo "Current time: $(date)"

(2) Turn on the network device at 6:00 a.m. every day (eth0);

0 6 * * * ifconfig eth0 up

(3) Turn off the network equipment regularly at 23:00 every night (eth0);

0 23 * * * ifconfig eth0 down

(4) Backup pub file data into data files every 2 hours from Monday to Friday;

0 */2 * * 1-5 cp /opt/pub /opt/data

(5) Delete temporary files (files in the /temp directory) every Friday at 18:00 pm.

0 18 * * 5 rm -rf /temp/*

3. Comprehensive programming questions (total 30 points, 15 points for each question)

1. Write a shell script that can cycle through the student's percentage score and convert it into the corresponding grade level display.

Excellent: 90-100 Good: 80-89 Premium: 70-79 Passed: 60-69 Failed 0-59

When the entry is completed, press the q or Q key to display the number of people who have entered the scores of each level, and then exit the program.

untie:

#!/bin/bash

 # Initialize the counter
 excellent=0
 good=0
 medium=0
 pass=0
 fail=0

 # Circular entry of results
 #Use the read command to prompt the user to enter the score and store the input in the variable score
 while true; do
     read -p "Please enter the percentage score of the student (enter q or Q to exit): " score

     # Check whether to exit
     if [[ "$score" =~ ^[qQ]$ ]]; then
         break
     fi

     # Check whether the input is a number
     if ! [[ "$score" =~ ^[0-9]+$ ]]; then
         echo "The input is invalid, please enter an integer or q/Q to exit."
         Continue continue
     fi

     # Judge grade
     if (( score >= 90 && score <= 100 )); then
         ((excellent++))
     elif (( score >= 80 && score <= 89 )); then
         ((good++))
     elif (( score >= 70 && score <= 79 )); then
         ((medium++))
     elif (( score >= 60 && score <= 69 )); then
         ((pass++))
     elif (( score >= 0 && score <= 59 )); then
         ((fail++))
     else
         echo "The entered score is invalid, please enter an integer between 0-100."
     fi
 done

 # Show the number of people with grades
 echo "Grade Grade Statistics:"
 echo "Excellent: $excellent"
 echo "Good: $good"
 echo ": $medium"
 echo "pass: $pass"
 echo "Failed: $fail"

Notice:

if [[ "$score" =~ ^[qQ]$ ]]; then break fi

if ! [[ "$score" =~ ^[0-9]+$ ]]; then echo "The input is invalid, please enter an integer or q/Q to exit." continue fi

[[]]: It is a syntax structure used for conditional judgment in Bash, called a conditional expression, and is[ ]The enhanced version of (test command) supports more operators and functions, such as regular expression matching, string comparison, and number comparison.

=~Is the operator in Bash for regular expression matching. Used to check if the string matches the given regular expression pattern.[[ "$score" =~ ^[qQ]$ ]]Used to check variables$scoreWhether the value of the regular expression^[qQ]$match.

"$score"is a variable reference, where$scoreIt is a variable name, quote""Used to prevent problems caused by spaces or special characters in variable values.

^: Indicates the beginning of the matching string.

[qQ]: Indicates any character in the matching character set.

$: Indicates the end of the matching string.

+: means matching the previous character set once or more times.

if (( score >= 90 && score <= 100 ));

(( ... ))is an arithmetic context that is used to perform arithmetic operations and conditional judgments.

existifIn the statement,(( ... ))Used to determine whether an arithmetic condition is true. If the condition is true, the exit status code 0 is returned (indicating success); otherwise, the non-zero status code is returned.

2. Write a multi-process program in C language. The main process writes the current system time and number of people online to the file every 1 minute. The child process reads the file every 5 minutes and displays the file content on the screen.

untie:

#include <>
 #include <>
 #include <>
 #include <>
 #include <sys/>
 #include <sys/>
 #include <>
 #include <>

 //Get the current time and format it as a string
 void get_current_time(char *time_str) {
     time_t now;
     time(&now);
     struct tm *local = localtime(&now);
     strftime(time_str, 20, "%Y-%m-%d %H:%M:%S", local);
 }

 //Get online users
 int get_online_users() {
     FILE *fp = popen("who | wc -l", "r");
     if (fp == NULL) {
         perror("popen");
         return -1;
     }
     int count;
     fscanf(fp, "%d", &count);
     pclose(fp);
     return count;
 }

 //Main process function
 void parent_process(const char *filename) {
     FILE *file;
     char time_str[20];
     int online_users;

     while (1) {
         get_current_time(time_str);
         online_users = get_online_users();

         file = fopen(filename, "a");
         if (file == NULL) {
             perror("fopen");
             exit(EXIT_FAILURE);
         }
         fprintf(file, "Time: %s, Online Users: %d\n", time_str, online_users);
         fclose(file);

         sleep(60);// Write every 1 minute
     }
 }

 //Subprocess function
 void child_process(const char *filename) {
     FILE *file;
     char buffer[256];

     while (1) {
         file = fopen(filename, "r");
         if (file == NULL) {
             perror("fopen");
             exit(EXIT_FAILURE);
         }

         printf("Contents of %s:\n", filename);
         while (fgets(buffer, sizeof(buffer), file) != NULL) {
             printf("%s", buffer);
         }
         fclose(file);

         sleep(300);//Read every 5 minutes
     }
 }

 int main() {
     pid_t pid;
     const char *filename = "";

     pid = fork();
     if (pid == -1) {
         perror("fork");
         exit(EXIT_FAILURE);
     }

     if (pid == 0) {
         // Subprocess
         child_process(filename);
     } else {
         // Main process
         parent_process(filename);
     }

     return 0;
 }