我不太清楚如何正确使用pipe()在两个进程之间传递整数值。
在程序中,我首先创建了一个管道,然后分叉它。我是否有“两个”管道呢?
从我的理解来看,这是我的任务。父进程通过一个for循环检查一个整数值“i”,执行某个操作,增加计数器,并将值保存到数组中。每次检查后,父进程应该通过管道传递一个整数值“i”给子进程。子进程然后使用该整数值,对其进行一些检查,并应该增加计数器并将结果保存在[共享?] 数组中。最终,子进程应该将其最终计数返回给父进程,然后父进程打印出两个计数和“共享”数组。
-> 我不确定是否需要一个共享的数组或完全保存结果。作业模糊不清,我正在等待教授的回复。另外,我是否可以在进程之间共享一个数组?这对我来说听起来像是一些问题的开始。
-> 这里是我的问题: 第一,如何使用管道传递整数?我只见过用于字符数组的管道,以前的答案似乎认为这不可能或不合法..?我不确定。我找不到任何解决方案。
-> 如何使用单向管道将整数传递给子进程?并让子进程返回一些东西?我不确定如何区分两个管道。我“知道”[或认为我知道]我必须关闭每个管道的一个未使用部分以避免“某些模糊问题”。
抱歉问这么弱智的问题;我在这门课中还没有学过进程(除了fork)或管道(根本没有)- 所以我真的不知道从哪里开始!
以下是我的代码的部分内容 - 它不太好看,也不工作,而且我不指望它能工作。这只是一个shell占位符。一旦我弄清楚了如何使用管道 - 我可能会让代码有意义。
int main(void)
{
int fd[2];
pid_t childpid;
pid_t parentpid;
int i;
int threecount = 0;
int fivecount = 0;;
int results [MAXSIZE];
parentpid = getpid(); //Get current process ID number
pipe(fd);
childpid = fork();
if(childpid == 0){
close(fd[0]); //Closing this for some other reason
}
int j = 0;
if(childpid > 0)
close(fd[1]); //Closing this for some reason
if( childpid == -1 )
{
perror("Failed to fork\n");
return 1;
}
if (childpid > 0)
{
for(i = 1; i < MAXSIZE;i++)
{
if(i % 5 == 0)
{
fivecount++;
i = results[j];
j++;
wait(NULL);
}
}
}
else if (childpid == 0)
{
if(i % 3 == 0) //This i here should probably be the i value above, piped to the child
{
threecount++;
i = results[j]; //This should be part of th pipe
j++; //Trying to keep count of that shared array, not really the right way to do it though.
}
}
printf("%d %d \n", fivecount,threecount);
return 0;
}