带有管道的简单主函数中的错误文件号

Bad file number in simple main function with pipes

我在 C 世界里还是个孩子,我正在做一些 "system" 编程以做一些练习,这时我偶然发现了一些明显的错误,但我找不到问题所在申请

这是代码

const int __WRITE_ERROR = 44;
const int __READ_ERROR = 43;

const int READ = 0;
const int WRITE = 1;
const int MAX = 1024;

int main(int argc, char *argv[]) {
    int fd[2], n;
    char buff[MAX];

    if(pipe(&fd[2]) < 0)
        exit(__PIPE_ERROR);
    printf("Hello, from pipe: write: %d and read: %d\n", fd[WRITE], fd[READ]);

    if(write(fd[WRITE], "Hello World\n", 12) != 12) {
        printf("Explanation: %i", errno); // <- constantly comes here with errno 9 for some reason.
        exit(__WRITE_ERROR);
    }

    if((n = read(fd[READ], buff, MAX)) != 0)
        exit(__READ_ERROR);

    write(1, buff, n);
    exit(0);
}

你能帮帮我吗,因为我 运行 没办法了,谢谢。

有问题:

if (pipe(&fd[2]) < 0)

应该改为:

if (pipe(fd) < 0)

前者传递给pipe()数组fd(即&fd[2])边界后一个元素的地址。


此外,read()write() return 分别是读取或写入的字节数。但是,如果发生错误,-1 将 return 用于两个函数。

正如有人已经指出的第一个错误是

if (pipe(&fd[2]) < 0) 

必须

if (pipe(fd) < 0)

由于条件错误,读取失败

if((n = read(fd[READ], buff, MAX)) != 0)

应该

if((n = read(fd[READ], buff, MAX)) <= 0)