我试图解决有关进程间通信和管道的操作系统书中的一个例子,但我遇到了一些困难。它让我在父母和孩子中找到时间,然后用儿童no1打印出来。一些睡觉的孩子没有2应该打印在儿童no1中找到的时间信息。并且在一些睡觉的父母应该打印在儿童no2中发现的时间信息之后。所以我认为我应该创建3管道,因为我需要传递时间信息3次。我试图设计他们之间的孩子一和孩子二,但我不知道如果我做得正确。另一个问题是,我不知道如何打印当我尝试使用printf%d打印它时,它会给我0任何人都可以帮助我将时间从父母传递给孩子number1并打印出来,以便我可以测试我的程序?下面是我的代码。C/UNIX中两个孩子和父母之间的连续管道
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include<signal.h>
int main(int argc, char** argv)
{
struct timeval t1;
struct timeval t2;
struct timeval t3;
int firstchild,secondchild;
firstchild=fork();
int mypipe[2];
int mypipe2[2];
int mypipe3[2];
if(pipe(mypipe) == -1) {
perror("Pipe failed");
exit(1);
}
if(firstchild == 0) //first child
{
close(STDOUT_FILENO); //closing stdout
dup(mypipe[1]); //pipewrite is replaced.
sleep(3);
close(mypipe[0]); //pipe read is closed.
close(mypipe[1]); //pipe write is closed
}else{
secondchild=fork(); //Creating second child
if(secondchild == 0) //2nd child
{
close(STDIN_FILENO); //closing stdin
dup(mypipe[0]); //pipe read
sleep(6);
close(mypipe[1]); //pipe write is closed.
close(mypipe[0]); //pipe read is closed.
}else{ //Parent
gettimeofday(&t1,NULL);
printf("\n Time is %d ",gettimeofday(&t1,NULL));
sleep(9);
printf("\n Parent:sent a kill signal to child one with id %d ",secondchild-1);
printf("\n Parent:sent a kill signal to child two with id %d ",secondchild);
kill(secondchild-1,SIGKILL);
kill(secondchild,SIGKILL);
exit(1);}}
close(mypipe[0]);
close(mypipe[1]);
return 0;
}
让问题更清楚一点:我认为dup工作正常。我需要的是父母和第一个孩子之间的工作管道,以及用第一个孩子打印时间(父母计算)的方法,以便我可以测试他们两个人的工作并继续编写代码。我打开使用不同风格的管道,只要它工作。使用dup是我在书中看到的东西,因此我使用的东西
你阅读的手册页*您正在使用的任何*功能?你希望从'dup(mypipe [0])获得什么;'?你是否认为回报价值*可能具有某种意义? – EOF
只是一个评论:在标准的英文写作中,在标点符号后面加上一个空格。 ,? ! ; :'。你的文章没有这样做,这使得它很难阅读。 –
@EOF我同意这个问题有点不清楚。但我认为'dup'可以,因为它正在用'mypipe [0]'替换stdin。这是因为'STDIN_FILENO'在'dup'之前关闭了。它依赖于dup使用最小编号的未使用描述符作为新描述符的事实(引用来自手册页)。我也不知道这种技术,并最近在SO上了解到这一点。 – kaylum