2014-03-06 27 views
0

因此,我已經使用了fork() ,其中parent正在打開文件並將其內容讀入緩衝區,並將寫入結束(fd [1])中的緩衝區發送到讀取結束fd [0])在stdin上使用grep

子進程負責讀取緩衝區。我想將fd [0]中的任何內容重定向到stdin,因此我可以在其上使用Unix命令。舉個例子:

// in child process 
dup2(fd[0], 0); // 0 is STDIN 

// Don't know what to do here 

execl("/bin/grep/", "grep", "hello", NULL); // find the string 'hello' and operate on the content coming from stdin 

任何幫助,將不勝感激。

回答

0

這似乎是相當好的。 也許你可以dup2後關閉一些FDS:

// in child process 
dup2(fd[0], STDIN_FILENO); 
close(fd[0]); 
close(fd[1]); 

編輯:

似乎有錯字:"/bin/grep/"

它應該是:"/bin/grep"

+0

,不能正常工作。在我調用dup2()之前,我已經關閉了fd [1],然後在孩子退出之前關閉了fd [0],但那也不起作用。 –

+0

@Phil Kurtis:我更新了答案。 – SKi