1

我正在编写一个 mini-shell 以更熟悉 C 中的 Unix 进程管理。它从命令行读取内容并通过 execlp 将这些参数传递给系统。

# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>

#define MAXSIZE 100

char prompt[MAXSIZE];

int main(void)
{
   pid_t pid;

   printf("> ");

   // read stuff 
   if (fgets(prompt, MAXSIZE, stdin) == NULL){
      printf("Input validation error!");
      abort();
   }
   // printf("DEBUG: %s" , prompt);

   if (strcmp(prompt, "exit")==0) abort();


   if ((pid=fork())<0){       // copy process

      printf("Process error!");
      abort();
   }

   if (pid==0){                // exec in son-prcess

      char *command=(char*)strtok(prompt, " ");
      execlp(command, command, 0);  // overwrite memory

      printf("Error, command not found!");
      abort();
   } else {

      waitpid(pid, 0, 0);
    }
}

实际上就是这样,但我没有从execlp(). 有人知道这是为什么吗?

4

2 回答 2

4

我尝试运行您的程序,但由于command包含\n(换行符)而失败。我通过在其中放入\n而不是“”来更改它,strtok然后它成功运行。

详细地:

  if (pid==0){                // exec in son-prcess
      char *command=(char*)strtok(prompt, "\n");
      printf ("'%s'\n", command);
      execlp (command, command, 0);  // overwrite memory
      printf("Error %d (%s)\n", errno, strerror (errno));
      abort();
   } else {

测试运行:

$ ./a.out
> ls
'ls'
(通常的 ls 行为)
于 2009-10-30T17:05:13.020 回答
1

Kinopiko 已经找到了它不起作用的原因,但是您没有看到任何错误消息的原因是您的 shell 提示符正在覆盖它。尝试在末尾添加换行符:

printf("Error, command not found!\n");
于 2009-10-30T17:08:56.883 回答