一个简单地Shell-like 的实现
2015-07-27 09:31
381 查看
下面的一个程序是shell的简单实现,虽然简单,但是原理是相同的。请仔细体会。
//shell-like function
#include "apue.h"
#include <sys/wait.h>
int main(int argc,
char *argv[])
{
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("err\n");
}
else
if (pid == 0)
/* child */
{
execlp(buf, buf, (char *)0);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status,
0)) < 0)
{
printf("error\n");
}
printf("%% ");
}
return(0);
}
//shell-like function
#include "apue.h"
#include <sys/wait.h>
int main(int argc,
char *argv[])
{
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("err\n");
}
else
if (pid == 0)
/* child */
{
execlp(buf, buf, (char *)0);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status,
0)) < 0)
{
printf("error\n");
}
printf("%% ");
}
return(0);
}
相关文章推荐
- 应用领航:盘点那些年我们一起追过的OS
- Linux VS Unix:Linux欲一统天下 Unix不死
- 无奇不有!盘点各国自己开发的操作系统
- Linux C函数参考手册(PDF版)
- Lua教程(十七):C API简介
- 可自定义oem的萝卜家园 Ghost XP 新春装机版 V200801 下载
- C#实现判断操作系统是否为Win8以上版本
- C#实现打造气泡屏幕保护效果
- C/C++数据对齐详细解析
- C 语言基础教程(我的C之旅开始了)[三]
- C++中的extern “C”用法详解
- C 语言基础教程(我的C之旅开始了)[七]
- C字符串操作函数实现方法小结
- C/C++ 宏详细解析
- C/C++实现对STORM运行信息查看及控制的方法
- 用C#生成不重复的随机数的代码
- 看UNIX高手的10个习惯第1/2页
- Linux操作系统添加新硬盘方法
- 在c和c++中实现函数回调