2011-11-05 85 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

我們確定你的系統有多個核心嗎?如果它只有一個處理器,這些進程將依次運行。