array search, multiple processes

I want to search for a key in an array, dividing it to k parts, and using k child processes.
But my code has problem...
int main ()
   int k=2;//number of childs
   int N=10;//array length
   int A[]={2,6,-8,9,10,1,6,3,7,4};
   int i;int key=1;//we search key in array A
   int position=-1;
   for (i=1;i<=k;i++){//create k childs
       int pid=fork();
       if (pid==0){//child
          int start=(N/k)*i;
          int end=start+(N/k);
          int j;
          printf("\nchild%d pid %d ppid %d\n",i,getpid(), getppid());
          for(j=start; j<end; j++){
                       if (A[j]==key) {position=j;printf("position=%d\n",position);break;}
          exit(0);//child terminates
      else if (pid>0){//parent         
          printf("\nparent pid %d \n",getpid());
return 0;


Open in new window

Who is Participating?
phoffricConnect With a Mentor Commented:
For one thing you start at i=1
then start=(N/k)*i is never 0
what problem does it have?
did you want the children to run simultaneously?
Also, when doing a fork (or any library call that can err), you should always test for an error.
Here is an example that illustrates how to check for errors:
In each child, you should print out the start and end values to see another problem.

This was not a problem; but here is a nice thing to do so that you can initialize the array without having to modify the size.
   int A[]={2,6,-8,9,10,1,6,3,7,4};  
   int N=sizeof(A)/sizeof(A[0]);//array length

Open in new window

Also, remember that arrays run from 0 .. N-1 where N is the number of elements in the array.
Take a look at this link to see how to wait for multiple children:

To test for error (which I always recommend doing for any library call):
     if (!WIFEXITED(pidStatus) || WEXITSTATUS(pidStatus) != 0) ...
All Courses

From novice to tech pro — start learning today.