首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我自己的C shell中的管道

我自己的C shell中的管道
EN

Stack Overflow用户
提问于 2016-09-13 06:16:28
回答 1查看 61关注 0票数 1

我已经实现了一个C shell的开始,如下所示。到目前为止,我的重定向工作正常,我想我会以类似的方式实现|,但我遇到了困难。有人能帮上忙吗?我会从检查管道操作符开始,然后将sai-1和sai+1保存为两个单独的命令,但是我不确定在这之后如何正确地执行fork()和exec()。

代码语言:javascript
复制
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;
  }
}
EN

回答 1

Stack Overflow用户

发布于 2016-09-13 06:31:54

pipe.

  • fork().

  • In父项将pipe.

  • exec()文件描述符(1)设置为管道的输入。子项中的

  • 将STDIN文件描述符(0)设置为父项和子项中的STDIN文件的输出。

在你fork()之后,在孩子中做所有这些事情,就像重定向一样。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39459594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档