大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
描述
原理
示例代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#define SOCKET_BUFFER_SIZE (32768U)
void *thread_function(void *arg)
{
int len = 0;
int fd = *((int*)(arg));
char buf[500];
int cnt = 0;
/*主线程*/
while(1)
{
/*向main thread线程发送数据*/
len = sprintf(buf, "Hi, main process, cnt = %d", cnt++);
write(fd, buf, len);
/*读数据*/
len = read(fd, buf, 500);
buf[len]='\0';
printf("%s\n",buf);
sleep(5);
}
return NULL;
}
int main()
{
int ret;
int sockets[2];
int bufferSize = SOCKET_BUFFER_SIZE;
pthread_t thread;
ret = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets);
if(ret == -1)
{
printf("socketpair create error!\n");
return -1;
}
/*设置socket描述符的选项*/
setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
/*创建线程1*/
pthread_create(&thread, NULL, thread_function, (void*)(&sockets[1]));
int len = 0;
int fd = sockets[0];
char buf[500];
int cnt = 0;
/*主线程*/
while(1)
{
/*读数据*/
len = read(fd, buf, 500);
buf[len]='\0';
printf("%s\n",buf);
/*项thread线程发送数据*/
len = sprintf(buf, "Hi, thread process, cnt = %d", cnt++);
write(fd, buf, len);
}
return 0;
}
测试结果:
gcc socketpair.c -o socketpair -lpthread
2. 运行,查看结果
test$ ./socketpair
Hi, main process, cnt = 0
Hi, thread process, cnt = 0
Hi, main process, cnt = 1
Hi, thread process, cnt = 1
Hi, main process, cnt = 2
Hi, thread process, cnt = 2
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/181941.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...