linux:从标准输入读取命令并执行

#include
#include
#include

#define MAXLINE 4096
int main(){
    char buf[MAXLINE];
    pid_t  pid;
    int  status;

    while(fgets(buf,MAXLINE,stdin) != NULL){
        if(buf[strlen(buf) - 1] == '\n')
            buf[strlen(buf) - 1] = 0;

        if((pid = fork()) < 0){
            printf("fork error\n");
        }
        else if(pid == 0){
            execlp(buf,buf,(char *)0);
            exit(127);
        }

        if((pid =  waitpid(pid,&status,0))  < 0)
            printf("waitpid error\n");
    }
    exit(0);
}

 

转载于:https://www.cnblogs.com/marvin007/archive/2013/04/06/3002398.html

你可能感兴趣的:(linux:从标准输入读取命令并执行)