23,124
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string.h> //strlen()
#include <fcntl.h> //O_WRONLY O_RDONLY
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h> //mkfifo()
#include <errno.h> //EEXIST
#define FIFOPATH1 "/home/xbq/dev/thread/fifo1"
#define FIFOPATH2 "/home/xbq/dev/thread/fifo2"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
using namespace std;
void* thread1 (void*)
{
int readfd, writefd;
char* buff = (char*)"nihao thread!";
writefd = open(FIFOPATH1, O_WRONLY, 0);
readfd = open(FIFOPATH2, O_RDONLY, 0);
int len = strlen(buff);
write(writefd, buff, len);
read(readfd, buff, 512);
cout << buff << "in thread1" << endl;
close(readfd);
close(writefd);
}
void* thread2 (void*)
{
int readfd, writefd, n;
char* buff;
buff = new char[15];
readfd = open(FIFOPATH1, O_RDONLY, 0);
writefd = open(FIFOPATH2, O_WRONLY, 0);
cout << read(readfd, buff, 13) << endl;
buff[strlen(buff)] = '\0';
cout << buff << "in thread2" << endl;
sprintf(buff, "%s%s", buff, "!!");
cout << buff << "in thread2" << endl;
write(writefd, buff, strlen(buff));
delete buff;
close(readfd);
close(writefd);
}
int main (void)
{
pthread_t tid1, tid2;
cout << pthread_self() << endl;
cout << mkfifo(FIFOPATH1, FILE_MODE);
cout << mkfifo(FIFOPATH2, FILE_MODE);
pthread_create(&tid1, NULL, thread1, NULL);
pthread_create(&tid2, NULL, thread2, NULL);
unlink(FIFOPATH1);
unlink(FIFOPATH2);
return 0;
}