pipe实例

来源:互联网 发布:nba2k16科比捏脸数据 编辑:程序博客网 时间:2024/05/15 02:06
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>

#include <fcntl.h>

#include <sys/stat.h>


int pipe_execv(const char *psCmd, char *const argv[], int (*fn_line_callback)(char *))
{

    int fd[2];
    pid_t pid;

    if (pipe(fd) < 0)
    {
        return -1;
    }

    if ((pid = fork()) < 0)
    {
        return -1;
    }
    else if (pid > 0)
    {
        /* close write end */
        close(fd[1]);

        int i = 0;
        char buf[1025] = { 0 };
        while (read(fd[0], buf + i, 1) == 1)
        {
            if(buf[i] == '\r' || buf[i] == '\n' || i >= 1024)
            {
                if(0 != fn_line_callback(buf))
                    break;

                memset(buf, 0, 1025);
                i = 0;
            }
            else
                i++;
        }
        close(fd[0]);

        int res = 0;
        if (waitpid(pid, &res, 0) > 0 && res != 0)
        {
            return -1;
        }
    }
    else
    {
        freopen("/dev/null", "r", stdin);
        freopen("/dev/null", "w", stdout);
        freopen("/dev/null", "w", stderr);

        int fd1 = open("/dev/null", O_RDONLY);
        dup2(fd1, 0);
        close(fd1);

        fd1 = open("/dev/null", O_WRONLY);
        dup2(fd1, 1);
        dup2(fd1, 2);
        close(fd1);
        /* close read end */
        close(fd[0]);

#if 0
        if (fd[1] != STDOUT_FILENO)
        {
            if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
            {
                exit(-1);
            }
            close(fd[1]);
        }
#else
        unlink("/tmp/xxxxxxxx.log");
        int myfd = open("/tmp/xxxxxxxx.log", O_CREAT | O_RDWR, 0644);
        printf("open=%d\r\n", myfd);
        int nres = dup2(myfd, STDOUT_FILENO);
        close(myfd);
        printf("dup2=%d\r\n", nres);
#endif

        if (execv(psCmd, argv) == -1)

        {
            exit(-1);
        }

        exit(0);
    }
    return 0;
}

int my_line_callback(char *msg)
{
    printf("my_line_callback:%s\r\n", msg);
    return 0;
}

int main(int argc,char *argv[])
{
    char *const myargv[] = {
            "unzip",
            "-l",
            "/root/download/zips/bugs/test.zip",
            NULL
    };

    int n = pipe_execv("/usr/bin/unzip", myargv, my_line_callback);
    printf("res = %d\r\n", n);

    return EXIT_SUCCESS;
}


原创粉丝点击