如何使用管道在两个程序之间发送一个简单的字符串? [英] How to send a simple string between two programs using pipes?
问题描述
我尝试在网上搜索,但几乎没有任何资源.一个小例子就足够了.
I tried searching on the net, but there are hardly any resources. A small example would suffice.
编辑我的意思是,两个不同的 C 程序相互通信.一个程序应该发送Hi",另一个程序应该接收它.类似的东西.
EDIT I mean, two different C programs communicating with each other. One program should send "Hi" and the other should receive it. Something like that.
推荐答案
一个普通的管道只能连接两个相关的进程.它是由一个进程创建的,当最后一个进程关闭它时它会消失.
A regular pipe can only connect two related processes. It is created by a process and will vanish when the last process closes it.
命名管道,因其行为也称为 FIFO, 可用于连接两个不相关的进程,独立于进程而存在;这意味着即使没有人使用它,它也可以存在.FIFO 是使用 mkfifo()
库函数.
A named pipe, also called a FIFO for its behavior, can be used to connect two unrelated processes and exists independently of the processes; meaning it can exist even if no one is using it. A FIFO is created using the mkfifo()
library function.
writer.c
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write "Hi" to the FIFO */
fd = open(myfifo, O_WRONLY);
write(fd, "Hi", sizeof("Hi"));
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
reader.c
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd;
char * myfifo = "/tmp/myfifo";
char buf[MAX_BUF];
/* open, read, and display the message from the FIFO */
fd = open(myfifo, O_RDONLY);
read(fd, buf, MAX_BUF);
printf("Received: %s
", buf);
close(fd);
return 0;
}
注意:为简单起见,上面的代码省略了错误检查.
这篇关于如何使用管道在两个程序之间发送一个简单的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!