• 进程和程序:编写命令解释器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 != '
    ')
    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
    ",
    53                     exitstatus>>8, exitstatus&0377);
    54     }
    55 }
    56 
    57 char *makestring(char *buf)
    58 {
    59     char *cp;
    60     buf[strlen(buf)-1] = '';
    61     cp = malloc(strlen(buf)+1);
    62     if (cp == NULL)
    63     {
    64         fprintf(stderr, "no memory
    ");
    65         exit(1);
    66     }
    67     strcpy(cp, buf);
    68     return cp;
    69 }
  • 相关阅读:
    Flask17 Flask_Script插件的使用
    python导入模块被加横线
    MYSQL中replace into的用法
    flask通过nginx代理后base_url拿不到正确的url_scheme2016-04-14 12:31
    nginx+Gunicorn部署你的Flask项目
    浅谈flask源码之请求过程
    浅谈Flask 中的 线程局部变量 request 原理
    flask基础之jijia2模板语言进阶(三)
    Redis在windows下安装过程
    如何打开Intellij IDEA的代码提示功能/联想/自动联想
  • 原文地址:https://www.cnblogs.com/bournet/p/4013726.html
Copyright © 2020-2023  润新知