[英]read() write() into pipe() via dup2() with stdin and stdout
I need to simulate the Linux command " cal -3
", which displays the calendar for 3 months side by side. 我需要模拟Linux命令“
cal -3
”,该命令并排显示3个月的日历。 What I need right now is to get my implementation, using pipes, working. 我现在需要的是使用管道来实现我的实现。 I've been told that I can't use
fork()
, but rather I should use dup2()
, write()
, read()
and close()
to call system("myCustomCommand")
three times. 有人告诉我不能使用
fork()
,而应该使用dup2()
, write()
, read()
和close()
来调用system("myCustomCommand")
3次。 Right now my program does not display the calendar side by side. 现在,我的程序没有并排显示日历。
I am trying to use pipes and ran into a problem. 我试图使用管道并遇到问题。 Here is what I am trying:
这是我正在尝试的:
int pfd[2];
int p; //for pipe
int d; //for dup2
const int BSIZE = 256;
char buf[BSIZE];
p = pipe(pfd);
if (p == -1) { perror("pipe"); exit(EXIT_FAILURE); }
if (p == 0)
{
d = dup2(pfd[1], 0);
close(pfd[1]);
nbytes = read (pfd[1], buf , BSIZE);
close(pfd[0]);
exit(EXIT_SUCCESS);
}
else
{
close(pfd[0]);
write(pfd[1], "test\n", BSIZE);
close(pfd[1]);
exit(EXIT_SUCCESS);
}
Unfortunately, this code does not display anything. 不幸的是,此代码不显示任何内容。 Could you please help me out with this?
你能帮我这个忙吗?
This looks like homework, so I'll give you a way to approach the problem: 这看起来像是作业,所以我将为您提供解决问题的方法:
Why not using FILE *fp = popen("my command", "r");
为什么不使用
FILE *fp = popen("my command", "r");
, reading the output into an array of strings, repeating that three times and concatenating arrays properly? ,将输出读取到字符串数组中,重复三遍并正确连接数组?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.