日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux 有名管道pipe,linux 用無名管道pipe和有名管道fifo實現線程間通信

發布時間:2024/9/27 linux 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux 有名管道pipe,linux 用無名管道pipe和有名管道fifo實現線程間通信 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.pipe

用與實現同一個進程下不同線程間的通信(跟IPC進程間通信中的具有血緣關系的進程通信實現方式一樣)

#include

#include

#include

#include

#include

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

#include

#include

#include

#include

#include

#include

#include

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

#include

#include

#include

#include

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

總結

以上是生活随笔為你收集整理的linux 有名管道pipe,linux 用無名管道pipe和有名管道fifo實現線程間通信的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。