I want to search a matrix for an int value passed as argument, and i want to do it using fork. It's supposed to search several lines at the same time (each different child will search a different line. However the way i'm doing it a child searches the 1st line, then another child searches the 2nd line, and so on, but they're not doing it at the same time.. The 2nd child waits for the 1st to end its search before starting. I guess i'm not using wait and exit as i should be. Here's my code so far:
int main(int argc, char **argv){
int p,i,j,val,status;
int mat[6][100];
//matrix
for(i=0;i<6;i++){
for(j=0;j<100;j++){
mat[i][j]=5;
}
}
mat[1][96]=2;
if (argc<2) {
printf("Insert num\n");
exit(-1);
}
val=atoi(argv[1]);
for(i=0;i<6;i++){
p=fork();
if (p==0){
for(j=0;j<100;j++){
printf("n:[%d][%d] -> pID: %d, ppID: %d\n",i,j,getpid(),getppid()); //This line is to see how my search is being done.
if (mat[i][j]==val){
printf("Found at line %d, Column %d\n",i,j);
_exit(i);
}
}
}
else{
wait(&status);
exit(i);
}
}
return 0;
}
Thanks.
You'll want to wait outside the loop. Otherwise, the processes will run serially. Something like this should work:
for(int i = 0; i < 6; i++)
{
switch(fork())
{
case 0: /* child */
/* Search */
for(j = 0; j < 100; j++)
{
printf("n:[%d][%d] -> pID: %d, ppID: %d\n",i,j,getpid(),getppid());
if (mat[i][j] == val)
{
printf("Found at line %d, Column %d\n", i, j);
_exit(i);
}
}
exit(0);
case -1:
perror("fork");
exit(1);
default: /* parent */
/* do stuff, but don't wait() or terminate */
}
}
/* Wait for children */
for(i = 0; i < 6; i++)
{
wait(&status);
/* Handle status */
}