- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
// grep ^\s*$ file1 file2 ... | wc -l
int main(int argc, const char **argv)
{
int fd[2];
pid_t pid;
assert(!pipe(fd));
assert((pid = fork()) >= 0);
if (!pid)
{
char **newargv;
assert(dup2(fd[1], 1) == 1);
assert(!close(fd[0]));
assert(!close(fd[1]));
assert(newargv = malloc((argc + 2) * sizeof(char *)));
newargv[0] = "grep";
newargv[1] = "^\\s*$";
memcpy(newargv + 2, argv + 1, (argc + 1) * sizeof(char *));
assert(execvp("grep", newargv) * 0);
}
assert((pid = fork()) >= 0);
if (!pid)
{
assert(dup2(fd[0], 0) == 0);
assert(!close(fd[0]));
assert(!close(fd[1]));
assert(execlp("wc", "wc", "-l", NULL) * 0);
}
assert(!close(fd[0]));
assert(!close(fd[1]));
while (wait(NULL) != -1);
return 0;
}