UNIX IPC-----pipe

来源:互联网 发布:好视通视频会议软件 编辑:程序博客网 时间:2024/06/07 12:39
/******************************************************************************
 * Created:            Nov 11th 2013
 * Author:            freeking
 * Descipation:        unix ipc pipe, C/S struct, parent to be client
 *                     child to be sever, client send a path/file to sever
 *                     and sever reback the file content, the example is
 *                     pratice for pipe,the example is introduced from
 *                     <Interprocess Communcation Volume 2>
 *****************************************************************************/
#include "pipe.h"


void server(int readfd, int writefd)
{
    int fd;
    ssize_t n;
    char buff[MAXLINE] = {0};

    if (0 == (n = read(readfd, buff, MAXLINE)))
    {
        perror("end of file");
        return;
    }

    buff[n] = '\0';
    if ((fd = open(buff, O_RDONLY)) < 0)
    {
        snprintf(buff + n, sizeof(buff) - n, ":can't open , %s\n", strerror(errno));
        n = strlen(buff);
        write(writefd, buff, n);
    }
    else
    {
        memset(buff, 0, MAXLINE-1);
        while((n = read(fd, buff, MAXLINE)) > 0)
        {
            write(writefd, buff, n);
        }    
        close(fd);
    }
}

void client(int readfd, int writefd)
{
    size_t len;
    ssize_t n;
    char buff[MAXLINE];

    if (NULL == fgets(buff, MAXLINE, stdin))
    {
        perror("fgets");
    }

    len = strlen(buff);
    
    if (buff[len - 1] = '\0')
    len--;

    write(writefd, buff, len);
    memset(buff, 0, MAXLINE-1);
    
    while ((n = read(readfd, buff, MAXLINE)) > 0 )
    {
        printf("~~~~%d : %s\n", __LINE__, buff);
        //write(STDOUT_FILENO, buff, n);
    }    
}

int main(int argc, char ** argv)
{
    int pipe1[2], pipe2[2];
    pid_t childpid;

    if (-1 == pipe(pipe1))
    {
        perror("pipe1");
        exit(EXIT_FAILURE);
    }    

    if (-1 == pipe(pipe2))
    {
        perror("pipe1");
        exit(EXIT_FAILURE);
    }    
    
    if(0 == (childpid = fork()))
    {
        close(pipe1[1]);
        close(pipe2[0]);
        server(pipe1[0], pipe2[1]);
        exit(0);
    }    

    close(pipe1[0]);
    close(pipe2[1]);
    client(pipe2[0], pipe1[1]);
    
    waitpid(childpid, NULL, 0);
    return 0;
}

pipe.h
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>


#define MAXLINE 4096

在fedora 17运行结果如下:

[free@freeking Pipe]$ ./a.out
/home/free/test.log
~~~~54 : hello
world
其中test.log 内容是:

[free@freeking Pipe]$ cat /home/free/test.log
hello
world

原创粉丝点击