处理命令,如ls -l / somedir

时间:2015-11-19 19:25:28

标签: c unix

我的代码到目前为止在用户输入时处理ls命令。我希望能够处理像ls -l /tmp这样的命令。 我的代码到目前为止。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <sys/types.h>


int main(void)
{
for(;;){
char str[500];
printf("Type a command : \n");
scanf("%s",str);
char *path;
  path = getenv("PATH");
    char *argv[] = { path ,NULL};

    int status;
    int pid = fork();

        if ( pid == 0 ) {
printf("executing==============> %s \n",str);
          execvp(str,argv);
}
wait(&status);
}
}

有什么想法吗?我必须在没有system()的情况下这样做。

4 个答案:

答案 0 :(得分:2)

execvp系统调用期望其参数为带有命令的字符串和以该命令开头的字符串数组,后跟其参数,逐个,以NULL字符串结尾。

在你的情况下,它将是:

char *argv[] = {"ls", "-l", "/tmp", NULL};

请记住,这段代码只是幕后内容的一个例证。您需要根据用户的输入构建argv[]

您可以组合strchr()来标记输入(查找空格),然后使用sscanf读取字符串的一部分。然后,您必须将输入指针更新为strchr() + 1返回的值,并使用sscanf()读取命令的下一部分。

答案 1 :(得分:1)

您可以使用system(str)轻松完成此操作和类似的事情。

它分叉,调用execl("/bin/sh", "sh". "-c", command, (char *) 0);并在命令完成后返回。

当它调用shell时,它也支持shell内置函数。

答案 2 :(得分:0)

使用“system”功能。 system(str)应该可行。 此函数创建一个单独的线程,执行提供给它的命令。 有关详细信息,请参阅“man system”。

答案 3 :(得分:0)

这对我有用:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <sys/types.h>
#define MAX_NAME_SZ 256

int main(void)
{
char *str,*ret, *pa1, *pa2, *dtm ,*pa3;
str=(char *)malloc(50*sizeof(char));
ret=(char *)malloc(50*sizeof(char));
pa1=(char *)malloc(50*sizeof(char));
pa2=(char *)malloc(50*sizeof(char));
dtm=(char *)malloc(50*sizeof(char));
pa3=(char *)malloc(50*sizeof(char));
char ch =' ' ;
printf("Type a command : \n");

    fgets (str, MAX_NAME_SZ, stdin);

    if ((strlen(str)>0) && (str[strlen (str) - 1] == '\n'))
        str[strlen (str) - 1] = '\0';
    ret = strchr(str, ch);

    if (ret !=NULL)
    {
        strcpy( dtm, str );
        sscanf( dtm, "%s %s %s  ", pa1, pa2,pa3  );
        }

    char *path;
     path = getenv("PATH");

    int status=2;
    int pid = fork();

    if ( pid == 0 ) {
        if (ret !=NULL){
          char *argv[] = { path ,pa2, pa3 ,NULL};
              execvp(pa1,argv);

                }
        else {
          char *argv[] = { path ,NULL};
          execvp(str,argv);

        }
    }
    wait(&status);

    }
相关问题