【发布时间】:2011-12-22 13:39:45
【问题描述】:
我正在尝试编写一个 C 程序,它将在整数数组中搜索另一个给定的整数。但是,为了加快搜索速度,搜索是由两个子进程并行完成的。父进程读取整数个数,然后读取数组中的整数。它还读入要搜索的整数。然后它创建两个子进程。第一个子进程搜索数组的前半部分,第二个子进程搜索后半部分。如果找到整数,则其在数组中的索引通过管道发送给父级。如果未找到,则通过管道将 -1 发送给父级。父进程等待两个子进程完成,然后打印相应的消息。
我查阅了一些书籍,这就是我想出的。不过有一个小问题......两个子进程一个接一个地运行,而不是并行运行。我应该做些什么改变?
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/ipc.h>
#include <string.h>
void main ()
{
int i,status,num1,num2,num3,num4, fd1[2], fd2[2];
int a[1000];
char b[5],c[5],d[5],e[5];
pid_t pid1,pid2;
printf("\n\n\nEnter how many numbers - ");
scanf("%d",&num1);
//printf("\n\nEnter the %d numbers below -\n",num1);
for (i=0;i<num1;i++)
{
printf("%d : ",i);
scanf("%d",&a[i]);
}
printf("\n\nEnter the number to search - ");
scanf("%d",&num2);
pipe(fd1);
pipe(fd2);
pid1=fork();
if (pid1==0)
{
printf("this is the child 1\n");
for (i=0;i<(num1/2);i++)
{
if (a[i]==num2)
{
printf("found by process 1\n");
sprintf(b,"%d",i);
sprintf(c,"%d",-1);
write(fd1[1],&b,4);
write(fd2[1],&c,4);
//kill(0,1);
break;
}
printf("%d\n",a[i]);
}
_exit ( EXIT_FAILURE ) ;
}
else
if (pid1>0)
{
pid2=fork();
if (pid2==0)
{
printf("this is the child 2\n");
for (i=(num1/2);i<num1;i++)
{
if (a[i]==num2)
{
printf("found by process 2\n");
sprintf(b,"%d",-1);
sprintf(c,"%d",i);
write(fd1[1],&b,4);
write(fd2[1],&c,4);
//kill(0,1);
break;
}
printf("%d\n",a[i]);
}
_exit(EXIT_FAILURE);
}
}
if (waitpid (pid1, &status, 0)>0 && waitpid (pid2, &status, 0)>0)
{
read(fd1[0],d,4);
read(fd2[0],e,4);
num3=atoi(d);
num4=atoi(e);
if (num3>0) printf("value of i is %d\n",num3);
if (num4>0) printf("value of i is %d\n",num4);
}
}
【问题讨论】:
-
改用线程 (computing.llnl.gov/tutorials/pthreads):您不必处理进程间问题,而且它需要的资源更少(创建一个新进程比创建一个线程更昂贵)。
-
@ern0 我可以试试,但我的教授希望这样做:-(
标签: c operating-system