进程间通信之socketpair

博客介绍了socketpair这种进程间通信方式,指出它与管道和命名管道相比,具有全双工的特点,且可用于任意两个进程之间的通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

socketpair是进程间通信的一种方式。

API:

int socketpair(int domain, int type, int protocol, int sv[2]);

DEMO:

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

#define MAXLINE 4096

int main(int argc, char **argv) {
    int fd[2];
    pid_t pid;
    char line[MAXLINE];
    int n;
    
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
        perror("socketpair error");
        exit(1);
    }
    if ( (pid = fork()) < 0) {
        perror("fork error");
        exit(1);
    } else if (pid > 0) {
        close(fd[1]);
        write(fd[0], "hello world\n", 12);
        char tmp[MAXLINE];
        read(fd[0], tmp, MAXLINE);
        printf("echo is: %s\n", tmp);
    } else {
        close(fd[0]);
        n = read(fd[1], line, MAXLINE);
        write(STDOUT_FILENO, line, n);
        char tmp[] = "world says hi";
        write(fd[1], tmp, strlen(tmp));
    }
    exit(0);
}

管道命名管道相比,socketpair有以下特点:

1. 全双工

2. 可用于任意两个进程之间的通信

转载于:https://www.cnblogs.com/gattaca/p/6548098.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值