回答編集履歴
2
コードと問題点の説明を追加
answer
CHANGED
@@ -39,4 +39,64 @@
|
|
39
39
|
}
|
40
40
|
}
|
41
41
|
```
|
42
|
-
このコードで分かったことと分からないことをコメントしてください。
|
42
|
+
このコードで分かったことと分からないことをコメントしてください。
|
43
|
+
|
44
|
+
**追記**
|
45
|
+
親プロセスの方で、重複行の削除をするようにしてみました。
|
46
|
+
```C
|
47
|
+
#include <stdio.h> // perror, fopen, fclose, fgets, fputs, printf
|
48
|
+
#include <stdlib.h> // exit
|
49
|
+
#include <string.h> // strcmp
|
50
|
+
#include <fcntl.h> // open
|
51
|
+
#include <unistd.h> // fork, pipe, dup, close
|
52
|
+
#include <wait.h> // wait
|
53
|
+
|
54
|
+
int main(int argc, char **argv)
|
55
|
+
{
|
56
|
+
if (argc != 2) {
|
57
|
+
perror("the number of command line arguments is wrong."); exit(1);
|
58
|
+
}
|
59
|
+
FILE *f = fopen(argv[1], "r");
|
60
|
+
if (!f) { perror(argv[1]); exit(1); }
|
61
|
+
|
62
|
+
int fd[2];
|
63
|
+
if (pipe(fd) < 0) { perror("pipe"); exit(1); }
|
64
|
+
|
65
|
+
pid_t ret = fork();
|
66
|
+
if (ret < 0) { perror("failed to fork"); exit(1); }
|
67
|
+
|
68
|
+
if (ret == 0) {
|
69
|
+
close(0);
|
70
|
+
dup(fd[0]);
|
71
|
+
close(fd[0]);
|
72
|
+
close(fd[1]);
|
73
|
+
fclose(f);
|
74
|
+
execl("/usr/bin/wc", "wc", "-l", NULL);
|
75
|
+
}
|
76
|
+
else {
|
77
|
+
close(1);
|
78
|
+
dup(fd[1]);
|
79
|
+
close(fd[0]);
|
80
|
+
close(fd[1]);
|
81
|
+
char s1[1024], s2[1024], *p1 = s1, *p2 = s2, *tmp;
|
82
|
+
*p1 = '\0';
|
83
|
+
while (fgets(p2, 1024, f))
|
84
|
+
if (strcmp(p1, p2)) {
|
85
|
+
fputs(p2, stdout);
|
86
|
+
tmp = p1, p1 = p2, p2 = tmp;
|
87
|
+
}
|
88
|
+
fclose(stdout);
|
89
|
+
fclose(f);
|
90
|
+
int status;
|
91
|
+
wait(&status);
|
92
|
+
}
|
93
|
+
}
|
94
|
+
```
|
95
|
+
でも、fopen, fclose などの高水準ライブラリ関数を使用しているのは
|
96
|
+
問題の条件に合いませんので、その部分は書き換えが必要です。
|
97
|
+
|
98
|
+
親プロセスで行数を数えるコードも、
|
99
|
+
getchar と printf を使っているのでダメですね。
|
100
|
+
|
101
|
+
高水準ライブラリ関数を使用しないコードが書けたら、
|
102
|
+
それを質問に追記して解決としてください。
|
1
コードの修正
answer
CHANGED
@@ -22,11 +22,13 @@
|
|
22
22
|
close(1);
|
23
23
|
dup(fd[1]);
|
24
24
|
close(fd[0]);
|
25
|
+
close(fd[1]);
|
25
26
|
execl("/usr/bin/uniq", "uniq", argv[1], NULL);
|
26
27
|
}
|
27
28
|
else {
|
28
29
|
close(0);
|
29
30
|
dup(fd[0]);
|
31
|
+
close(fd[0]);
|
30
32
|
close(fd[1]);
|
31
33
|
int c, count = 0;
|
32
34
|
while ((c = getchar()) != EOF)
|