码迷,mamicode.com
首页 > 其他好文 > 详细

进程和程序:编写命令解释器sh(一)

时间:2014-10-09 19:07:17      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   文件   sp   div   

shell是一个管理进程和运行程序的程序,所有常用的shell有三个主要功能。

(1)运行程序

grep、date、ls、echo和mail都是一些普通程序,用C编写,并被编译成机器语言。shell将它们载入内存并运行它们。很多人把shell看作一个程序启动器。

(2)管理输入和输出

使用<、>和|符号可以将输入输出重定向。这样就可以告诉shell将进程的输入和输出连接到一个文件或是其他的进程。

(3)编程

shell同时也是带有变量和流程控制的编程语言。

一个shell的主循环主要执行下面的4步

(1)用户键入a.out;

(2)shell建立一个新的进程来运行这个程序;

(3)shell将程序从磁盘载入;

(4)程序在它的进程中运行直到结束。

 1 #include <stdio.h>
 2 #include <signal.h>
 3 #include <string.h>
 4 #include <stdlib.h>
 5 
 6 #define MAXARGS 20
 7 #define ARGLEN 100
 8 
 9 int main()
10 {
11     char    *arglist[MAXARGS+1];
12     int     numargs;
13     char    argbuf[ARGLEN];
14     char    *makestring();
15     numargs = 0;
16 
17     while (numargs < MAXARGS)
18     {
19         printf("Arg[%d]? ", numargs);
20         if (fgets(argbuf, ARGLEN, stdin) && *argbuf != \n)
21             arglist[numargs++] = makestring(argbuf);
22         else
23         {
24             if (numargs > 0)
25             {
26                 arglist[numargs] = NULL;
27                 execute(arglist);
28                 numargs = 0;
29             }
30         }
31     }
32     return 0;
33 }
34 
35 int execute(char *arglist[])
36 {
37     execvp(arglist[0], arglist);
38     perror("execvp failed");
39     exit(1);
40 }
41 
42 char *makestring(char *buf)
43 {
44     char *cp;
45     buf[strlen(buf)-1] = \0;
46     cp = malloc(strlen(buf)+1);
47     if (cp == NULL)
48     {
49         fprintf(stderr, "no memory\n");
50         exit(1);
51     }
52     strcpy(cp, buf);
53     return cp;
54 }

 

进程和程序:编写命令解释器sh(一)

标签:style   blog   color   io   使用   ar   文件   sp   div   

原文地址:http://www.cnblogs.com/bournet/p/4013726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!