- 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;
}
運行結果
歡迎留言交流。。。。