-3

我想问一下如何用C编写exec进程编程。现在,我输入了这些代码,我使用了strtok和strdup。

我的代码错误地从输入中赋值,所以你能看到我的代码吗?你能告诉我代码中有什么问题吗?

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

int main(){

  int pid;
  int status, i = 0;
  char input[256], path[30];
  const char* a[10];
  char* token;
  char* split = " ";

  while(input != "exit"){
    printf("Please type your command:\n");
    fgets(input, 256, stdin); /* emxape: ls -alf    argv[0] = "ls" argv[1] = -alf*/
    printf("Input: %s", input);
    i = 0;
    token = strdup(strtok(input,split));

while(token != NULL){
  a[i] = token;
  token = strdup(strtok(NULL,split));
  printf("a%d is %s\n", i, a[i]);
  i++;
}

int j = 0;
while( j < sizeof(a))
  {
    printf("%s", a[j]);
    j++;
  }

//free(copy);



if(strcmp(a[0],"cd")== 0 )/*for compare pointer*/
{
  if (chdir((a[1])) == 0) {
    printf("Sucess change Directory.\n");
    return 0;
  }
  else {
    printf("Fault change Directroy\n");
    perror("");
  }

  if (a[1] == NULL)
    {
      if(chdir(getenv("HOME"))<<0)
        perror("cd");
      return 0;
    }
  else
    {
      if(chdir(a[1]) <0)
        perror("cd");
    }



}

sprintf(path,"%s",a[0]);

pid = fork();

/*Child process*/
if(pid == 0){
   //execl(path,a[0],a[1],NULL);
   execl(a[0],a[1],a[2],NULL);
   printf("Wrong child process: %s",path);
   exit(0);
  }

  /*Parents Process*/
   else {
    wait(&status);
   }
  }//while
   printf("Thank you.");
 }/*main*/
4

1 回答 1

1

至少有2个问题

  1. 第 26 行: token = strdup(strtok(NULL,split)); 应该是token = strdup(strtok(input,split));

  2. 第一次修改后,第24行的循环就可以运行了。但仍然无法正常运行。似乎strtok(), 并strdup()没有正确运行。

于 2013-03-12T08:40:42.393 回答