#include <pthread.h>
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#define MAX_BUF_SIZE (500)
void *function_thread1(void *arg)
{
int fd = *(int*)arg;
char buf[MAX_BUF_SIZE + 1];
int cnt = 0;
while(1)
{
/* write to main thread*/
sprintf(buf,"say hello to main thread %d \r\n",cnt++);
write(fd,buf,MAX_BUF_SIZE);
/*read fron main thread*/
memset(buf,0,sizeof(buf));
read(fd,buf,MAX_BUF_SIZE);
printf("%s",buf);
/*休眠*/
sleep(5);
}
return NULL;
}
int main()
{
int sockets[2];
pthread_t threadId;
int ret = 0;
int mainFd;
int threadFd;
int cnt = 0;
char buf[MAX_BUF_SIZE + 1];
/*创建socketpair*/
ret = socketpair(AF_UNIX, SOCK_STREAM,0, sockets);
if(ret != 0)
{
perror("can't create socketpair: ");
return -1;
}
threadFd = sockets[0];
mainFd = sockets[1];
ret = pthread_create(&threadId,NULL,function_thread1,&threadFd);
if(ret != 0)
{
perror("can't create thread: ");
return -1;
}
while(1)
{
/*read fron thread1*/
memset(buf,0,sizeof(buf));
read(mainFd,buf,MAX_BUF_SIZE);
printf("mainthread read:%s",buf);
/* write to thread1*/
sprintf(buf,"say hello to thread1 %d \r\n",cnt++);
write(mainFd,buf,MAX_BUF_SIZE);
}
return 0;
}
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#define MAX_BUF_SIZE (500)
void *function_thread1(void *arg)
{
int fd = *(int*)arg;
char buf[MAX_BUF_SIZE + 1];
int cnt = 0;
while(1)
{
/* write to main thread*/
sprintf(buf,"say hello to main thread %d \r\n",cnt++);
write(fd,buf,MAX_BUF_SIZE);
/*read fron main thread*/
memset(buf,0,sizeof(buf));
read(fd,buf,MAX_BUF_SIZE);
printf("%s",buf);
/*休眠*/
sleep(5);
}
return NULL;
}
int main()
{
int sockets[2];
pthread_t threadId;
int ret = 0;
int mainFd;
int threadFd;
int cnt = 0;
char buf[MAX_BUF_SIZE + 1];
/*创建socketpair*/
ret = socketpair(AF_UNIX, SOCK_STREAM,0, sockets);
if(ret != 0)
{
perror("can't create socketpair: ");
return -1;
}
threadFd = sockets[0];
mainFd = sockets[1];
ret = pthread_create(&threadId,NULL,function_thread1,&threadFd);
if(ret != 0)
{
perror("can't create thread: ");
return -1;
}
while(1)
{
/*read fron thread1*/
memset(buf,0,sizeof(buf));
read(mainFd,buf,MAX_BUF_SIZE);
printf("mainthread read:%s",buf);
/* write to thread1*/
sprintf(buf,"say hello to thread1 %d \r\n",cnt++);
write(mainFd,buf,MAX_BUF_SIZE);
}
return 0;
}