用linux写一个博客

它所创建的管道等价于下面的shell管道:$echo good morning|sed s/good/hi/g该程序的实现过程是:调用pipe()建立一个管道,利用fork()创建两个子进程;一个是左侧进程,另一个是右侧进程。左侧进程使用close(pipefd[0])关闭管道读取端,使用close(1)关闭最初的标准输出,使用dup(pipefd[1])将管道的写入端改为文件描述符1,使用close(pipefd[1])关闭打开文件描述符的一个副本,调用execvp()启动运行的程序;右侧进程的工作于此相似:使用close(pipefd[1])关闭管道写入端,使用close(0)关闭最初的标准输入,使用dup(pipefd[0])将管道的读取端改为文件描述符0,使用close(pipefd[0])关闭打开文件描述符的一个副本,调用execvp()启动运行程序。在父进程中,关闭管道的两端:close(pipefd[0])和close(pipefd[1]).最后,在父进程中使用wait()等待两个子进程结束。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    int pid1, pid2;
    int pfd[2];

    pipe(pfd);

    pid1 = fork();
    if (pid1 == 0)
    {
        char * argv[] = {
            "echo",
            "good morning",
            NULL
        };
        /* left child */
        close(pfd[0]);
        close(1); /* close stdout */
        dup(pfd[1]); /* redirect stdout to pipe */
        close(pfd[1]);
        execvp("echo", argv);
        exit(1);
    }

    pid2 = fork();
    if (pid2 == 0)
    {
        char *argv[] = {
            "sed",
            "s/good/hi/g",
            NULL
        };

        /* right child */
        close(pfd[1]);
        close(0); /* close stdin */
        dup(pfd[0]); /* redirect stdin to pipe */
        close(pfd[0]);
        execvp("sed", argv);
        exit(1);
    }

    close(pfd[0]);
    close(pfd[1]);
    wait(NULL);
    wait(NULL);
    printf("Both children exited.\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值