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

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 <stdlib.h>
 3 #include <signal.h>
 4 #include <string.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 
16     numargs = 0;
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 execute(char *arglist[])
36 {
37     int pid, exitstatus;
38 
39     pid = fork();
40     switch(pid)
41     {
42         case -1:
43             perror("fork");
44             exit(1);
45         case 0:
46             execvp(arglist[0], arglist);
47             perror("execvp failed");
48             exit(1);
49         default:
50             while (wait(&exitstatus) != pid)
51                 ;
52             printf("child exited with status %d, %d\n",
53                     exitstatus>>8, exitstatus&0377);
54     }
55 }
56 
57 char *makestring(char *buf)
58 {
59     char *cp;
60     buf[strlen(buf)-1] = '\0';
61     cp = malloc(strlen(buf)+1);
62     if (cp == NULL)
63     {
64         fprintf(stderr, "no memory\n");
65         exit(1);
66     }
67     strcpy(cp, buf);
68     return cp;
69 }

 

转载于:https://www.cnblogs.com/bournet/p/4013726.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值