您的位置:首页 > 运维架构 > Linux

linux的管道与重定向牛刀小试

2010-08-14 10:54 274 查看
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。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: