Unix-Linux編程實踐教程——shell(1)

//
// Created by Jimmy on 3/19/20.
//
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <zconf.h>

#define MAXARGS 20
#define ARGLEN 100

char *makestring(char *buf)
{
    char *cp;
    buf[strlen(buf) - 1] = '\0';
    cp =  (char *) malloc(strlen(buf) + 1);
    if(cp == NULL){
        fprintf(stderr, "no memory\n");
        exit(1);
    }
    strcpy(cp, buf);
    return cp;
}

void execute(char * arglist[])
{
    execvp(arglist[0], arglist);
    perror("execvp failed");
}

int main()
{
    char *arglist[MAXARGS + 1];
    int numargs = 0;
    char argbuf[ARGLEN];

    while(numargs < MAXARGS){
        if(fgets(argbuf, ARGLEN, stdin) && *argbuf != '\n')
            arglist[numargs++] = makestring(argbuf);
        else{
            if(numargs > 0){
                arglist[numargs] = NULL;
                execute(arglist);
                fprintf(stdout, "endding\n");
                numargs = 0;
            }
        }
    }
    return 0;
}

第二個版本主要是加了forkwait

定義函數:pid_t wait (int * status);

函數說明:wait()會暫時停止目前進程的執行, 直到有信號來到或子進程結束. 如果在調用wait()時子進程已經結束, 則wait()會立即返回子進程結束狀態值. 子進程的結束狀態值會由參數status 返回, 而子進程的進程號也會一快返回. 如果不在意結束狀態值, 則參數status 可以設成NULL. 子進程的結束狀態值請參考waitpid().

//
// Created by Jimmy on 3/19/20.
//
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <zconf.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAXARGS 20
#define ARGLEN 100

char *makestring(char *buf)
{
    char *cp;
    buf[strlen(buf) - 1] = '\0';
    cp =  (char *) malloc(strlen(buf) + 1);
    if(cp == NULL){
        fprintf(stderr, "no memory\n");
        exit(1);
    }
    strcpy(cp, buf);
    return cp;
}

void execute(char * arglist[])
{
    int pid, exitstatus;
    pid = fork();
    switch(pid){
        case -1:
            perror("fork failed");
            exit(1);
        case 0:
            printf("child progress");
            execvp(arglist[0], arglist);
            perror("execvp failed");
            exit(1);
        default:
            printf("parent progress ");
            while (wait(&exitstatus) != pid){}
            printf("child exited with status %d, %d\n", exitstatus>>8, exitstatus&0377);

    }

}

int main()
{
    char *arglist[MAXARGS + 1];
    int numargs = 0;
    char argbuf[ARGLEN];

    while(numargs < MAXARGS){
        printf("Arg[%d]?", numargs);
        if(fgets(argbuf, ARGLEN, stdin) && *argbuf != '\n')
            arglist[numargs++] = makestring(argbuf);
        else{
            if(numargs > 0){
                arglist[numargs] = NULL;
                execute(arglist);
                numargs = 0;
            }
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章