在看Android 輸入系統的時候,第一次看到socketpair,發現和管道非常相似。唯他們的差別就是socketpair,預設支援全雙工,而pipe是半雙工的。他們一樣隻能用在父子程序或者線程之間通信。
下面分别以socketpair和管道實作全雙工通信。
管道實作線程間全雙工通信
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#define SIZE 1024
int fd1[],fd2[]; //fd1[]:read, fd1[]:write
void *func_thread1(void *arg)
{
char buf[SIZE] = {0};
int cnt = ;
while()
{
sprintf(buf,"hello main %d\n",cnt++);
write(fd1[],buf,strlen(buf));
int len = read(fd2[],buf,SIZE);
buf[len] = '\0';
printf("%s",buf);
bzero(buf,SIZE);
sleep();
}
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 = ;
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(){
int len = read(fd1[],buf,SIZE);
buf[len] = '\0';
printf("%s",buf);
bzero(buf,SIZE);
sprintf(buf,"hello thread %d\n",cnt++);
write(fd2[],buf,strlen(buf));
sleep();
}
return ;
}
Socketpair實作線程間全雙工通信
#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] = {};
int cnt = ;
int fd = (int)arg;
while()
{
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();
}
return NULL;
}
int main(int agrc,char**argv)
{
int fd[];
pthread_t thread1_t;
/*1. create socketpair*/
int ret = socketpair(AF_UNIX,SOCK_STREAM,,fd);
if(ret < ){
perror("socketpair");
exit(-);
}
/*2. create thread1*/
pthread_create(&thread1_t, NULL,
func_thread1, fd[]);
char buf[SIZE] = {};
int cnt = ;
char * p = buf;
while(){
int len = read(fd[],buf,SIZE);
buf[len] = '\0';
printf("%s",buf);
bzero(buf,SIZE);
sprintf(buf,"hello thread %d\n",cnt++);
write(fd[],buf,strlen(buf));
sleep();
}
return ;
}