【发布时间】:2016-05-08 17:59:35
【问题描述】:
所以我正在从一个包含一行命令的文件中读取命令,每个命令都由一个分号分隔符分隔。我将这些命令放入一个数组中,我基本上是一个一个地执行它们。一切正常,直到我有一个带有选项的命令并且execvp 失败并且我不知道如何解决这个问题。
这是我的代码:
int main(int argc, char *argv[])
{
char delim[] = ";"; // the semicolon is the commands separator
FILE* batchFile;
char oneLine[512];
batchFile = fopen("myfile.txt", "r");
int numOfCommands = 0;
char *commands[100];
char *oneCommand;
pid_t childPid;
int child_status;
if(batchFile == NULL)
{
perror("Error opening file ... exiting !");
exit(1);
}
if(fgets(oneLine,512,batchFile) != NULL)
{
//puts(mystring);
fclose(batchFile);
}
printf("The command is: %s \n", oneLine);
oneCommand = strtok(oneLine,delim);
commands[numOfCommands++] = strdup(oneCommand);
while((oneCommand=strtok(NULL, delim))!=NULL)
{
commands[numOfCommands++] = strdup(oneCommand);
}
commands[numOfCommands] = NULL;
for(int i = 0;i < numOfCommands;i++)
{
printf("The command is: %s \n",commands[i]);
}
for(int i =0;i < numOfCommands;i++)
{
childPid = fork();
if(childPid == 0)
{
execvp(commands[i], argv);
perror("exec failure");
exit(1);
}
else
{
wait(&child_status);
}
}
return 1;
}
exit、cd 等一些命令不起作用,我猜可能是因为它们不在 /bin 中??
如何解决这个问题?
我的文件有以下一行
ls;date;cal;pwd;cd;ls -l;
当我运行我的程序时,它会输出以下内容。
【问题讨论】:
-
你正在传递
argv:execvp(commands[i], argv);。你可能想通过commands。 -
@I3x 我更改了它,但没有为每个命令找到这样的文件或目录。
-
发布 execvp 失败的示例行。打印您传递给
execvp的命令和参数以进行验证。 -
您需要解析输入字符串。许多不同的方法来做到这一点。例如
strtok。而且你不能运行cd,因为它不是一个可执行文件,而是一个内置的shell命令。 -
没有名为
ls -l的程序——五个字符,l,s,空格,破折号,l;您需要使用char *args[] = { "ls", "-l", 0 }; execvp(args[0], args);或等效项。你必须更彻底地解析你的命令,在空格处分割命令和参数。
标签: c shell operating-system command exec