linux 用无名管道pipe和有名管道fifo实现线程间通信

1.pipe

用与实现同一个进程下不同线程间的通信(跟IPC进程间通信中的具有血缘关系的进程通信实现方式一样)

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h>
#include <string.h>
#include <pthread.h>

using namespace std;

void *func(void * fd)
{
    char str[] = "this is write thread!\n";
    write( *(int*)fd, str, strlen(str) );
}

int main()
{
    int fd[2];
    char readbuf[1024];

    if(pipe(fd) < 0)
    {
        printf("pipe error!\n");
    }

    pthread_t tid = 0;
    pthread_create(&tid, NULL, func, &fd[1]);
    pthread_join(tid, NULL);

    sleep(3);

    // read buf from child thread
    read( fd[0], readbuf, sizeof(readbuf) );
    printf("read buf = %s\n", readbuf);

    return 0;
}

2.fifo

用于实现不同进程的线程间通信。不同进程的线程间的通信等同于不同进程间的通信。

读线程

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
void *func(void *fd)
{

   char readbuf[1024];
   read( *(int*)fd, readbuf, 30);
   printf("this is Thread_read!\n");
   printf("Receive message: %s\n", readbuf);
   close(*(int*)fd);
}
int main()
{
    int fd;
    char buff[2048];
    if(mkfifo("fifo", 0666) < 0 && errno != EEXIST)
    {
        printf("create FIFO falied!\n");
        return 0;
    }
    fd = open("fifo", O_RDONLY);
    if(fd < 0)
    {
        printf("open FIFO falied!\n");
    }
    pthread_t tid = 0;
    pthread_create(&tid, NULL, func, &fd);
    pthread_join(tid, NULL);

    //sleep(3);

    return 0;
}
//g++ -o Thread_read Thread_read.cpp -lpthread

写线程

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>
void *func(void * fd)
{

    int wri = write(*(int*)fd, "this is Thread_write", 30);
    if(wri < 0)
    {
        printf("wirte fifo failed!\n");
    }
    close(*(int*)fd);
}
int main()
{

    int fd = open("fifo", O_WRONLY);
    if(fd < 0)
    {
        printf("open fifo failed!\n");
        return 0;
    }
    pthread_t tid = 1;
    pthread_create(&tid, NULL, func, &fd);
    pthread_join(tid, NULL);

   // sleep(3);

    return 0;
}
//g++ -o Thread_write Thread_write.cpp -lpthread

猜你喜欢

转载自blog.csdn.net/creatorx/article/details/80242151