前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >管道socket什么意思_pipe是什么意思

管道socket什么意思_pipe是什么意思

作者头像
全栈程序员站长
发布2022-11-04 16:11:06
发布2022-11-04 16:11:06
7.3K00
代码可运行
举报
运行总次数:0
代码可运行

在看Android 输入系统的时候,第一次看到socketpair,发现和管道非常相似。唯他们的区别就是socketpair,默认支持全双工,而pipe是半双工的。他们一样只能用在父子进程或者线程之间通信。

下面分别以socketpair和管道实现全双工通信。

管道实现线程间全双工通信
代码语言:javascript
代码运行次数:0
复制
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#define SIZE 1024
int fd1[2],fd2[2]; //fd1[0]:read,  fd1[1]:write
void *func_thread1(void *arg)
{
char buf[SIZE] = {0};
int cnt = 0;
while(1)
{
sprintf(buf,"hello main %d\n",cnt++);
write(fd1[1],buf,strlen(buf));
int len = read(fd2[0],buf,SIZE);
buf[len] = '\0';
printf("%s",buf);
bzero(buf,SIZE);
sleep(3);
}
return NULL;
}
int main(int agrc,char**argv)
{
pthread_t thread1_t;
/*1. create pipe*/
pipe(fd1);
pipe(fd2);
/*2. create thread1*/
pthread_create(&thread1_t, NULL,
func_thread1, NULL);
char buf[SIZE] = {0};
int cnt = 0;
char * p = buf;
printf("buf[SIZE] sizeof:%d, strlen:%d\n",sizeof(buf),strlen(buf));
printf(" char * p sizeof:%d, strlen:%d\n",sizeof(p),strlen(p));
while(1){
int len = read(fd1[0],buf,SIZE);
buf[len] = '\0';
printf("%s",buf);
bzero(buf,SIZE);
sprintf(buf,"hello thread %d\n",cnt++);
write(fd2[1],buf,strlen(buf));  
sleep(3);
}
return 0;
}
Socketpair实现线程间全双工通信
代码语言:javascript
代码运行次数:0
复制
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#define SIZE 1024
void *func_thread1(void *arg)
{
char buf[SIZE] = {
0};
int cnt = 0;
int fd = (int)arg;
while(1)
{
sprintf(buf,"hello main %d\n",cnt++);
write(fd,buf,strlen(buf));
int len = read(fd,buf,SIZE);
buf[len] = '\0';
printf("%s",buf);
bzero(buf,SIZE);
sleep(3);
}
return NULL;
}
int main(int agrc,char**argv)
{
int fd[2];
pthread_t thread1_t;
/*1. create socketpair*/
int ret = socketpair(AF_UNIX,SOCK_STREAM,0,fd);
if(ret < 0){
perror("socketpair");
exit(-1);
}
/*2. create thread1*/
pthread_create(&thread1_t, NULL,
func_thread1, fd[1]);
char buf[SIZE] = {
0};
int cnt = 0;
char * p = buf;
while(1){
int len = read(fd[0],buf,SIZE);
buf[len] = '\0';
printf("%s",buf);
bzero(buf,SIZE);
sprintf(buf,"hello thread %d\n",cnt++);
write(fd[0],buf,strlen(buf));   
sleep(3);
}
return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/181914.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年10月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 管道实现线程间全双工通信
  • Socketpair实现线程间全双工通信
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档