gps hal用到的函数4--socketpair

来源:互联网 发布:得力美工刀片价格 编辑:程序博客网 时间:2024/05/16 15:27

socketpair
编辑

目录

1新建一对socket

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

套接字可以用于网络通信,也可以用于本机内的进程通信。由于本机内进程的IP地址都相同,因此只需要进程号来确定通信的双方。非网络通信套接字在Linux环境中的应用很多,最典型的就是Linux的桌面系统——Xserver,其就是使用非网络套接字的方法进行进程之间的通信的。
Linux环境下使用socketpair函数创造一对未命名的、相互连接的UNIX域套接字。
定义
int socketpair(int d, int type, int protocol, int sv[2]);描述
建立一对匿名的已经连接的套接字

1新建一对socket

int sockets[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {
printf("error %d on socketpair\n", errno);
}

2用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);
}
[1]
参考资料
0 0
原创粉丝点击