1. 程式人生 > >簡單shell實現

簡單shell實現

.net 執行 buffer 參數 tdi efi command 分開 結束

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; }

簡單shell實現