回答編集履歴

2

コードと問題点の説明を追加

2021/06/25 23:18

投稿

kazuma-s
kazuma-s

スコア8224

test CHANGED
@@ -81,3 +81,123 @@
81
81
  ```
82
82
 
83
83
  このコードで分かったことと分からないことをコメントしてください。
84
+
85
+
86
+
87
+ **追記**
88
+
89
+ 親プロセスの方で、重複行の削除をするようにしてみました。
90
+
91
+ ```C
92
+
93
+ #include <stdio.h> // perror, fopen, fclose, fgets, fputs, printf
94
+
95
+ #include <stdlib.h> // exit
96
+
97
+ #include <string.h> // strcmp
98
+
99
+ #include <fcntl.h> // open
100
+
101
+ #include <unistd.h> // fork, pipe, dup, close
102
+
103
+ #include <wait.h> // wait
104
+
105
+
106
+
107
+ int main(int argc, char **argv)
108
+
109
+ {
110
+
111
+ if (argc != 2) {
112
+
113
+ perror("the number of command line arguments is wrong."); exit(1);
114
+
115
+ }
116
+
117
+ FILE *f = fopen(argv[1], "r");
118
+
119
+ if (!f) { perror(argv[1]); exit(1); }
120
+
121
+
122
+
123
+ int fd[2];
124
+
125
+ if (pipe(fd) < 0) { perror("pipe"); exit(1); }
126
+
127
+
128
+
129
+ pid_t ret = fork();
130
+
131
+ if (ret < 0) { perror("failed to fork"); exit(1); }
132
+
133
+
134
+
135
+ if (ret == 0) {
136
+
137
+ close(0);
138
+
139
+ dup(fd[0]);
140
+
141
+ close(fd[0]);
142
+
143
+ close(fd[1]);
144
+
145
+ fclose(f);
146
+
147
+ execl("/usr/bin/wc", "wc", "-l", NULL);
148
+
149
+ }
150
+
151
+ else {
152
+
153
+ close(1);
154
+
155
+ dup(fd[1]);
156
+
157
+ close(fd[0]);
158
+
159
+ close(fd[1]);
160
+
161
+ char s1[1024], s2[1024], *p1 = s1, *p2 = s2, *tmp;
162
+
163
+ *p1 = '\0';
164
+
165
+ while (fgets(p2, 1024, f))
166
+
167
+ if (strcmp(p1, p2)) {
168
+
169
+ fputs(p2, stdout);
170
+
171
+ tmp = p1, p1 = p2, p2 = tmp;
172
+
173
+ }
174
+
175
+ fclose(stdout);
176
+
177
+ fclose(f);
178
+
179
+ int status;
180
+
181
+ wait(&status);
182
+
183
+ }
184
+
185
+ }
186
+
187
+ ```
188
+
189
+ でも、fopen, fclose などの高水準ライブラリ関数を使用しているのは
190
+
191
+ 問題の条件に合いませんので、その部分は書き換えが必要です。
192
+
193
+
194
+
195
+ 親プロセスで行数を数えるコードも、
196
+
197
+ getchar と printf を使っているのでダメですね。
198
+
199
+
200
+
201
+ 高水準ライブラリ関数を使用しないコードが書けたら、
202
+
203
+ それを質問に追記して解決としてください。

1

コードの修正

2021/06/25 23:18

投稿

kazuma-s
kazuma-s

スコア8224

test CHANGED
@@ -46,6 +46,8 @@
46
46
 
47
47
  close(fd[0]);
48
48
 
49
+ close(fd[1]);
50
+
49
51
  execl("/usr/bin/uniq", "uniq", argv[1], NULL);
50
52
 
51
53
  }
@@ -55,6 +57,8 @@
55
57
  close(0);
56
58
 
57
59
  dup(fd[0]);
60
+
61
+ close(fd[0]);
58
62
 
59
63
  close(fd[1]);
60
64