按下ls -l *.py并回車,Shell都為我們做了什么?
你是否想過,當你在 shell 上執行一個命令時,unix 的 shell 到底做了哪些事情?shell 是如何理解和解釋這些命令的?屏幕的背后都做些什么?比如說,當我們執行 ls -l *.py 的時候,shell 都做了哪些事情?了解了這些,可以更好的使用 Unix 類操作系統,今天我們就來一探究竟。
0、什么是 shell
shell 通常是一個命令行界面,它將操作系統的服務暴露給人類使用或其他程序。在 shell 啟動后,shell 通常會通過顯示提示來等待用戶的輸入。下圖描述了基本的 UNIX 和 Windows shell 提示。
所以 shell 會提示用戶輸入命令。現在是用戶輸入命令的時候了。那么 shell 是如何獲取用戶輸入的命令并進行解釋的呢?為了理解這一點,讓我們將它們分為 4 個步驟,分別是:
- 獲取并解析用戶輸入
- 識別命令及命令的參數
- 查找命令
- 執行命令
現在詳細展開:
1、獲取并解析用戶輸入
比如說,在 shell 上輸入了 ls -l *.py 并回車,shell 內部會調用一個叫 getline()「聲明在#include 中,下同」 的函數來讀取用戶輸入的命令,用戶輸入的命令字符串作為標準輸入流,一旦按下回車,表示一行結束,getline() 就會將輸入的字符串存儲到緩沖區中。
- ssize_t getline(char **restrict lineptr, size_t *restrict n, FILE *restrict stream);
函數參數說明:
- lineptr: 緩沖區
- n: 緩沖區大小
- stream: 流,這里就是標準輸入流
現在讓我們看一下代碼:
- char *input_buffer;
- size_t b_size;
- b_size = 32; // size of the buffer
- input_buffer = malloc(sizeof(char) * b_size); // the buffer to store the user input
- getline(&input_buffer, &b_size, stdin); // gets the line and stores it in input_buffer
一旦用戶按下回車,就會調用 getline() ,將用戶輸入的字符串或命令將存儲在 input_buffer 中。所以現在 shell 已經獲取了用戶輸入,那么下一步是什么?
2、識別命令及命令的參數
現在 shell 已經知道你輸入了字符串是 'ls -l *.py' 但是,還需要知道這里面哪個是命令,哪個是命令的參數,誰來做這個事情呢?那就是函數 strtok()「#include 」。
strtok() 將一個字符串標記為分隔符,在這個例子中分隔符是一個空格。所以一個空格告訴 strtok() 它是一個詞的結尾。因此 input_buffer 中的第一個標記或單詞是命令 (ls),其余的單詞或標記(-l 和 *.py)是命令的參數。因此,一旦 shell 標記了字符串,它就會將它們存儲在一個變量中,以便以后使用。
- char *strtok(char *restrict str, const char *restrict delim);
參數說明:
- str: 要標記的字符串
- delim: 分隔符
函數 strtok() 接受字符串和分隔符作為參數,返回一個指向標記字符串的指針。具體的執行代碼如下所示:
- char *input_buffer, *args, *delim_args, *command_argv[50];
- int i;
- i = 0;
- delim_args = " \t\r\n\v\f"; // the delimeters
- args = strtok(input_buffer, delim_args); // stores the token inside args
- while (args)
- {
- command_argv[i] = args; // stores the token in command_argv
- args = strtok(NULL, delim_args);
- i++;
- }
- command_argv[i] = NULL; // sets the last entity of command_argv to NULL
command_argv[i] = NULL; // sets the last entity of command_argv to NULL
command_argv 保存了命令字符串,其內容如下:
- command_argv[0] = "ls"
- command_argv[1] = "-l"
- command_argv[2] = "*.py"
- command_argv[3] = NULL
好了,command_argv[0] 是命令,其他的都是它的參數,最后一個是 NULL,表示命令的結束。命令字符串已經拆解完畢了,下一步就是查找命令。
3、查找命令
第二步已經知道,用戶要執行的命令就是 ls,那么去哪里查找這個命令呢?shell 回去環境變量 PATH 中去查找,PATH 這個環境變量就是存儲可執行命令的位置的。
不過,一個 PATH 存儲的路徑可不止一個:
如何在這么多路徑中高效的查找到 ls 命令呢?這就需要 access() 「#include 」 函數:
- int access(const char *pathname, int mode);
參數及返回值說明:
- pathname: 文件/可執行文件的路徑
- mode: 模式,我們使用 X_OK 來檢查文件是否存在
- 返回值:如果文件存在,返回 0,否則返回 -1
- {
- char *path_buff, *path_dup, *paths, *path_env_name, *path[50];
- int i;
- i = 0;
- path_env_name = "PATH";
- path_buff = getenv(path_env_name); /* get the variable of PATH environment */
- path_dup = _strdup(path_buff); /* this function is found below */
- paths = strtok(path_dup, ":"); /* tokenizes it */
- while (paths)
- {
- path[i] = paths;
- paths = strtok(NULL, ":");
- i++;
- }
- path[i] = NULL; /* terminates it with NULL */
- }
- /**
- * _strdup - duplicates a string
- * @from: the string to be duplicated
- *
- * Return: ponter to the duplicated string
- */
- char *_strdup(char *from)
- {
- int i, len;
- char *dup_str;
- len = _strlen(from) + 1;
- dup_str = malloc(sizeof(int) * len);
- i = 0;
- while (*(from + i) != '\0')
- {
- *(dup_str + i) = *(from + i);
- i++;
- }
- *(dup_str + i) = '\0';
- return (dup_str);
- }
上面代碼中的 path 數組存儲所有 PATH 位置并且以 NULL 終止。因此,可以將每個 PATH 位置與命令連接起來,并使用 access() 函數執行存在性檢查:
- {
- char *command_file, *command_path, *path[50];
- int i;
- i = 0;
- command_path = malloc(sizeof(char) * 50);
- while (path[i] != NULL)
- {
- _strcat(path[i], command_file, command_path); /* this function is found below */
- stat_f = access(command_path, X_OK); /* and checks if it exists */
- if (stat_f == 0)
- return (command_path); /* returns the concatenated string if found */
- i++;
- }
- return NULL; /* otherwise returns NULL */
- }
- /**
- * _strcat - concatenates two strings and saves it to a blank string
- * @path: the path string
- * @command: the command
- * @command_path: the string to store the concatenation
- *
- * Return: Always void
- */
- void _strcat(char *path, char *command, char *command_path)
- {
- int i, j;
- i = 0;
- j = 0;
- while (*(path + i) != '\0')
- {
- *(command_path + i) = *(path + i);
- i++;
- }
- *(command_path + i) = '/';
- i++;
- while (*(command + j) != '\0')
- {
- *(command_path + i) = *(command + j);
- i++;
- j++;
- }
- *(command_path + i) = '\0';
- }
一旦找到命令,就會返回命令的完整路徑,否則就返回 NULL,然后 shell 會顯示命令不存在的錯誤。
現在假如命令找到了,然后呢?
4、執行命令
命令一旦找到,就是執行它的時候了,問題是怎么執行呢?
執行命令,需要借助函數 execve()「#include 」中:
- int execve(const char *pathname, char *const argv[],
- char *const envp[]);
參數說明:
- pathname: 可執行文件的完整路徑
- argv: 命令的參數
- envp: 環境變量列表
execve() 會執行找到的命令,返回一個整數表示執行結果。
但是現在如果 shell 只是運行 execve(),就會出現問題。execve() 調用后不返回標準輸出的信息,這是不好的,因為用戶需要執行的結果。所以為了解決這個問題,shell 在子進程中執行命令。因此,一旦在子進程內執行完成,父進程就會收到信號并且程序流繼續。所以為了執行命令,shell 使用 fork() 創建了一個子進程。(fork 聲明在#include 中)
- pid_t fork(void);
fork() 通過復制調用進程來創建一個新進程。新進程稱為子進程。調用進程稱為父進程。fork() 在父進程中返回子進程的進程 ID,在子進程中返回 0:
- {
- char *command, *command_argv[50], **env;
- pid_t child_pid;
- int status;
- get_each_command_argv(command_argv, input_buffer); /* this function is found below */
- child_pid = fork();
- if (child_pid == -1)
- return (0);
- if (child_pid == 0)
- {
- if (execve(command, command_argv, env) == -1)
- return (0);
- }
- else
- wait(&status);
- }
- /**
- * get_each_command_argv - stores all the arguments \
- * of the input command to the list
- * @command_argv: the command argument list
- * @input_buffer: the input buffer
- *
- * Return: Always void
- */
- void get_each_command_argv(char **command_argv, char *input_buffer)
- {
- char *args, *delim_args;
- int i;
- delim_args = " \t\r\n\v\f";
- args = strtok(input_buffer, delim_args);
- i = 0;
- while (args)
- {
- command_argv[i] = args;
- args = strtok(NULL, delim_args);
- i++;
- }
- command_argv[i] = NULL;
- }
shell 使用 wait()(函數聲明在#include ) 在程序流繼續之前等待子進程的狀態變化,并再次為用戶顯示提示。
- pid_t wait(int *wstatus);
wstatus:是一個指向整數的指針,可以用來標識子進程是如何終止的。
shell 在子進程內執行命令,然后 wait() 等待子進程完成。所以這樣用戶就可以得到命令的結果,并且可以在 shell 顯示其提示后輸入另一個命令。
所以最后當子進程完成時顯示 ls -l *.py 的結果,并且由于我們已經等待子進程結束,這意味著給出了命令的結果。所以現在 shell 可以再次顯示它的提示以再次等待用戶輸入。這將繼續循環,除非用戶鍵入 exit。