[英]Triple pipe in C using pipe(), execlp() and dup()
考慮一個新的運算符“ |||”。 它將獲取先前程序的輸出,並將其作為輸入傳遞給三個不同的程序。 給出一個程序Triplepipe.c以實現以下命令:ls –l | uniq ||| grep ^ d,grep ^-,grep ^ p。 不要使用popen()庫調用,system()庫調用或臨時文件。
我正在使用以下邏輯來解決問題的第一部分。 在child1中執行'ls -l',在child2中執行'uniq',使用child1的標准輸出作為stdin,在父級中使用'grep ^ d',將child2的標准輸出作為stdin。 我能夠看到輸出。
但是我不知道如何將child2的輸出提供給三個單獨的grep來滿足限制集。 誰能幫忙嗎?
這項工作的一部分基本上是實施tee
。 設置完管道和子進程后,您必須進入一個循環,該循環讀取一次並寫入3次,直到讀取達到EOF。
在Linux中,還有一個tee
syscall,它不在您的禁止列表中。 對於該程序而言,它是完美的選擇,但是它是一個相當新的東西,因此很有可能您的老師還不知道它。
引用“管道只是文件”
認為您dup2'ed並且當前在一個孩子中將數據存儲在管道中。 現在只需從管道讀取並使用Write System調用並寫入3個不同的管道即可。
從那里您可以在3個不同的過程中對數據進行不同的處理
認為那就是您所需要的;)
附上我的問題的答案。
void main() {
int p1[2]; // pipe between ls | uniq and grep
int p2[2]; // pipt between ls and uniq
int p3[2]; // pipt between ls and uniq
int p4[2]; // pipt between ls and uniq
int p5[2]; // pipt between ls and uniq
char buff[200];
char data[10 * 1024];
int count;
int teelen;
pid_t ret;
pid_t chd;
pipe (p1);
ret = fork();
if (ret == 0) {
pipe (p2);
chd = fork();
if (chd == 0) {
close (1); // close stdout
dup (p2[1]); // dup stdout to p2's out
close (p2[0]); // close p2's in
execlp ("ls", "ls", "-l", NULL); // execute command
exit (0);
}
if (chd > 0) {
close (0); // close stdin
dup (p2[0]); // dup stdin to p2's in
close (p2[1]); // close p2's out
wait(NULL); // wait for child to finish
close (1); // close stdout
dup (p1[1]); // dup stdout to p1's out
close (p1[0]); // close p1's in
execlp ("uniq", "uniq", NULL); // command
exit (0);
}
}
if (ret > 0) {
close (0); // close stdin
dup (p1[0]); // dup stdin to p1's in
close(p1[1]);
wait(NULL); // wait for child to complete
memset (data, '\0', sizeof(data));
do {
memset(buff, '\0', sizeof(buff));
count = read(p1[0], buff, 199);
buff[count] = '\0';
if (count == 0)
break;
strcat (data, buff);
} while(1);
pipe (p3);
close(p1[0]);
write (p3[1], data, sizeof (data));
fsync(p3[1]);
if (fork() == 0) {
int c;
close(0);
dup(p3[0]);
close(p3[1]);
execlp ("grep", "grep", "-a", "^d", NULL);
exit (0);
}
close(p3[1]);
wait(NULL);
pipe (p4);
write (p4[1], data, sizeof (data));
if (fork() == 0) {
close(0);
dup(p4[0]);
close(p4[1]);
execlp ("grep", "grep", "-a", "^-", NULL);
exit (0);
}
close(p4[1]);
wait(NULL);
pipe (p5);
write (p5[1], data, sizeof (data));
if (fork() == 0) {
close(0);
dup(p5[0]);
close(p5[1]);
execlp ("grep", "grep", "-a", "^c", NULL);
exit (0);
}
close(p5[1]);
wait(NULL);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.