简体   繁体   English

从名为 pipe 的非阻塞读取给出 Ubuntu 中的 EFAULT (14)

[英]reading from non-blocking named pipe gives EFAULT (14) in Ubuntu

The code below returns EFAULT (errno == 14).下面的代码返回 EFAULT (errno == 14)。 I would appreciate help figuring out why.我会很感激帮助找出原因。

I've also tried to implement the code using select() but still got the same error code.我也尝试使用 select() 实现代码,但仍然得到相同的错误代码。

I've got very similar code running on Python with no issues.我在 Python 上运行了非常相似的代码,没有任何问题。

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



int read_fail1(int fd)
{
    int n;
    char buf[500];

    for (;;)
    {
        buf[strlen(buf)-1] = 0;
        n = read(fd, buf, strlen(buf)-1);
        
        if (n == -1)
        {
            if (errno == EFAULT)
            {
                fprintf(stderr, "EFAULT");
                return 42;
            }
        }
        else if (n > 0)
        {
            fprintf(stderr, "%s", buf);
        }

    }
}



int main(int argc, const char *argv[])
{
    const char *myfifo = "pipeMUD";
  
    mkfifo(myfifo, 0666); 
  
    int fd = open(myfifo, O_RDWR | O_NONBLOCK);

    if (fd <= 0)
        return 42;

    read_fail1(fd);

    return 0;
}

POST ANSWER EDIT:发布答案编辑:

As mentioned in the post linked below, if an invalid address is passed to the kernel, it throws the EFAULT.如下面链接的帖子中所述,如果将无效地址传递给 kernel,则会引发 EFAULT。 I guess that on Linux, based on the above code, passing a 0 length count parameter to read() will also cause EFAULT to be retured.我猜想在 Linux 上,基于上面的代码,将一个 0 长度的计数参数传递给 read() 也会导致 EFAULT 被返回。

unix socket error 14: EFAULT (bad address) unix 套接字错误 14:EFAULT(错误地址)

This line:这一行:

buf[strlen(buf)-1] = 0;

buf if a local variable, and thus is not initialized in C. buf如果是局部变量,因此未在 C 中初始化。 strlen looks for '\0' (null character) value, and thus will give unpredictable result on uninitialized array. strlen查找 '\0' (空字符)值,因此会在未初始化的数组上给出不可预测的结果。

But, as long as you declare buf statically as you do, you can use sizeof instead.但是,只要像您一样静态声明buf ,就可以改用sizeof Though it would be a better practice to use a macro instead:尽管改用宏会是一种更好的做法:

#define READ_BUFFER_SIZE 500

char buf[READ_BUFFER_SIZE];
n = read(fd, buf, READ_BUFFER_SIZE - 1);

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

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