#include <sys/wait.h>
#include <stdio.h>
const int MAXLINE=16;
int main(void){
char buf[MAXLINE];
pid_t pid;
int status;
printf("%% ");
while(fgets(buf,MAXLINE,stdin)!=NULL){
if(buf[strlen(buf)-1]=='\n')
buf[strlen(buf)-1]=0;
if((pid=fork())<0){
printf("fork error!\n");
}else if(pid==0){
execlp(buf,buf,(char*)0);
printf("couldn't execute: %s",buf);
exit(127);
#include <stdio.h>
const int MAXLINE=16;
int main(void){
char buf[MAXLINE];
pid_t pid;
int status;
printf("%% ");
while(fgets(buf,MAXLINE,stdin)!=NULL){
if(buf[strlen(buf)-1]=='\n')
buf[strlen(buf)-1]=0;
if((pid=fork())<0){
printf("fork error!\n");
}else if(pid==0){
execlp(buf,buf,(char*)0);
printf("couldn't execute: %s",buf);
exit(127);
}
if((pid==waitpid(pid,&status,0))<0){
printf("waitpid error");
}
printf("%% ");
}
exit(0);
}
gcc execlp.c
./a.out
程序运行,产生提示符:%,
输入 命令 ls等,就可以看到结果。
按CTRL+D退出。
本文介绍了一个简单的C语言程序,该程序通过使用execlp函数实现了基本的Shell功能。用户可以输入命令如ls,并由系统执行这些命令。文章提供了完整的源代码及运行说明。
601

被折叠的 条评论
为什么被折叠?



