请输入您要查询的百科知识:

 

词条 socketpair
释义

套接字可以用于网络通信,也可以用于本机内的进程通信。由于本机内进程的IP地址都相同,因此只需要进程号来确定通信的双方。非网络通信套接字在Linux环境中的应用很多,最典型的就是Linux的桌面系统——Xserver,其就是使用非网络套接字的方法进行进程之间的通信的。

Linux环境下使用socketpair函数创造一对未命名的、相互连接的UNIX域套接字。

定义

int socketpair(int d, int type, int protocol, int sv[2]);描述

建立一对匿名的已经连接的套接字

新建一对socket

int sockets[2];

if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {

printf("error %d on socketpair\", errno);

}

用socketpair实现父子进程双工通信

#include <sys/socket.h>

#include <netinet/in.h>

#include <stdlib.h>

#include <stdio.h>

#include <unistd.h>

void err_sys(const char *errmsg);

int main(void)

{

int sockfd[2];

pid_t pid;

if ((socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd)) == -1)

err_sys("socketpair");

if ((pid = fork()) == -1)

err_sys("fork");

else if (pid == 0) { /* child process */

char buf[] = "hello china", s[BUFSIZ];

ssize_t n;

close(sockfd[1]);

write(sockfd[0], buf, sizeof(buf));

if ((n = read(sockfd[0], s, sizeof(s))) == -1)

err_sys("read");

write(STDOUT_FILENO, s, n);

close(sockfd[0]);

exit(0);

} else if (pid > 0) { /* parent process */

char buf[BUFSIZ];

ssize_t n;

close(sockfd[0]);

n = read(sockfd[1], buf, sizeof(buf));

write(sockfd[1], buf, n);

close(sockfd[1]);

exit(0);

}

}

void err_sys(const char *errmsg)

{

perror(errmsg);

exit(1);

}

随便看

 

百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。

 

Copyright © 2004-2023 Cnenc.net All Rights Reserved
更新时间:2025/3/25 16:35:17