标签:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<sys/wait.h> 5 #include<sys/types.h> 6 #include<unistd.h> 7 #define MAXLINE 4096 8 9 int main(void) 10 { 11 char buf[MAXLINE]; 12 pid_t pid; 13 int status; 14 15 printf("%% "); 16 17 while(fgets(buf,MAXLINE,stdin)!=NULL) 18 { 19 if(buf[strlen(buf)-1]==‘\n‘) 20 buf[strlen(buf)-1]=‘\0‘;
21 22 23 if((pid=fork())<0) 24 { 25 printf("fork error\n"); 26 } 27 else if(pid==0) 28 { 29 execlp(buf, buf,(char *)0);//执行命令行参数 30 printf("couldn‘t execute:%s", buf); 31 exit(127); 32 } 33 else 34 { 35 if((pid=waitpid(pid,&status,0))<0)//等待执行结束 36 printf("waitpid error\n");
printf("%% ");
37 }
38
39 }
40 exit(0);
41 }
程序运行结果
1 % ls 2 4 4.c 9 9.c pthread pthread.c 3 % dgdfg 4 couldn‘t execute:dgdfg 5 % ls 6 4 4.c 9 9.c pthread pthread.c 7 % date 8 星期日 二月 14 20:41:52 CST 2016
标签:
原文地址:http://www.cnblogs.com/wireless-dragon/p/5189570.html