请用c语言编写两个Linux下的程序,一个用于读管道,一个用语言写管道。其中读管道的程序里创建管道,并且作为main()函数里的参数由用户输入要写入的内容。读管道的程序会读出用户写到管道的内容,这两个程序采用的是阻塞式对鞋管道模式。
时间: 2024-03-27 16:41:23 浏览: 23
下面是读管道程序的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <errno.h>
int main() {
int fd[2];
pid_t pid;
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程写管道
close(fd[0]); // 关闭读端
char buf[100];
printf("请输入要写入管道的内容:");
scanf("%s", buf);
if (write(fd[1], buf, strlen(buf)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
close(fd[1]); // 关闭写端
exit(EXIT_SUCCESS);
} else { // 父进程读管道
close(fd[1]); // 关闭写端
char buf[100];
if (read(fd[0], buf, sizeof(buf)) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("从管道中读出的内容为:%s\n", buf);
close(fd[0]); // 关闭读端
wait(NULL);
exit(EXIT_SUCCESS);
}
}
```
下面是写管道程序的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <errno.h>
int main() {
int fd[2];
pid_t pid;
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程读管道
close(fd[1]); // 关闭写端
char buf[100];
if (read(fd[0], buf, sizeof(buf)) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("从管道中读出的内容为:%s\n", buf);
close(fd[0]); // 关闭读端
exit(EXIT_SUCCESS);
} else { // 父进程写管道
close(fd[0]); // 关闭读端
char buf[100];
printf("请输入要写入管道的内容:");
scanf("%s", buf);
if (write(fd[1], buf, strlen(buf)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
close(fd[1]); // 关闭写端
wait(NULL);
exit(EXIT_SUCCESS);
}
}
```