从 main 写入 returns 不同于从 main 调用的函数中的错误?

Write returns different error from main than within a function called from main?

这个问题和标题听起来一样奇怪。我在 MacOSX 的 Assembler 中创建了一个 _ft_write,它会在出现错误时设置 errno。这是我的 _ft_write:

extern ___error
global _ft_write

section .text
    _ft_write:
        mov rax, 0x2000004
        clc
        syscall
        jc error
        ret
    
    error:
        push rax
        call ___error
        pop rbx
        mov [rax], ebx
        mov rax, -1
        ret

用我的 _ft_write 和 C 的原始 write 进行试验,我编写了一个调用 _ft_write 并使用相同参数编写的主程序,并打印了 ERRNO 和发生错误时关联的错误消息。

如果我从 main 中同时调用 _ft_writewrite 并向它们传递一个 NULL 字符串作为第二个参数,两个版本 return ERRNO "14, Bad address ”。如果我通过将所有相同的参数发送到另一个函数来调用它们,然后在该函数中调用 _ft_writewrite - 我的 _ft_write 继续 return “14,地址错误",如你所料,但 C 写 returns "22, Invalid argument"!

所以有了这个程序:

int main(void)
{
    int bytes;
    int *string;

    string = NULL;
    printf("Write Res: %d\n", (bytes = ft_write(1, string, 13)));
    if (bytes < 0)
    {
        printf("My Errno: %d\n", errno);
        perror("[=12=]");
    }
    printf("Write Res: %d\n", (bytes = write(1, string, 13)));
    if (bytes < 0)
    {
        printf("C's Errno: %d\n", errno);
        perror("[=12=]");
    }
    return (0);
}

我得到:

Write Res: -1
My Errno: 14
Bad address
Write Res: -1
C's Errno: 14
Bad address

然而,有了这个程序:

void    testwrite(int fd, char *string, int bytes)
{
    printf("Write Res: %d\n", (bytes = ft_write(fd, string, bytes)));
    if (bytes < 0)
    {
        printf("My Errno: %d\n", errno);
        perror("[=14=]");
    }
    printf("Write Res: %d\n", (bytes = write(fd, string, bytes)));
    if (bytes < 0)
    {
        printf("C's Errno: %d\n", errno);
        perror("[=14=]");
    }
}


int main(void)
{
    testwrite(1, NULL, 13);
    return (0);
}

我得到:

Write Res: -1
My Errno: 14
Bad address
Write Res: -1
C's Errno: 22
Invalid argument

据我所知,没有任何变化 可以解释为什么 C write 应该更改错误消息。有谁知道是怎么回事吗?

您修改 bytes(变成 -1),这样最后一次调用是

write(fd, ..., -1)'