Roe*_*man 11 linux bash pipe c++ process-substitution
我正在尝试组合一些像这样的程序(请忽略任何额外的包含,这是正在进行的繁重工作):
pv -q -l -L 1 < input.csv | ./repeat <(nc "host" 1234)
Run Code Online (Sandbox Code Playgroud)
重复节目的来源如下所示:
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <string>
inline std::string readline(int fd, const size_t len, const char delim = '\n')
{
std::string result;
char c = 0;
for(size_t i=0; i < len; i++)
{
const int read_result = read(fd, &c, sizeof(c));
if(read_result != sizeof(c))
break;
else
{
result += c;
if(c == delim)
break;
}
}
return result;
}
int main(int argc, char ** argv)
{
constexpr int max_events = 10;
const int fd_stdin = fileno(stdin);
if (fd_stdin < 0)
{
std::cerr << "#Failed to setup standard input" << std::endl;
return -1;
}
/* General poll setup */
int epoll_fd = epoll_create1(0);
if(epoll_fd == -1) perror("epoll_create1: ");
{
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = fd_stdin;
const int result = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd_stdin, &event);
if(result == -1) std::cerr << "epoll_ctl add for fd " << fd_stdin << " failed: " << strerror(errno) << std::endl;
}
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
const char * filename = argv[i];
const int fd = open(filename, O_RDONLY);
if (fd < 0)
std::cerr << "#Error opening file " << filename << ": error #" << errno << ": " << strerror(errno) << std::endl;
else
{
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = fd;
const int result = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event);
if(result == -1) std::cerr << "epoll_ctl add for fd " << fd << "(" << filename << ") failed: " << strerror(errno) << std::endl;
else std::cerr << "Added fd " << fd << " (" << filename << ") to epoll!" << std::endl;
}
}
}
struct epoll_event events[max_events];
while(int event_count = epoll_wait(epoll_fd, events, max_events, -1))
{
for (int i = 0; i < event_count; i++)
{
const std::string line = readline(events[i].data.fd, 512);
if(line.length() > 0)
std::cout << line << std::endl;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我注意到了这一点:
./repeat,一切都按预期工作。我尝试了以下方法:
pv和./repeat使用的管道上的缓冲stdbuf -i0 -o0 -e0,但这似乎不起作用。pv和./repeatwith之间的流时tee stream.csv,这看起来是正确的。strace看到发生了什么,我看到很多单字节读取(正如预期的那样),它们还表明数据正在丢失。我想知道发生了什么?或者我可以做些什么来进一步调查?
mos*_*svy 16
因为nc里面的命令<(...)也会从 stdin 中读取。
更简单的例子:
$ nc -l 9999 >/tmp/foo &
[1] 5659
$ echo text | cat <(nc -N localhost 9999) -
[1]+ Done nc -l 9999 > /tmp/foo
Run Code Online (Sandbox Code Playgroud)
text去哪儿了?通过网猫。
$ cat /tmp/foo
text
Run Code Online (Sandbox Code Playgroud)
你的程序和nc同一个标准输入竞争,并nc得到其中的一部分。