Chinaunix首页 | 论坛 | 博客
  • 博客访问: 47318
  • 博文数量: 33
  • 博客积分: 1301
  • 博客等级: 中尉
  • 技术积分: 335
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 21:06
文章分类
文章存档

2009年(33)

我的朋友

分类: LINUX

2009-07-07 09:52:58

pzpopen:
返回的是文件描述符
 

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>

int pzpopen(char *proc, char *mode) {
    int pipe_d[2];
    pid_t pid;
    
    if(pipe(pipe_d) != 0) {
        fprintf(stderr, "pipe failed!\n");
        return -1;
    }
    if(*mode == 'r' && *(mode + 1) == '\0'){
        pid = fork();
        switch(pid) {
        case -1:
            fprintf(stderr, "fork failed.\n");
            return -1;
        case 0:
            dup2(pipe_d[1], 1);
            close(pipe_d[1]);
            close(pipe_d[0]);
            execl(proc, proc, NULL);
            fprintf(stderr, "execl failed.\n");
            return -1;
        }
        close(pipe_d[1]);
        return pipe_d[0];
    }else if(*mode == 'w' && *(mode + 1) == '\0') {
        pid = fork();
        switch(pid) {
        case -1:
            fprintf(stderr, "fork failed.\n");
            return -1;
        case 0:
            dup2(pipe_d[0], 0);
            close(pipe_d[0]);
            close(pipe_d[1]);
            execl(proc, proc, NULL);
            fprintf(stderr, "execl failed.\n");
            return -1;
        }
        close(pipe_d[0]);
        return pipe_d[1];
    }
    fprintf(stderr, "Unknown mode %s!\n", mode);
    return -1;
}

 
 
阅读(1159) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~