免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2679 | 回复: 0
打印 上一主题 下一主题

pipe()用法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-07-20 13:29 |只看该作者 |倒序浏览
#include
#include
#include
#include
#include
void signal_handler();
void sig_chld(int signo);
void err_sys(const char *errmsg);
int main(void)
{
        int fd[2];
        pid_t pid;
        char buf[BUFSIZ];
        ssize_t n;
        signal_handler();       /* handler SIGCHLD */
        if (pipe(fd) == -1)     /* create pipe */
                err_sys("pipe");
        if ((pid = fork()) == -1)
                err_sys("fork");
        else if (!pid) {        /* child process */
                if (close(fd[0]) == -1)
                       
err_sys("close");
               
if ((n = read(STDIN_FILENO, buf, sizeof(buf))) == -1)
                       
err_sys("read");
                else if (write(fd[1], buf, n) != n)
                       
err_sys("write");
                exit(0);
        }
        if (close(fd[1]) == -1)
                err_sys("close");
        if ((n = read(fd[0], buf, sizeof(buf))) == -1)
                err_sys("read");
        else if (write(STDOUT_FILENO, buf, n) != n)
                err_sys("write");
        exit(0);
}
void signal_handler(void)
{
        struct sigaction act;
        act.sa_handler = sig_chld;
        act.sa_flags = 0;
        if (sigemptyset(&act.sa_mask) == -1)
                err_sys("sigemptyset");
        else if (sigaction(SIGCHLD, &act, NULL) == -1)
                err_sys("sigaction");
}
void sig_chld(int signo)
{
        while(waitpid(-1, NULL, WNOHANG) > 0)
                /* wait child process */;
}
void err_sys(const char *errmsg)
{
        perror(errmsg);
        exit(1);
}
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/39758/showart_343494.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP