【发布时间】:2020-10-17 02:05:41
【问题描述】:
我们有一个用 c 编写的应用程序,它向用 c# 编写的应用程序发送事件/通知。两个应用程序都在同一台 linux 计算机上运行。
C 应用程序:
C 应用程序是Asterisk,我们修改了源代码(它是开源的),以便它可以向我们的 dotnet 控制台应用程序发送事件。我们目前发送事件的方式只是将文本附加到文件中。例如,这是我们发送新对等点(ip-phone)连接的事件的方式:
// place this on chan_sip.c
// Example: 1-LN-48T6-E3C5-OFWT|10.0.0.103:5868|189.217.18.244|10216|Z 3.9.32144 r32121
if(!ast_sockaddr_isnull(&peer->addr))
{
// lock
ast_mutex_lock(&some_lock);
// write to file
FILE *pFile;
pFile=fopen("/var/log/asterisk/peer-subscriptions.txt", "a");
if(pFile==NULL) { perror("Error opening file."); }
else {
fprintf(pFile,"%s|%s|%s|%s|%s\n",
/* 1-LN-48T6-E3C5-OFWT */ peer->name,
/* 10.0.0.103:5868 */ pvt->initviasentby,
/* 189.217.18.244 */ ast_sockaddr_stringify_addr(&peer->addr),
/* 10216 */ ast_strdupa(ast_sockaddr_stringify_port(&peer->addr)),
/* Z 3.9.32144 */ peer->useragent
// Other:
// peer->fullcontact, // sip:1-LN-48T6-E3C5-OFWT@189.217.18.244:10216;rinstance=8b4135488f735cbf;transport=UDP
// pvt->via // SIP/2.0/UDP 54.81.92.135:20001;branch=z9hG4bK58525e18;rport
);
}
fclose(pFile);
// unlock
ast_mutex_lock(&some_lock);
}
C# 应用程序 c# 应用程序是一个控制台应用程序,它打开该文件以读取没有什么花哨的事件。
所以基本上 C 应用程序正在写入文本文件,而 C# 应用程序正在从该文本文件中读取。
问题
随着时间的推移,文件会变大,我不想麻烦地截断它并创建另一个锁,同时它会截断等... 使用mkfifo 似乎正是我想要的。由于我对 linux 比较陌生,我想确保在使用它之前了解它是如何工作的。我知道 C 的基础知识(我不是专家),并且希望使用更有效的方法。你们推荐使用 mkfifo、namedpipes 还是 tcp?
示例 1:
mkfifo 只需要几行就可以很好地工作,但是当我尝试阅读很多行时它会失败。举个例子:
mkfifo foo.pipe # create a file of type pipe
在终端一写入该文件
echo "hello world" >> foo.pipe # writes hello world AND blocks until someone READS from it
我在一个单独的终端上:
cat foo.pipe # it will output hello world. This will block too until someone WRITES to that file
示例 2:
mkfifo foo.pipe # create a file of type pipe. If it exists already do not create again
在终端 1 上从该文件读取
tail -f foo.pipe # similar to cat foo.pipe but it keeps reading
在终端 2 上写入该文件但有很多数据
echo ~/.bashrc >> foo.pipe # write the content of file ~/.bashrc to that file
这不起作用,控制台上只显示该文件的几行。 如何正确使用 mkfifo 来阅读所有文本?我应该使用不同的方法并改用 tcp 吗?
【问题讨论】: