socketpair
2016-07-15 09:14
435 查看
外文名socketpair性 质科学类 别计算机属 于编程
目录
1新建一对socket2用socketpair实现父子进程双工通信
套接字可以用于网络通信,也可以用于本机内的进程通信。由于本机内进程的IP地址都相同,因此只需要进程号来确定通信的双方。非网络通信套接字在Linux环境中的应用很多,最典型的就是Linux的桌面系统——Xserver,其就是使用非网络套接字的方法进行进程之间的通信的。
Linux环境下使用socketpair函数创造一对未命名的、相互连接的UNIX域套接字。
定义
int socketpair(int d, int type, int protocol, int sv[2]);描述
建立一对匿名的已经连接的套接字
socketpair函数概要如下:
#include <sys/types.h>
#include <sys/socket.h>
int socketpair(int domain, int type, int protocol, int sv[2]);
sys/types.h文件需要用来定义一些C宏常量。sys/socket.h文件必须包含进来定义socketpair函数原型。
socketpair函数需要四个参数。他们是:
套接口的域
套接口类型
使用的协议
指向存储文件描述符的指针
类型参数声明了我们希望创建哪种类型的套接口。socketpair函数的选择如下:
SOCK_STREAM
SOCK_DGRAM
对于socketpair函数,protocol参数必须提供为0。
参数sv[2]是接收代表两个套接口的整数数组。每一个文件描述符代表一个套接口,并且与另一个并没有区别。
如果函数成功,将会返回0值。否则将会返回-1表明创建失败,并且errno来表明特定的错误号。
关于流程。socketpair()函数创建出两个进程,fork()之后这两个进程都会执行主程序中的代码,这个一定要注意!尤其是bind的时候,如果bind两次的话,那就会出错了。一般会在子进程里调用一个带死循环的函数,这样就好了。
新建一对socket
编辑int sockets[2];
if (socketpair(AF_UNIX,
SOCK_STREAM, 0, sockets) < 0) {
printf("error %d on socketpair\n", 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))<0)
err_sys("socketpair");
if ((pid = fork()) == -1)
err_sys("fork");
else if (pid == 0)
{ /* child process */
char s[BUFSIZ];
ssize_t n;
close(sockfd[1]); //write port
if ((n = read(sockfd[0], s, sizeof(s))) <0)
err_sys("read error!\n");
printf("read:%s\n",s);
close(sockfd[0]);
exit(0);
}
else if (pid > 0)
{ /* parent process */
char buf[] = "hello china";
ssize_t n;
close(sockfd[0]); //read port
if((n = write(sockfd[1], buf, sizeof(buf)))<0)
err_sys("write error!\n");
close(sockfd[1]);
wait(NULL);
}
return 0;
}
void err_sys(const char *errmsg)
{
perror(errmsg);
exit(1);
}
相关文章推荐
- 百度云+AI,人工智能走进场景应用时代
- container_of学习
- Leetcode Factorial Trailing Zeroes
- Leetcode Container With Most Water
- 崩溃定位到main方法里怎么办
- Fairpixels向初创公司开源未被采用的Logo
- 373. Find K Pairs with Smallest Sums
- 杭电 1023 Train Problem II
- UVA 573 The Snail
- MainWindows
- Numpy ConfigParser.MissingSectionHeaderError: File contains no section headers.
- Raid技术白皮书(强烈推荐)
- Email邮件头揭密
- codeforces 360 D - Remainders Game
- RAID 概述
- Flex桌面AIR软件日志添加
- a:focus,input:focus{ -webkit-tap-highlight-color:rgba(0,0,0,0); -webkit-user-modify:read-write-plaintext-only;} a选中高亮显示
- Assume the coasting is an infinite straight line. Land is in one side of coasting, sea in the other.
- The working copy"XXX" failed to commit files
- 人工智能的革命:道德可以被编程么?