简体   繁体   English

从管道读取时的随机字符

[英]Random characters when reading from pipe

In the following code : 在以下代码中:

    ...
    char *message = "This is the message!";
    ...

    printf("Writing to file descriptor FD[%i] \n", fd[1]);
    write( fd[1], message, strlen(message));
    printf("Reading from file descriptor FD[%i] \n", fd[0]);
    read( fd[0], buffer, strlen(message));
    printf("Message from FD[%i] : \"%s\" .\n", fd[0], buffer);

I get the following output : 我得到以下输出:

 "This is the message!���" .

But if I remove the "!" 但如果我删除“!” from my message, the output doesn't have random characters... Any idea why I get these 3 random characters to appear? 从我的消息,输出没有随机字符...任何想法为什么我会出现这3个随机字符?

When you write your message of length strlen(whatever) , that does not include the terminating NUL character. 当你编写长度为strlen(whatever)消息时,它包括终止NUL字符。 Hence what comes out at the other end is not a C string but rather just a collection of characters. 因此,另一端出现的不是 C字符串,而只是字符集合。

What follows that collection of characters in memory depends entirely upon what was there before you read them from the pipe. 接下来在内存中的字符集是完全依赖于什么在那里你从管道中读取它们之前。 Since it's not a C string (except by possible accident if the memory location following just happened to already contain a NUL), you should not be passing it to printf with an unbounded %s format specifier. 因为它不是C字符串(除非偶然发生的内存位置已经包含NUL,否则可能发生意外),你不应该将它传递给带有无界%s格式说明符的printf

You have two possibilities here. 你有两种可能性。 The first is to send the NUL character along with the data with something like: 第一种是将NUL字符与数据一起发送,例如:

write (fd[1], message, strlen(message) + 1);

or (probably better) use the return value from read which tells you how many bytes were read, something like: 或者(可能更好)使用read的返回值,它告诉你read了多少字节,如:

int sz = read (fd[0], buffer, sizeof(buffer));
// should probably check sz here as well.
printf ("Message from FD[%i] : \"%*s\" .\n", fd[0], sz, buffer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM