【问题标题】:Making simple shell in c while implementing pipe between children在 c 中制作简单的 shell,同时实现子级之间的管道
【发布时间】:2017-04-24 14:38:41
【问题描述】:

我想用管道做一个简单的外壳。 我想我几乎做到了,但它并没有回到主要的。 我认为 exec 没有完成。 以下是我的代码的一部分。 我将命令解析为如下定义的结构块。 符号类型 5 表示它有 | . 当我运行这个程序时, this is result image. 当我不使用管道时,它会返回并再次打印 > 但当我使用管道时它不会。

typedef struct Command {
    char *file;             // file to execute 
    char **arglist;         // argument list to executable
    SymbolType symbolType;  // command seperator 

    int status;             // exit code of the commnad

    struct Command *next, *prev;
} Command;


void GetPipe(Command *command, int *fd){
  SymbolType symbol = command->symbolType;
    if(symbol==5){
      close(1);
      close(fd[0]);
      dup2(fd[1],1);
}

  if((command->prev)!=NULL) symbol=command->prev->symbolType;
  if(symbol==5){
    close(0);
    close(fd[1]);
    dup2(fd[0],0);
  }
}

void ExecuteCommand(Command *command){
  int fd[2];
  pipe(fd);
  for(;command!=NULL;command=command->next){
    pid_t pid = fork();
    if(pid<0) exit(1);
    else if(pid==0){
      GetPipe(command, fd);
      if (execvp(command->file, command->arglist)==-1){
      command->status=status_failure; exit(1);}}
    else {
      int status;
      //waitpid(pid, &status, 0);
      wait(&status);
    }
  }

  close(fd[0]);
  close(fd[1]);

}

int main(void){

Command *head = NULL;
int should_run = 1;

  while (should_run){
    printf("> ");
    fflush(stdout);
    GetCommandChain(&head);
    ExecuteCommand(head);
    DeleteCommandChain(head);
  }
}

【问题讨论】:

  • 为什么你认为exec 没有完成?您是否使用调试器单步执行您的代码?如果没有,请这样做,然后发布您的发现。

标签: c pipe dup


【解决方案1】:

。我认为 exec 没有完成。

exec 系列系统调用将进程的整个地址空间替换为命令exec'd 的新地址空间。它不会回来。话虽如此,您的子代码看起来还不错。

一个潜在的问题是父进程没有对管道的读取端做任何事情。因此,该命令会将其输出写入管道,然后,当缓冲区已满时,它将阻塞写入等待某些东西读取一些数据。

另一个潜在的问题是,您永远不会向命令的标准输入写入任何内容。如果它期待输入,它将在读取时永远阻塞。

我认为您需要做的是将链中每个命令的标准输出通过管道传输到链中下一个命令的标准输入(也可能根据第一个命令的内容将一些输入放入其中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2012-03-06
    相关资源
    最近更新 更多