C语言 为什么管道的任务是固定的f[0]读f[1]写?

Python010

C语言 为什么管道的任务是固定的f[0]读f[1]写?,第1张

创建管道时返回的是一对文件描述符,fd[0]读,fd[1]写,这个是pipe()函数的固定实现。

要说为什么的话,管道是半双工的,一端写入数据流,一端读出数据流,所以至少需要两个文件描述符,一个读一个写。

你好,

用gets会有越界问题,建议使用fgets。

代码如下:

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

int main(int argc, const char *argv[])

{

pid_t pid

int fd[2]

pipe(fd)

pid = fork()

if (pid == -1) {

perror("fork")

return -1

} else if (pid == 0) { //子进程

char buf[128] = {0}

close(fd[1])//关闭了写,具有读管道权限

read(fd[0], buf, sizeof(buf))

printf("read from parent:%s\n", buf)

close(fd[0])

} else { //父进程

char buf[128] = {0}

close(fd[0])//关闭读,具有写管道权限

gets(buf)

printf("write to child\n")

write(fd[1], buf, sizeof(buf))

close(fd[1])

}

return 0

}

祝你生活愉快。