C管道方式通信的demo code
时间: 2023-10-15 20:08:10 浏览: 26
以下是一个使用C语言管道方式通信的简单示例代码:
**管道的创建和使用**
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int fd[2];
pid_t pid;
char buf[256];
// 创建管道
if (pipe(fd) < 0) {
perror("pipe error");
exit(-1);
}
// 创建子进程
if ((pid = fork()) < 0) {
perror("fork error");
exit(-1);
} else if (pid == 0) { // 子进程
close(fd[1]); // 关闭写端
read(fd[0], buf, sizeof(buf)); // 读取数据
printf("child read from pipe: %s\n", buf);
close(fd[0]);
exit(0);
} else { // 父进程
close(fd[0]); // 关闭读端
write(fd[1], "Hello, world!", 13); // 写入数据
wait(NULL); // 等待子进程结束
close(fd[1]);
exit(0);
}
}
```
在上面的示例中,我们使用`pipe`函数创建了一个管道,并使用`fork`函数创建了一个子进程。在子进程中,我们关闭了写端,然后使用`read`函数从管道中读取数据。在父进程中,我们关闭了读端,然后使用`write`函数向管道中写入数据,并使用`wait`函数等待子进程结束。最后,我们关闭了写端,并退出程序。
注意,管道是半双工的,也就是说,同一时间只能有一个进程进行读写操作。如果需要进行双向通信,需要创建两个管道,或使用其他通信方式。