相关代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
char cmd[
128];
while(
1)
{
printf(
"[LJH@My_host MyShell]$ ");
fflush(
stdout);
ssize_t _s = read(
0,cmd,
sizeof(cmd)-
1);
if(_s >
0)
{
cmd[_s-
1]=
'\0';
}
else
{
perror(
"read");
exit(
1);
}
//ls -a -l -i
char *_argv[
32];
_argv[
0]= cmd;
int i =
1;
char *start = cmd;
while(*start)
{
if(
isspace(*start))
{
*start=
'\0';
start++;
_argv[i]=start;
i++;
continue;
}
start++;
}
_argv[i]=
NULL;
pid_t id = fork();
if(id<
0)
{
perror(
"fork");
}
else
if(id==
0)
{
//child
execvp(_argv[
0],_argv);
exit(
2);
}
else
{
//father
int status =
0;
pid_t ret=waitpid(id,&status,
0);
if(ret>
0 && WIFEXITED(status))
{
//printf("exit code:%d\n",WEXITSTATUS(status));
}
else
{
perror(
"wait");
}
}
}
}