模拟shell进程

1.        用fork( )创建一个进程,再调用execl( ),用新的程序(命令)替换该子进程的内容,利用wait( )来控制进程执行顺序。例如模拟一个shell程序,可以是最简化版的shell模拟,即创建一个子进程运行一个固定的shell命令,也可以是从终端获取用户输入的shell命令,创建子进程执行这个shell命令,直到用户终止shell的运行。代码要加注释


模拟了一个shell程序,一直输入命令,直到用户输入exit就结束这个子进程

 

#include<stdio.h>

#include<unistd.h>

#include<sys/types.h>

#include<sys/wait.h>

int main(){

   int son_pid;   //fork后返回的id

   int error_num; 

   printf("\n");

   printf("simulate shell:\n\n");   //模拟shell

   while ((son_pid = fork()) == -1); //fork()创建进程

   if(son_pid == 0){    //子进程

          error_num = execl("/root/exec",(char *)0);  //子进程去调用别的程序(这里是exec),之后不返回本程序

          if(error_num == -1)  //调用exec程序不成功,就会返回-1,输出错误

              printf("what the hell!!! itis over \n");

   }else {

       wait(0);   //父进程被挂起,需等待子进程运行结束才运行

       printf("\nSon over. Now this is parent\n\n");

    }

   return 0;

}


 

下面是调用的程序exec的代码

#include<stdio.h>

#include<stdlib.h>

int main(){

   system("./exec.sh");   用system()函数调用shell脚本exec.sh

   printf("\n");

   return 0;

}


 

下面是shell脚本exec.sh

echo -e "Son order: _\b\c"   //模拟shell程序,这里是类似shell提示符

read a   //读入命令

while [ $a != "exit" ]   //循环体(while[] do …done),读入的命令如果是exit则退出循环

do

$a

echo '' //空一行

echo -e "Son order: _\b\c "

read a

done

echo  "exit"



效果如下



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值