将exec()的输出放入管道

时间:2018-05-09 23:53:38

标签: c pipe

我遇到了一些管道问题。我正在创建一个shell,我正在扩展命令行参数。 我想我需要使用dup2,但我一直无法实现它,以至于我只是将我的所有代码重置为前一天的内容,因为它最终会被破坏。现在我有两个相互作用的功能。一个字符串,另一个调用exec,我需要获取该输出并使用管道将其放入另一个函数的字符串中。

我有一个名为expand的函数:

...
new = "my username is ";
string = "echo Lazarus";

//make the pipe
int myPipe[2];
pipe(myPipe);
int n;
char buffer[65000];

//call changeString         
changeString(string, myPipe[0], myPipe[1]);

/*currently, this is how I can get a string into the pipe. 
I need to do this in changeString instead.*/
write(myPipe[1], "this is a test", 14); 

//read from the pipe in a loop until EOF
int stillReading = 1;
while(stillReading != 0){
   if((n = read(myPipe[0], buffer, 65000)) >= 0){   
      stillReading = 0;
      buffer[n] = '\0';
   }    
}

close(myPipe[0]);
...

//add the result to the new string
for(int i = 0; i < bufferLength; i++){
   string[stringIndex++] = buffer[i];
}

printf("string is now '%s'\n", string); //should output: 'my username is Lazarus'
...

然后我有一个流程changeString

...

cpid = fork();
if(cpid < 0){
   return -1;
}

if(cpid == 0){
   //We are the child!

   //where argList[0] == the first word of string, and argList = string
   //(this works just fine)
   execvp(argList[0], argList);

...

...

我需要做的是将一些代码放入changeString(dup2?),这允许我将exec的输出放入新字符串中。最后,我得到new“我的用户名是拉撒路”

0 个答案:

没有答案