Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 socketpair() 完成進程間的全雙工通訊

socketpair() 建立一對已連線的 socket,fork 之後父子各自持有其中一端,天生就是全雙工管道,寫起來比 pipe 直覺。

/*************************************************
 *  description: use socketpair() to implement IPC (全雙工的 IPC)
 *  author: chengshuguang
 **************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

#define child  "wo shi child fa lai de"
#define parent "wo shi parent fa lai de"

int main()
{
    int fd[2];
    int ret;
    ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);

    pid_t pid;
    pid = fork();
    printf("here\n");

    if (pid == 0)
    {
        char buf[20];
        close(fd[0]);
        read(fd[1], buf, 20);
        printf("child: %s\n", buf);

        write(fd[1], child, sizeof(child));
        close(fd[1]);
    }
    else
    {
        char buf[20];
        close(fd[1]);
        write(fd[0], parent, sizeof(child));
        read(fd[0], buf, 20);
        printf("parent: %s\n", buf);
        close(fd[0]);
    }

    sleep(10);
    return 0;
}

幾個實作重點:建立 socketpair 之後要 fork,父子各關掉自己不用那一端,避免讀取端被寫端撐住而永遠收不到 EOF;通訊完成後各自 close。因為是 SOCK_STREAM,資料是位元組流,正式環境要留意 read/write 可能短寫短讀,需搭配迴圈或改用 readn/writen 之類的封裝。

延伸閱讀:解決 mini2440 聲卡全雙工問題,實現同時錄音及播放 https://www.linuxidc.com/Linux/2011-05/36718.htm

Copyright © Linux教程網 All Rights Reserved