要说为什么的话,管道是半双工的,一端写入数据流,一端读出数据流,所以至少需要两个文件描述符,一个读一个写。
你好,
用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
}
祝你生活愉快。