使用管道

时间:2017-11-11 22:40:04

标签: c python-3.x pipe

嗨所以我试图与C"服务器进行通信"从python到管道,我得到一个UnicodeDecodeError,我不知道为什么,这里是两个代码:

"服务器"在C:

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

#define MAX_BUF 1024

int main(){
    int fd;
        char * myfifo = "/tmp/myfifo";
    char *menu;

    // create FIFO pipe
        mkfifo(myfifo, 0666);

    while(1){


            // open the pipe for writing, and send a message to the client
            fd = open(myfifo, O_WRONLY);
            //fd = open(myfifo, O_NONBLOCK);
            //fd = open(myfifo, O_RDONLY);
        menu = "conectado a servidor con PIPE Escribe 'exit' para desconexión\n";
            write(fd, menu, 1000);
            close(fd);
        sleep(10);
        // open the pipe for reading, and print the message received from the client
        char buf[MAX_BUF];
            fd = open(myfifo, O_RDONLY);    
            read(fd, buf, MAX_BUF);
        if(strcmp("exit",buf)==0){
            break;
        }else{  
            printf("Recibido: %s\n", buf);
        }           
            close(fd);
    }

    // remove the pipe
        unlink(myfifo);

        return 0;
}

和&#34;客户&#34;在python:

import os,sys,errno,pipes


def Prueba():
    print ("creating pipe and connecting...")
    p = pipes.Template()
    fifo = "/tmp/myfifo"
    f = p.open(fifo,'r')
    try:
        algo = f.read()
    finally:
        f.close()
    print (algo)

我的错误是:

algo = f.read()
  File "/usr/lib/python3.5/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 97: invalid start byte

对此代码的任何帮助/评论/建议都将受到欢迎,提前感谢

1 个答案:

答案 0 :(得分:1)

你的文字后面有垃圾,因为你发送的内容是这样的:

        write(fd, menu, 1000);

例如,1000应该strlen(menu) + 1发送以空字符结尾的字符串。