您的位置:首页 > 编程语言 > C语言/C++

python c++ 交互之管道 pipe

2017-03-16 11:09 1591 查看
linux 下 python c++ 使用管道进行数据通信示例

c++ code writer.cpp

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#define _PATH_ "/tmp/vsd_fifo.pipe"
#define _SIZE_ 100

void Write(){
int ret = mkfifo(_PATH_, 0666 | S_IFIFO);
if (ret == -1){
printf("Failed to create pipe\n");
//return;
}

int fd = open(_PATH_, O_WRONLY);
if(fd <0){
printf("Failed to open\n");
return;
}

char buf[_SIZE_];

while(1){
printf("Please input: \n");
scanf("%s", buf);

int ret = write(fd, buf, strlen(buf) + 1);
if (ret < 0){
printf("Write error");
break;
}

}
close(fd);
}

int main(){
Write();
return 1;
}


Python code reader.py

import os
import time

read_path = "/tmp/vsd_fifo.pipe"

try:
os.mkfifo(read_path)
except OSError, e:
print "mkfifo error", e

rf = os.open(read_path, os.O_RDONLY)
print("os.open finished")

while True:
data = os.read(rf, 1024)
if len(data) == 0:
print("nodata")
time.sleep(1)
print data


运行效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python linux pipe c++