简体   繁体   English

通过带有stdin和stdout的dup2()将read()write()写入pipe()

[英]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: 这看起来像是作业,所以我将为您提供解决问题的方法:

  1. Get it working with one calendar, reading in one line at a time and writing to stdout. 使它与一个日历一起使用,一次读一行并写入stdout。
  2. Now store each line in an array of strings, and print out each line once you get the whole calendar read in. 现在,将每一行存储在字符串数组中,并在读完整个日历后打印出每一行。
  3. Get it working with three calendars, storing the results of each into three separate arrays of strings, then printing out all three (not next to each other). 使它与三个日历一起使用,将每个结果存储到三个单独的字符串数组中,然后打印出所有三个(不相邻)。
  4. Instead of printing out all of the lines from one calendar, then all of the lines from the next calendar, etc., print out the first line from each calendar, then the second line from each calendar, etc. 而不是打印出一个日历的所有行,而是打印下一个日历的所有行,等等,而是打印出每个日历的第一行,然后打印出每个日历的第二行,依此类推。
  5. Fiddle around with the formatting until it looks right. 摆弄格式,直到看起来正确为止。

Displaying three calendars at once has nothing to do with forking processes and really you don't need to get in to pipes and stuff. 一次显示三个日历与分叉过程无关,实际上,您不需要介入管道和其他工作。

What you want to use is the ncurses library to do special control of your output. 您要使用ncurses库对输出进行特殊控制。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM