您的位置:首页 > 运维架构 > Shell

shell-like program(shell程序的基本实施部分)

2015-08-16 10:09 501 查看
直接上代码:

#include "apue.h"
#include <sys/wait.h>

int main(void)
{
char    buf[MAXLINE]; /* form apue.h  4096 */
pid_t   pid;
int     status;

printf("%% "); /* print promt (printf requires %% to print %) */
while (fgets(buf, MAXLINE, stdin) != NULL) {
if (buf[strlen(buf) - 1] == '\n') {
buf[strlen(buf) - 1] = 0; /* replace newline while null */
}

if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) {
execlp(buf, buf, (char *)0);
err_ret("couldn't execute: %s", buf);
exit(127);
}

/* parent */
if ((pid = waitpid(pid, &status, 0)) < 0) {
err_sys("waitpid error");
}
printf("%% ");
}

exit(0);
}


很多时候不喜欢csdn这种代码显示,再贴上vim的



测试:



这个小程序的功能限制就是不能给命令传入参数,比如我们不能指定目录名给list,我们只能在当前工作目录中运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: