微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c-execl`d程序不回复提示

如何解决c-execl`d程序不回复提示

编辑:该问题已在评论中回答

所以,我正在研究管道。长话短说,我有两个程序:

  1. 一个程序创建一个pipe和两个fork:第一个fork关闭read描述符,并向write写一些东西(然后关闭它) ,第二个fork关闭write一个,第二个dup2关闭管道read上的read到标准输入端(末端关闭execl本身)程序,给出第一个fork作为参数写入的文本大小;父级关闭两个waitpid(第二个)的子级的两个管道侧和execl
  2. 第二个程序只需从其标准输入(管道一侧)填充read,然后write将其输出到标准输出,然后关闭管道以防万一。

在这样的设置中,所有内容均按我的预期工作,但是当我在第一个程序中删除waitpid时(或只是等待第一个写入的孩子而不是第二个孩子),第二个孩子的行为就很奇怪-它执行直到最后,遍历所有IO(即执行printf之前的exit),然后不给我返回提示。即,终端看起来程序正在等待来自标准输入的输入。如果我在没有execl的情况下执行第一个程序,那么一切正常,如果我仅在一个参数的情况下执行第二个程序,那么它将仅等待直到将输入提供给标准输入为止(因为它不是一部分)在这种情况下是管道的数量)。

据我所知,当父母终止时,孩子init被“继承”并得到wait。但是,即使不是,也就是说,即使它仍然是僵尸,也还是很奇怪-为什么直到我明确等待才能恢复提示

下面的代码(正确运行的设置):

一个程序

  /* headers */
  int main(void)      
  {   
      int fildes[2];
      pid_t p1,p2;
      int status;
      char mess[] = "written from execved program!\n";
      int buf = strlen(mess);
      
      if(pipe(fildes) == -1) {
          perror("pipe in main");
          exit(EXIT_FAILURE);
      }
      p1 = fork(); 
      if(p1 == -1) {
          perror("fork p1 in main");
          exit(EXIT_FAILURE);
      }
      else if (p1 == 0) {
          printf("Child 1!\n");
          close(fildes[0]);
          write(fildes[1],mess,buf);
          close(fildes[1]);
          printf("Before exit in child 1!\n");
          exit(EXIT_SUCCESS);
      }
      
      p2 = fork(); 
      if(p2 == -1) {
          perror("fork p2 in main");
          exit(EXIT_FAILURE);
      }
      else if (p2 == 0) {
          printf("Child 2!\n");
          dup2(fildes[0],0);
          close(fildes[0]);
          close(fildes[1]);
          char s_buf[30];
          sprintf(s_buf,"%d",buf);
          execl("./pipe2slave","pipe2slave",s_buf,(char *) 0);
          perror("execl have returned");
          exit(EXIT_FAILURE);
      }
      close(fildes[0]);
      close(fildes[1]);
  /* 
   below if I wait for,say,p1,or don't wait it all,the weird behavior described in my question happens 
  */
      if(waitpid(p2,&status,0) == -1) { 
          perror("waitpid in main");
          exit(EXIT_FAILURE);
      }   
      if(WIFEXITED(status))
          printf("pipe2slave exit status is %d\n",WEXITSTATUS(status));
      printf("End of main in pipe2!\n"); 
      exit(EXIT_SUCCESS);  
  }

第二程序

   /* headers */ 
   int main(int argc,char **argv) 
   {
        if (argc != 2) {
            perror("pipe2slave - not enough args");
            exit(EXIT_FAILURE);
        }
        printf("program name is %s\n",argv[0]);
        int buf = atoi(argv[1]);
        printf("%d\n",buf);
        char mess_in[buf];
        read(0,mess_in,buf);
        write(1,buf);
        fsync(1);
        close(0);
        printf("end of slave!\n");
        exit(EXIT_SUCCESS); 
    }

提前谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。