linux的套接口和管道

  创建管道的函数:

#include <unistd.h>
int pipe(int pipefd[2]);

  pipefd[0]代表管道读出端的文件描述符,pipefd[1]代表管道写入端的文件描述符。信息只能从pipefd[0]读出,也只能重pipefd[1]写进。所以实现的通信就是单项的,如果要实现双向通信的话可以采用建立两个管道。不过也可以使用套接字通信。因为套接字的通信是双向的。

  创建管道的例子:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
    int pipefd[2];
    pid_t cpid;
    char buf;
    if (argc != 2) {
      fprintf(stderr, "Usage: %s <string>\n", argv[0]);
      exit(EXIT_FAILURE);
    }
    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }
    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (cpid == 0) {    /* 子进程从管道中读取 */   
        close(pipefd[1]);          /* 读的时候先关闭不用的写进端 */
        while (read(pipefd[0], &buf, 1) > 0)
            write(STDOUT_FILENO, &buf, 1);
        write(STDOUT_FILENO, "\n", 1);
        close(pipefd[0]);
        _exit(EXIT_SUCCESS);
    } else {            /* 父进程向管道写入 argv[1]*/
        close(pipefd[0]);          /* 写之前关闭不用的读出端*/
        write(pipefd[1], argv[1], strlen(argv[1]));
        close(pipefd[1]);          /* Reader will see EOF */
        wait(NULL);                /* Wait for child */
        exit(EXIT_SUCCESS);
    }
}

  

  创建套接口的函数:

#include <sys/types.h> 
#include <sys/socket.h>
int socketpair(int domain, int type, int protocolint " sv [2]);

  sv[2]是指向接收用于引用套接口文件描述符数组的指针。类似于管道中的端点。使用例子:

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>#include <sys/types.h>
#include <sys/socket.h>

int main()
{
    int z;
    int s[2];
    
    z = socketpair(AF_LOCAL,SOCK_STREAM,0,s);
    if (z==-1)
    {
        fprintf(stderr,"%s:socketpair(AF_LOCAL,SOCK_STREAM,0)\n",strerror(errno));
        exit(1);
    }

    printf("s[0]=%d;\n",s[0]);
    printf("s[1]=%d;\n",s[1]);
    return 1;    
}

   下一篇:套接口和I/O通信

posted @ 2012-06-04 08:39  涵曦  阅读(1430)  评论(0编辑  收藏  举报