线程之间的通信socketpair【学习笔记】【原创】

平台信息:
内核:linux3.1.0
系统:android5.0
平台:tiny4412

作者:庄泽彬(欢迎转载,请注明作者)

说明: 韦老师的安卓视频学习笔记

一、在一个进程中多个线程如何进行通信,主要使用的是socketpair的机制,详细代码如下:

 1 #include <pthread.h>
 2 #include <unistd.h>
 3 #include <stdio.h>
 4 #include <sys/types.h>          /* See NOTES */
 5 #include <sys/socket.h>
 6 
 7 
 8 #define SOCKET_BUFFER_SIZE      (32768U)
 9 #define BUF_MAX_LEN              512
10 
11 void *function_thread (void *arg)
12 {
13     int fd = (int)arg;
14     char buf[BUF_MAX_LEN];
15     int cnt = 0;
16     int len = -1;
17     
18 
19     while(1)
20     {
21         len = sprintf(buf,"Hello,main thread1, cnt = %d\r\n",cnt++);
22         write(fd,buf,len);
23 
24         len = read(fd,buf,BUF_MAX_LEN);
25         buf[len] = '\0';
26         printf("thead1 read:%s\r\n",buf);
27 
28         sleep(5);
29     }
30     
31 
32     return NULL;
33 }
34 
35 
36 int main(int argc,char **argv)
37 {
38     int ret = -1;
39     int sockets[2];
40     int bufferSize = SOCKET_BUFFER_SIZE;
41     pthread_t threadID;
42     char buf[BUF_MAX_LEN];
43     int len = 0;
44     int cnt = 0;
45     int fd = -1;
46 
47     ret = socketpair(AF_UNIX,SOCK_SEQPACKET,0,sockets);
48     if(ret){
49         printf("Error socketpair\r\n");
50         return -1;
51     }
52 
53     setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
54     setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
55     setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
56     setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
57 
58     ret = pthread_create(&threadID,NULL,function_thread,(void *)sockets[1]);
59 
60     fd = sockets[0];
61 
62     while(1){
63         len = read(fd,buf,BUF_MAX_LEN);
64         buf[len] = '\0';
65         printf("Main thread read:%s\r\n",buf);
66 
67         len = sprintf(buf,"Hello,thread1, cnt = %d\r\n",cnt++);
68         write(fd,buf,len);    
69     }
70 
71     return 0;
72 }

编译方法:gcc -o socketpair socketpair.c -lpthread

二、实验现象:

三、如下图所示socketpair的进程号为5919,在这个进程下面有两个线程运行。

 

觉得不错,就给我点小支持吧,蟹蟹

 

posted @ 2017-12-18 23:37  请给我倒杯茶  阅读(697)  评论(0编辑  收藏  举报