gpt4 book ai didi

c - 如何使用管道在两个程序之间发送一个简单的字符串?

转载 作者:太空狗 更新时间:2023-10-29 16:14:45 25 4
gpt4 key购买 nike

我尝试在网上搜索,但几乎没有任何资源。一个小例子就足够了。

编辑我的意思是,两个不同的 C 程序相互通信。一个程序应该发送“Hi”,而另一个程序应该接收它。像那样的东西。

最佳答案

一个普通的管道只能连接两个相关的进程。它由一个进程创建,并在最后一个进程关闭时消失。

A named pipe ,因其行为也被称为 FIFO,可用于连接两个不相关的进程并且独立于进程而存在;这意味着即使没有人使用它也可以存在。使用 mkfifo() 创建 FIFO库函数。

例子

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\n", buf);
close(fd);

return 0;
}

注意:为简单起见,上面的代码省略了错误检查。

关于c - 如何使用管道在两个程序之间发送一个简单的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2784500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com