69,373
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include "csapp.h"
#define null NULL
int mysystem(char *command)
{
int status=0;
int argc, i, j;
int length=0;
while (command[length] != 0) length++;
//assumes the number of arguments is 20 at most
char **argv=(char **)malloc((23)*sizeof(char *));
argv[0]=(char *)malloc(3*sizeof(char));
argv[0][0]='s';
argv[0][1]='h';
argv[0][2]=0;
argv[1]=(char *)malloc(3*sizeof(char));
argv[1][0]='-';
argv[1][1]='c';
argv[1][2]=0;
//load arguments from the command string
argc=1;
i=0;
while (command[i] != 0)
{
if ((command[i] != ' ') && (command[i] != '\n'))
{
argc++;
j=0;
argv[argc]=(char *)malloc(length*sizeof(char)); //length is the upper boundary
while ((command[i] != ' ') && (command[i] != '\n') && (command[i] != 0))
{
argv[argc][j]=command[i];
i++;
j++;
}
argv[argc][j]=0;
}
if (command[i] == 0) break;
while ((command[i] == ' ') || (command[i] == '\n')) i++;
}
argv[argc+1]=null;
i=0;
while (argv[i] != null)
{
j=0;
while (argv[i][j] != 0)
{
printf("%c", argv[i][j]);
j++;
}
printf("\n");
i++;
}
if (Fork() == 0)
{
execve("/bin/sh", argv, null);
}
waitpid(-1, &status, 0);
if (WIFEXITED(status))
{
return WEXITSTATUS(status);
}
else
{
return status;
}
}
void main()
{
char *command=(char *)malloc(200*sizeof(char));
int i;
for (i=0; i < 200; i++)
{
scanf("%c", &command[i]);
if (command[i] == '\n') break;
}
command[i+1]=0;
printf("%d\n", mysystem(command));
//one test command : ls
}