2011-11-05 163 views
0

我tryimg写一个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); 
} 

} 
+0

改为使用线程(https://computing.llnl.gov/tutorials/pthreads/):您不必处理进程间问题,而且需要的资源更少(创建新进程比创建线)。 – ern0

+0

@ ern0我试过,但我的教授希望这样做:-( – rits

回答

1

你的代码很好,但请记住,处理器时间是在相当大的切片中给出的。也就是说,在其他进程甚至接收到处理器时间片之前,通常会完成一个短计算。将几个调用sleep插入到循环中,您将看到并发性。

0

我们确定你的系统有多个核心吗?如果它只有一个处理器,这些进程将依次运行。