- mysys.c: 实现函数mysys,用于执行一个系统命令,要求如下
- mysys的功能与系统函数system相同,要求用进程管理相关系统调用自己实现一遍
- 使用fork/exec/wait系统调用实现mysys
- 不能通过调用系统函数system实现mysys
测试程序
#include <stdio.h>
int main()
{
printf("--------------------------------------------------\n");
system("echo HELLO WORLD");
printf("--------------------------------------------------\n");
system("ls /");
printf("--------------------------------------------------\n");
return 0;
}
测试程序的输出结果
--------------------------------------------------
HELLO WORLD
--------------------------------------------------
bin core home lib mnt root snap tmp vmlinuz
boot dev initrd.img lost+found opt run srv usr vmlinuz.old
cdrom etc initrd.img.old media proc sbin sys var
--------------------------------------------------
实现思路:在mysys
函数中创建一个新进程,调用execl函数执行命令
代码实现
#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
#include<sys/types.h>
#include<stdlib.h>
void mysys(char *str){
pid_t pid;
if(str==NULL){
printf("Error:wrong shell string!\n");
exit(0);
}
pid=fork();
if(pid==0)
execl("/bin/sh","sh","-c",str,NULL);
wait(NULL);
}
int main(){
printf("---------------------------------\n");
mysys("echo a b c d");
printf("---------------------------------\n");
mysys("ls /");
printf("---------------------------------\n");
return 0;
}
运行结果
欢迎留言交流。。。。