| 订阅 | 在线投稿
分享
 
 
 

用标准C实现shell功能

来源:互联网网民  宽屏版  评论
2008-06-01 01:54:49

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/wait.h>

#include <string.h>

#include <errno.h>

#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\n", argv[0],

cmd, strerror(errno));

exit(1);

}

wait(&statval);

if(WIFEXITED(statval))

{

if(WEXITSTATUS(statval))

{

fprintf(stderr,

"%s: child exited with status %d.\n",

argv[0], WEXITSTATUS(statval));

}

} else {

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

argv[0]);

}

}

}

 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
  #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <string.h> #include <errno.h> #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\n", argv[0], cmd, strerror(errno)); exit(1); } wait(&statval); if(WIFEXITED(statval)) { if(WEXITSTATUS(statval)) { fprintf(stderr, "%s: child exited with status %d.\n", argv[0], WEXITSTATUS(statval)); } } else { fprintf(stderr, "%s: child died uneXPectedly.\n", argv[0]); } } }
󰈣󰈤
 
 
 
>>返回首页<<
 
 热帖排行
 
 
静静地坐在废墟上,四周的荒凉一望无际,忽然觉得,凄凉也很美
©2005- 王朝网络 版权所有