标签:else 失败 实现 details 参数 ret csdn 指针 tail
http://blog.csdn.net/lishuhuakai/article/details/11928055
#include <stdio.h> #include <unistd.h> #include <wait.h> #define MAXLINE 80 void setup (char inputBuffer[], char *argv[]) { int i, j; char *p; i = 0; for (p = inputBuffer; ;p++)/*将字符命令一段一段拆分开来,如输入ls -l,则argv[0]= "ls",argv[1]="-l",argv[2]=NULL*/ { argv[i++] = p; while (*p != ‘ ‘ && *p != ‘\0‘) p++; if (*p == ‘\0‘) { break; } *p = ‘\0‘; } argv[i] = NULL;/*最后一个参数须用空指针NULL作结束*/ execvp (argv[0], argv);/*执行命令,argv[0]放着执行的命令,其余的argv放着参数*/ } int main() { char inputBuffer[MAXLINE]; char *argv[MAXLINE / 2 - 1]; while (1) { printf ("COMMAND->"); gets (inputBuffer);/*输入命令*/ setup (inputBuffer, argv); printf ("扑街!"); } return 0; }
#include <stdio.h> #include <unistd.h> //#define SIZE 20 #define MAXLINE 80 char *p; void setup (char inputBuffer[], char *argv[]) { int i, j; i = 0; for (p = inputBuffer; ;p++)/*一个一个地将输入字符分开*/ { argv[i++] = p; while (*p != ‘ ‘ && *p != ‘\0‘) p++; if (*p == ‘\0‘) { break; } *p = ‘\0‘; } argv[i] = NULL; pid_t pid pid = fork();/*新建一个子进程*/ if (pid == 0)/*对于子进程,执行输入的命令*/ { execvp (argv[0], argv); printf ("command not found\n");/*如果execvp执行失败的话,会返回-1,也就是这句话会被执行*/ } else if( pid > 0 )/*对于父进程,等待*/ { wait(NULL);/*父进程等待子进程执行完*/ } else /*否则的话,就出错了*/ { printf ("fork error\n"); } } int main() { char inputBuffer[MAXLINE]; char *argv[MAXLINE / 2 - 1]; while (1) { printf ("COMMAND->"); gets (inputBuffer); /*关于scanf和gets,scanf对于输入的字符遇到空格或回车就结束了,而gets对于输入的空格也接受*/ setup (inputBuffer, argv); } return 0; }
标签:else 失败 实现 details 参数 ret csdn 指针 tail
原文地址:http://www.cnblogs.com/qlky/p/6890346.html