【问题标题】:putting output of execvp into string将 execvp 的输出放入字符串
【发布时间】:2018-05-10 21:29:50
【问题描述】:

我有一个 shell,它有一个最终调用 execvp(...) 的函数,该函数给出一个输出。例如“echo hello”给出“hello”的输出。一切正常,别担心。我已经测试了很多,我只是没有把完整的代码放在这里,因为它是1000行代码。

我如何从 execvp 中获取输出,将其 dup2,然后放入字符串中?

我知道我使用 dup2,但我不确定如何使用。

我的代码中都有这些:

char* globalString;   //a global string I want to put the output into
char* myString = "one two three ";
char* append = "echo four";
int myPipe[2];  //my pipe  
pipe(myPipe);

然后我调用我的函数,我想将管道的写入端传递给它。

 myfunction( ... , [pointer to write end of pipe]); //i don't know how    

  //ignoring previous code


  cpid = fork();
  if(cpid < 0){
     //Fork wasn't successful 
     perror("fork");
     return -1;
  }

  //in the child
  if(cpid == 0){

     execvp(...);  // in this example, this prints "four" to stdout        

     //execvp returned, wasn't successful
     perror("exec");

     fclose(stdin);  

     exit(127);
  }

//then more code happens
}

最后,我希望将 exec 的输出放入 globalString。然后我把globalString放到myString中,这样myString就是“一二三四”

谢谢。

【问题讨论】:

  • @Mulliganaceous 现在没有错。我在问如何使用 dup2 从 execvp 获取输出并将其放入字符串中。我只包含了涉及这种情况的代码区域,因为我的其余代码用于执行其他操作。
  • 当然有popen()...
  • @Mulliganaceous 我觉得你没注意。
  • 我假设您在致电 execvp 之前先致电 fork。基本配方是:(1)拨打pipe(); (2) 拨打fork(); (2) 在子进程中,关闭管道[0],使用dupdup2 将管道[1] 重新调整为fd 1(即stdout),并调用execvp; (3)在parent中,关闭pipe[1],从pipe[1]中读取child的输出。
  • @SteveSummit 成功了!我有一个新问题,我认为是换行符,但我可以自己解决。谢谢你的公式,这很容易理解。

标签: c pipe


【解决方案1】:

我用于从衍生进程获取输出的 sn-p 是:

pid_t pid = 0;
int pipefd[2];

pipe(pipefd); //create a pipe
pid = fork(); //spawn a child process
if (pid == 0)
{
   // Child. redirect std output to pipe, launch process
   close(pipefd[0]);
   dup2(pipefd[1], STDOUT_FILENO);
   execv(my_PROCESSNAME, args);
}
//Only parent gets here. make tail nonblocking.
close(pipefd[1]);
fcntl(pipefd[0], F_SETFL, fcntl(pipefd[0], F_GETFL) | O_NONBLOCK);

child_process_output_fd = pipefd[0];  //read output from here
child_process_pid = pid;  //can monitor this for completion with `waitpid`

【讨论】:

    猜你喜欢
    • 2011-09-13
    • 1970-01-01
    • 2020-05-23
    • 2018-03-20
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    相关资源
    最近更新 更多