【问题标题】:Piping in my own C shell在我自己的 C shell 中管道
【发布时间】:2016-09-12 22:16:27
【问题描述】:

我已经实现了一个 C shell 的开头,如下所示。到目前为止,我的重定向工作正常,我想我会实现 |以类似的方式,但我遇到了困难。 任何人都可以帮忙吗? 我将从检查管道运算符开始,然后将 sa[i-1] 和 sa[i+1] 保存为两个单独的命令,但我不确定在此之后如何正确地 fork() 和 exec() .

int startProcess (StringArray sa)
{
  int pid; 
  int status;
  int fd1;
  int fd2; 
  int current_in;
  int current_out;
  int fd0;
  int fd00;
  int in = 0;
  int out = 0; 
  char input[64]="";
  char output[64]="";
  char cmd1[64] ="";
  char cmd2[64] ="";
  int fd[2];
  int pipe = 0; 

  switch( pid = fork()){
 case -1://This is an error 
   perror("Failure of child.");
   return 1;
 case 0: // This is the child
   // Redirection


   /* finds where '<' or '>' occurs and make that sa[i] = NULL ,
      to ensure that command wont' read that*/

    for(int i=0;sa[i]!='\0';i++)
    {
        if(strcmp(sa[i],"<")==0)
        {        
            sa[i]=NULL;
            strcpy(input,sa[i+1]);
            in=2;           
        }               

        if(strcmp(sa[i],">")==0)
        {      
            sa[i]=NULL;
            strcpy(output,sa[i+1]);
            out=2;
        }

    }

    //if '<' char was found in string inputted by user
    if(in)
    {   

        // fdo is file-descriptor
        int fd0;
        if ((fd0 = open(input, O_RDONLY, 0)) < 0) {
            perror("Couldn't open input file");
            exit(0);
        }           
        // dup2() copies content of fdo in input of preceeding file
        dup2(fd0, 0); // STDIN_FILENO here can be replaced by 0 

        close(fd0); // necessary
    }

    //if '>' char was found in string inputted by user 
    if (out)
    {

        int fd00 ;
        if ((fd00 = creat(output , 0644)) < 0) {
            perror("Couldn't open the output file");
            exit(0);
        }           

        dup2(fd00, STDOUT_FILENO); // 1 here can be replaced by STDOUT_FILENO
        close(fd00);
    }


          execvp(sa[0], sa);
          perror("execvp");
          _exit(1);


    printf("Could not execute '%s'\n", sa[0]);
  default:// This is the parent 
   wait(&status);
   return (status == 0) ? 0: 1;
  }
}

【问题讨论】:

  • 在 SO 和其他网站上有很多关于这个确切问题的问题。你做过搜索吗?如果您真的需要帮助,那么您需要问一个比“我不确定如何正确地 fork() 和 exec()”更具体的问题。答案是您先拨打fork,然后拨打exec。具体有什么不明白怎么办?
  • 是的,我进行了很多搜索。我不明白何时何地,以及 STDOUT 和 STDIN 如何与管道一起工作。

标签: c shell pipe


【解决方案1】:
  1. 制作管道。
  2. fork()
  3. 在父级中,将 STDOUT 文件描述符 (1) 设置为管道的输入。
  4. 在子进程中,将 STDIN 文件描述符 (0) 设置为管道的输出。
  5. exec() 在父母和孩子中。

fork() 之后在孩子身上执行所有这些操作,就像重定向一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多