私は2人の子供と1つの親が欲しいです。プロセス間のパイプチェーン
親はファイル "a.txt"から読み取り、トラフパイプを最初の子に送信します。最初の子は文字を読み取り、2番目の子に下位の文字を送信します。
2番目の子は、それぞれ異なるcharと出現回数(1行につき)を "b.txt"で出力し、親にパイプを通って別個の文字数を送ります。親は2番目の子からの結果を出力します。
私はパイプを親から1子にしてテストしましたが、パイプを親に戻しました。 私がそれを理解できないのは、パイプを2番目の子供に行く方法です。私はdup2
の情報を探していましたが、それを動作させる方法はありません。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
void main()
{
int pfd1[2], pfd2[2], pid1, pid2, pfin, status, fd;
char *c = (char *)malloc(sizeof(char));
if (pipe(pfd1) < 0) {
printf("Eroare la crearea pipe-ului\n");
exit(1);
}
if (pipe(pfd2) < 0) {
printf("Eroare la crearea pipe-ului\n");
exit(1);
}
if ((pid1 = fork()) < 0) {
printf("Eroare la fork\n");
exit(1);
}
if (pid1 == 0) { /*child */
close(pfd1[1]);
while (read(pfd1[0], c, 1) > 0) {
//printf("%s",c);
if (islower(*c)) {
close(pfd2[0]);
//inchid capul de citire; scriu in pipe
write(pfd2[1], c, 1);
////dup??????
}
}
printf("\n");
write(pfd[1], buff, len);
close(pfd1[0]);
close(pfd2[1]);
exit(0);
}
if ((pid2 = fork()) < 0) {
printf("Eroare la fork\n");
exit(1);
}
if (pid2 == 0) {
printf("second child");
exit(0);
}
/* parent */
close(pfd1[0]);
close(pfd2[1]);
fd = open("date.txt", O_RDONLY);
while (read(fd, c, 1) > 0) {
write(pfd1[1], c, 1);
}
close(pfd1[1]); /* la sfarsit inchide si capatul utilizat */
close(pfin);
while (read(pfd2[0], c, 1) > 0)
printf("%s", c);
close(pfd2[0]);
printf("%d", wait(&status));
printf("%d", wait(&status));
}