感谢支持
我们一直在努力

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。

赞(0) 打赏
转载请注明出处:服务器评测 » Linux的管道与重定向牛刀小试
分享到: 更多 (0)

听说打赏我的人,都进福布斯排行榜啦!

支付宝扫一扫打赏

微信扫一扫打赏