现在的位置: 首页 > 综合 > 正文

进程通信:管道(pipe)和socketpair区别

2013年04月19日 ⁄ 综合 ⁄ 共 1580字 ⁄ 字号 评论关闭

管道pipe是半双工的,pipe两次才能实现全双工,使得代码复杂。socketpair直接就可以实现全双工

socketpair对两个文件描述符中的任何一个都可读和可写,而pipe是一个读,一个写

详间代码:

一:pipe实现父子进程全双工通信:

#include <stdlib.h>
#include <stdio.h>

int main ()
{
    int fd1[2],fd2[2];
    pipe(fd1);
    pipe(fd2);
    if ( fork() ) {
        /* Parent process: echo client */
        int val = 0;
        close( fd1[0] );
        close(fd2[1]);
        while ( 1 ) {
            sleep( 1 );
            ++val;
            printf( "parent Sending data: %d\n", val );
            write( fd1[1], &val, sizeof(val) );
            read( fd2[0], &val, sizeof(val) );
            printf( "parent Data received: %d\n", val );
        }
    }
    else {
        /* Child process: echo server */
        int val ;
        close( fd1[1] );
        close(fd2[0]);
        while ( 1 ) {
            read( fd1[0], &val, sizeof(val) );
            printf( "son Data received: %d\n", val );
            ++val;
            write( fd2[1], &val, sizeof(val) );
            printf( "son send received: %d\n", val );
        }
    }
}

输出结果:parent Sending data: 1
son Data received: 1
son send received: 2
parent Data received: 2
parent Sending data: 3
son Data received: 3
son send received: 4

parent Data received: 4

一:soketpair实现父子进程全双工通信:

#include <sys/types.h>
#include <sys/socket.h>

#include <stdlib.h>
#include <stdio.h>

int main ()
{
    int fd[2];
    int r = socketpair( AF_UNIX, SOCK_STREAM, 0, fd );
    if ( r < 0 ) {
        perror( "socketpair()" );
        exit( 1 );
    }   
    if ( fork() ) {
        /* Parent process: echo client */
        int val = 0;
        close( fd[1] );
        while ( 1 ) {
            sleep( 1 );
            ++val;
            printf( "parent Sending data: %d\n", val );
            write( fd[0], &val, sizeof(val) );
            read( fd[0], &val, sizeof(val) );
            printf( "parent Data received: %d\n", val );

        }
    }
    else {
        /* Child process: echo server */
        int val ;
        close( fd[0] );
        while ( 1 ) {
            read( fd[1], &val, sizeof(val) );
            printf( "son Data received: %d\n", val );
            ++val;
            write( fd[1], &val, sizeof(val) );
            printf( "son send received: %d\n", val );
        }
    }
}

输出结果:parent Sending data: 1
son Data received: 1
son send received: 2
parent Data received: 2
parent Sending data: 3
son Data received: 3
son send received: 4

parent Data received: 4

抱歉!评论已关闭.