当命令具有选项

时间:2016-01-31 06:15:54

标签: c shell operating-system command exec

所以我从一个有一行命令的文件中读取命令,每个命令都用一个分号分隔开来。我把这些命令放到一个数组中,我基本上是逐个执行它们。一切正常,直到我有一个有选项的命令,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;

当我运行我的程序时,它输出以下内容。

enter image description here

1 个答案:

答案 0 :(得分:1)

如果查看输出,则cd失败。这是预期的,因为cd是内置的shell,而不是命令。对于cd,您必须使用chdir(2)代替execv()

ls -l失败,因为没有这样的命令。在将命令传递给execvp()之前,您需要再次拆分命令。

基本上,您传递的命令必须采用以下形式:

char *cmd[] = {"ls", "-l", 0};  
execvp(cmd[0], cmd);