龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

用标准C实现shell功能

时间:2009-12-22 15:42来源:未知 作者:admin 点击:
分享到:
#include #include #include #include #include #include #define SHELL_NAME "sh1" #define PROMPT_ENVIRONMENT_VARIABLE "PROMPT" char *prompt; int main(int argc, char **argv) { char cmd[80]; int statval; /* Determine prompt value. */ if ((prompt

  #include

  

#include

  

#include

  

#include

  

#include

  

#include

  

  

#define SHELL_NAME "sh1"

  

#define PROMPT_ENVIRONMENT_VARIABLE "PROMPT"

  

  

char *prompt;

  

  

int main(int argc, char **argv)

  

{

  

char cmd[80];

  

int statval;

  

  

/* Determine prompt value. */

  

if ((prompt = getenv(PROMPT_ENVIRONMENT_VARIABLE)) == NULL)

  

prompt = SHELL_NAME ":";

  

  

/* Process commands until exit, or death by signal. */

  

while (1)

  

{

  

/* Prompt and read a command. */

  

printf(prompt);

  

gets(cmd);

  

  

/* Process built-in commands. */

  

if(strcasecmp(cmd, "exit") == 0)

  

break;

  

  

/* Process non-built-in commands. */

  

if(fork() == 0) {

  

execlp(cmd, cmd, NULL);

  

fprintf(stderr, "%s: Exec %s failed: %s

", argv[0],

  

cmd, strerror(errno));

  

exit(1);

  

}

  

  

wait(&statval);

  

if(WIFEXITED(statval))

  

{

  

if(WEXITSTATUS(statval))

  

{

  

fprintf(stderr,

  

"%s: child exited with status %d.

",

  

argv[0], WEXITSTATUS(statval));

  

}

  

} else {

  

fprintf(stderr, "%s: child died uneXPectedly.

",

  

argv[0]);

  

}

  

}

  

}

  

精彩图集

赞助商链接