用C语言写一个自己的shell-Part Ⅱ--execute commands

news/2024/11/21 1:43:52/

Part Ⅱ–execute commands

Exec

This brings us to the exec family of functions. Namely, it has the following functions:

  • execl
  • execv
  • execle
  • execve
  • execlp
  • execvp

For our needs,we will use execvp whose signature looks like this

int execvp(const char *file, char *const argv[]);

execvp function indicates that,it accepts the name of a file,for which it will search for $PATH variable of the system and an array of arguments to be executed.

A few things to note about the execvp function:

  1. The first argument is the name of the command
  2. The second argument consists of the name of the command and the arguments passed to the command itself. It must also be terminated by NULL.
  3. It also swaps out the current process image with that of the command being executed, but more on that later.

execvp.c

#include <unistd.h>int main() {char *argv[] = {"ls","-l","-h","-a",NULL};execvp(argv[0],argv);return 0;
}

If you compile and execute the execvp.c, you will see an output similar to the following:

total 32K
drwxrwxr-x 2 marco marco 4.0K  3月  1 22:07 .
drwxrwxr-x 5 marco marco 4.0K  3月  1 22:04 ..
-rwxrwxr-x 1 marco marco  17K  3月  1 22:07 execvp
-rw-rw-r-- 1 marco marco  123  3月  1 22:07 execvp.c

Which is exactly the same if you manually executels -l -h -a

readline

https://tiswww.case.edu/php/chet/readline/rltop.html

With execvp function,we can perform commands in $PATH but how to accept the string of commands as stdin?

This brings us to the Readline Library.

#include <stdio.h>
#include <readline/readline.h>
char * readline (const char *prompt);

However,when I used this function,error occured.

Ubuntu that I used doesn’t have the library by default.Hence,the library need to be installed.

sudo apt-get install libreadline-dev

Meanwhile,we should add an another argument to link the library when compiling the File.c ,otherwise you may see an error like

“undefined reference to `readline’
collect2: error: ld returned 1 exit status”.

gcc File.c -o File -lreadline

And here’s the code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <readline/readline.h>
#include <sys/wait.h>char **get_input(char *);int main() {//in C,ptr can be used as array.char **command;char *input;pid_t child_pid;int stat_loc;while(1) {input = readline("mysh> ");//with "mysh> " to be a prompt,the function reads a line of input.command = get_input(input);if(!command[0]) {//empty commandsfree(input);free(command);continue;}child_pid = fork();if(child_pid == 0) {//child processexecvp(command[0],command);} else {waitpid(child_pid, &stat_loc, WUNTRACED);}free(input);free(command);}return 0;
}char **get_input(char *input) {char **command = malloc(8 * sizeof(char *));char *separator = " ";char *parsed;int index = 0;parsed = strtok(input, separator);while (parsed != NULL) {command[index] = parsed;index++;parsed = strtok(NULL, separator);}command[index] = NULL;return command;
}

Let’s test it.

在这里插入图片描述

However,the exec family of function can’t perform built-in commands like cd.

在这里插入图片描述

The code with weak robustness should be revised to be more robust and stronger.

  1. Dynamic memory allocation - in char ** get_input(char *input);

    The command variable only malloc 8 sizeof(char *).It’s limited,

    so you will see the following error:

在这里插入图片描述

To handle the error,commandshould malloc dynamic memories.

  1. fork failed - If the OS runs out of memory or reaches the maxmum number of allowed processes,a child process will not be created.We add the following segment to our code:

    		if(child_pid < 0) {perror(command[0]);exit(1);}
    
  2. exev failed - the exev function may fail.We modify the following block to our code:

    			//child processif (execvp(command[0], command) < 0) {perror(command[0]);exit(1);}
    

The revised code is here,written by chatGPT.The AI is amazing!!!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <readline/readline.h>
#include <sys/wait.h>char **split_input(char *);int main() {//in C,ptr can be used as array.char **command;char *input;pid_t child_pid;int stat_loc;while(1) {input = readline("mysh> ");//with "mysh> " to be a prompt,the function reads a line of input.command = split_input(input);if(!command[0]) {//empty commandsfree(input);free(command);continue;}//fork failed.child_pid = fork();if(child_pid < 0) {perror(command[0]);exit(1);}if(child_pid == 0) {//child processif (execvp(command[0], command) < 0) {perror(command[0]);exit(1);}} else {waitpid(child_pid, &stat_loc, WUNTRACED);}free(input);free(command);}return 0;
}
char **split_input(char *input) {int capacity = 10;char **command = malloc(capacity * sizeof(char *));if (command == NULL) {fprintf(stderr, "Error: memory allocation failed\n");exit(EXIT_FAILURE);}char *token = strtok(input, " ");int i = 0;while (token != NULL) {if (i == capacity - 1) {  // resize the array if it is fullcapacity *= 2;char **new_command = realloc(command, capacity * sizeof(char *));if (new_command == NULL) {fprintf(stderr, "Error: memory allocation failed\n");exit(EXIT_FAILURE);}command = new_command;}command[i] = malloc((strlen(token) + 1) * sizeof(char));if (command[i] == NULL) {fprintf(stderr, "Error: memory allocation failed\n");exit(EXIT_FAILURE);}strcpy(command[i], token);token = strtok(NULL, " ");i++;}command[i] = NULL;  // terminate the array with NULLreturn command;
}

http://www.ppmy.cn/news/29430.html

相关文章

W25Q256被写保护如何修改

W25Q256被写保护如何修改1、 W25Q256数据读不到1.1 打印的寄存器的值1.2 可能原因1.3 解决办法1.4 用到的函数1、 W25Q256数据读不到 能够正确的读到ID&#xff0c;但是读到的数据不正确 1.1 打印的寄存器的值 0x2 BUSY &#xff1a;只读&#xff0c; 指令正在执行 WEL (1) &…

【ArcGIS Pro二次开发】(11):面要素的一键拓扑

在工作中&#xff0c;经常需要对要素进行拓扑检查。 在ArcGIS Pro中正常的工作流程是在数据库中【新建要素数据集——新建拓扑——将要素加入拓扑——添加规则——验证】&#xff0c;工作流程不算短&#xff0c;操作起来比较繁琐。 下面以一个例子演示如何在ArcGIS Pro SDK二次…

Spark开发实战-主播打赏排行榜统计

&#xff08;一&#xff09;需求分析 计算每个大区当天金币收入排名前N的主播 背景&#xff1a; 我们有一款直播APP&#xff0c;已经在很多国家上线并运营了一段时间&#xff0c;产品经理希望开发一个功能&#xff0c;计算前N主播排行榜&#xff0c;按天更新排名信息&#xf…

Nodejs模块化

1.模块化 1.1.模块化的基本概念 模块化是指解决一个复杂问题时&#xff0c;自顶向下逐层把系统划分为若干模块的过程。对于整个系统而言&#xff0c;模块是可组合、分解和更换的单元。 1.2 编程中的模块化 编程领域的模块化就是把一个大文件拆成独立并相互依赖的多个小模块…

【2023】某python语言程序设计跟学第二周内容

本文说明&#xff1a; 案例内容为北理工python语言程序设计课程&#xff0c;如有不妥请联系&#xff01; 目录蟒蛇绘制案例&#xff1a;执行结果&#xff1a;代码分析&#xff1a;举一反三&#xff1a;绘制一个五角星图案执行结果&#xff1a;turtle库根据案例简单说明&#xf…

大话数据结构-普里姆算法(Prim)和克鲁斯卡尔算法(Kruskal)

5 最小生成树 构造连通网的最小代价生成树称为最小生成树&#xff0c;即Minimum Cost Spanning Tree&#xff0c;最小生成树通常是基于无向网/有向网构造的。 找连通网的最小生成树&#xff0c;经典的有两种算法&#xff0c;普里姆算法和克鲁斯卡尔算法。 5.1 普里姆&#xff…

计算机网络安全基础知识2:http超文本传输协议,请求request消息的get和post,响应response消息的格式,响应状态码

计算机网络安全基础知识&#xff1a; 2022找工作是学历、能力和运气的超强结合体&#xff0c;遇到寒冬&#xff0c;大厂不招人&#xff0c;可能很多算法学生都得去找开发&#xff0c;测开 测开的话&#xff0c;你就得学数据库&#xff0c;sql&#xff0c;oracle&#xff0c;尤…

vue2 @hook 的解析与妙用

目录前言几种用法用法一 将放在多个生命周期的逻辑&#xff0c;统一到一个生命周期中用法二 监听子组件生命周期运行的情况运用场景场景一 许多时候&#xff0c;我们不得不在不同的生命周期中执行某些逻辑&#xff0c;并且这些逻辑会用到一些通用的变量&#xff0c;这些通用变量…