歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux的管道與重定向牛刀小試

Linux的管道與重定向牛刀小試

日期:2017/2/28 16:32:15   编辑:Linux教程

chengouxuan@chengouxuan-laptop:~/Desktop$ cat > isum.c
#include <stdio.h>
int main()
{
int a, b;
while(scanf("%d%d", &a, &b) != EOF)
printf("%d\n", a + b);
return 0;
}
chengouxuan@chengouxuan-laptop:~/Desktop$ gcc isum.c -o isum
chengouxuan@chengouxuan-laptop:~/Desktop$ cat > rand.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
srand(time(NULL));
for(i=0; i<10; ++i)
printf("%d %d\n", rand() % 100, rand() % 100);
return 0;
}
chengouxuan@chengouxuan-laptop:~/Desktop$ gcc rand.c -o rand
chengouxuan@chengouxuan-laptop:~/Desktop$ cat > redirection.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *argv1[] = {argv[1], NULL};
char *argv2[] = {argv[2], NULL};
int ppid[2];
int pid1, pid2;
if (argc < 3)
{
fprintf(stdout, "usage : %s receiver sender\n", argv[0]);
exit(EXIT_FAILURE);
}
pipe(ppid);
if ((pid1 = fork()) == 0)
{//child1
close(ppid[1]);
close(STDIN_FILENO);
dup(ppid[0]);
close(ppid[0]);
execvp(argv[1], argv1);
exit(EXIT_FAILURE);
}
else if ((pid2 = fork()) == 0)
{//child2
close(ppid[0]);
close(STDOUT_FILENO);
dup(ppid[1]);
close(ppid[1]);
execvp(argv[2], argv2);
exit(EXIT_FAILURE);
}
else
{//parent
close(ppid[0]);
close(ppid[1]);
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
exit(EXIT_SUCCESS);
}
return 0;
}
chengouxuan@chengouxuan-laptop:~/Desktop$ gcc redirection.c -o redir
chengouxuan@chengouxuan-laptop:~/Desktop$ ./redir ./isum ./rand
102
88
137
120
82
97
97
66
49
132

建立一根pipe,將rand的stdout定向到isum的stdin。

Copyright © Linux教程網 All Rights Reserved