将 execvp 的输出放入字符串 [英] putting output of execvp into string

查看:77
本文介绍了将 execvp 的输出放入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a shell that has a function which eventually calls execvp(...) which gives an output. For example "echo hello" gives an output of "hello". Everything works, don't worry. I have tested it very much, I just didn't put the full code here because it is 1000 lines of code.

如何从 execvp、dup2 中获取该输出并将其放入字符串中?

How can i take that output from execvp, dup2 it, and put it into a string?

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

I know I use dup2, but I'm not sure how.

我的代码中都有这些:

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);

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

then I call my function and I want to pass the write end of pipe into it.

 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就是一二三四"

at the end, I want the output from exec to be put into globalString. Then I put globalString into myString, so that myString is "one two three four"

谢谢.

推荐答案

我用于从衍生进程获取输出的代码片段是:

The snippet I use for getting output from a spawned process is:

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`

这篇关于将 execvp 的输出放入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆