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"
效果如下