我正在撰寫一個程式,我想以編程方式將命令重定向到另一個行程。因此,如果我收到命令作為引數,我想接收父行程的輸出。
我的代碼是:
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char* argv[]) {
{
char msg[8]=“message”;
int pp[2];
if(pipe(pp)<0) {
printf("Error pipe");
exit(1);
}
if (!fork())
{
close(fd[0]);
//TODO...
} else {
close(fd[1]);
read(fd[0], msg, 8);
close(fd[0]);
}
}
我迷失了子部分,在那里我執行命令并進行重定向。我正在使用管道在子行程和父行程之間進行通信。
在子端,我關閉了未使用的管道端,然后我不知道如何繼續。
你能幫我嗎?
uj5u.com熱心網友回復:
步驟如下:
- 關閉管道讀取和標準輸出
- dup() pipe-write 將 pipe-write 重定向到 fd=1 的 stdout
- 關閉初始管道寫入
- 執行命令,從 argv 讀取第一個引數
你的代碼變成這樣:
if (!fork())
{
close(pp[0]);
close(1);
dup(pp[1]);
close(pp[1]);
execlp(argv[1], argv[1],(char *)0);
exit(0)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537363.html
標籤:Cunix管道叉子等待
