簡體   English   中英

如何重定向由fork()創建並使用exec()函數的子進程的IO?

[英]How to redirect the IO of child process created by fork() and uses exec() function?

我正在用C語言編寫Shell。 用戶應該能夠執行各種命令,並使用pipe(|)將一個命令的輸入重定向到另一個命令。 主shell進程是父進程,並為每個命令派生新進程,在子進程中,該命令由exec *()函數調用。

但是我不知道如何將一個子進程的標准輸入/輸出重定向到另一個。

也許這可以幫助您。

int f=open(somefile, O_WRONLY | O_CREAT, S_IRWXU);
dup2(f,1);  //redirecting output to file
//execute your first command here using fork
close(f);
int f=open(somefile, O_RDONLY | O_CREAT, S_IRWXU);
dup2(f,0);    //this will give the ouput of the first command to stdout 
//i.e. the input is present for second one
//execute your second command here
close(f);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM