编写linux 命名管道c程序例子
时间: 2023-09-03 15:12:03 浏览: 46
以下是一个简单的编写 Linux 命名管道的 C 语言程序例子:
首先,创建一个命名管道文件:
```bash
mkfifo /tmp/myfifo
```
然后编写以下 C 语言代码。该程序将从命名管道读取用户的输入,将其转换为大写字母,然后将结果写回到命名管道,然后再次等待输入。该程序不断循环执行。
```c
#include <stdio.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
int fd;
char *myfifo = "/tmp/myfifo";
char input[256];
char output[256];
/* create named pipe */
mkfifo(myfifo, 0666);
/* open named pipe for reading */
fd = open(myfifo, O_RDONLY);
while(1) {
/* read input from named pipe */
read(fd, input, 256);
/* convert input to uppercase */
int i;
for (i = 0; input[i]; i++) {
output[i] = toupper(input[i]);
}
/* write output to named pipe */
int len = i;
write(fd, output, len);
}
/* close named pipe */
close(fd);
unlink(myfifo);
return 0;
}
```
编译代码:
```bash
gcc -o myfifo myfifo.c
```
运行程序:
```bash
./myfifo
```
现在可以在命令行中使用命名管道与该程序进行通信。例如,可以使用以下命令向命名管道中写入数据:
```bash
echo "hello, world" > /tmp/myfifo
```
程序将读取该输入并将其转换为大写字母,并将结果写回到命名管道文件中。可以使用以下命令从命名管道中读取输出:
```bash
cat /tmp/myfifo
```