linux:从标准输入读取命令并执行
#include<stdio.h> #include<stdlib.h> #include<sys/wait.h> #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); }

浙公网安备 33010602011771号