【问题标题】:Why using named pipes gives random chars in C?为什么使用命名管道会在 C 中给出随机字符?
【发布时间】:2017-08-05 14:57:33
【问题描述】:

我在 Linux 中使用mkfifo 命令。 这是我的代码:

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

int main(){
    char* filename = "myf";
    int res = mkfifo(filename, 0777); 
    pid_t x = fork();
    if(x){
        char buff[4];
        res = open("myf", O_RDONLY);
        if(res == -1){
            printf("problem opening fifo\n");
        }
        while(read(res, buff, 4)){
            printf("Father:  %s\n", buff);
        }
    }
    else{
        int toFath = open (filename, O_WRONLY);
        char buff [4];
        strcpy(buff, "hi");
        write(toFath, buff, strlen(buff));
        strcpy(buff, "bye");
        write(toFath, buff, strlen(buff));
        close(toFath);
    }
    return 0;
}

但它会打印:

Father:  hi@
Father:  bye

我不明白为什么会有这些我没有写的字符 (@)。我知道strcpy 复制带有空终止符的字符串,所以当父亲打印时它应该在空终止符处停止,为什么不呢?

【问题讨论】:

  • 然后试试 strlen+1。

标签: c pipe


【解决方案1】:

strlen(buff) 返回 3,因此 write() 会输出 buff 的前 3 个字节

【讨论】:

  • 考虑edit这个答案来解释为什么 strlen(buff)返回3。
  • 没有。给定strcpy(buff, "hi");,strlen( buff ) 返回 2,而不是 3。
【解决方案2】:

第一个char buff[4] 未初始化。因此,read(res, buff, 4) 可能会返回一个不是 '\0' 终止的 buff。

修复,使用 char buff[4] = {0} 初始化第一个 buff。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多