Search code examples
cunixparallel-processingforkdeadlock

I'd like to create a deadlock in my program but it's not working(C, fork, paralell-programming)


I'd like to create a deadlock after down(&s); printf("c s %d\n",s);

It suppose to stuck after down(&s); printf("c s %d\n",s); and I cant figure out why not. So I'd like to ask some help.

void down(int *s){
while(*s<0 || *s==0){;}
*s=*s-1;
}
void up(int *q){
     *q=*q+1;
}
int main(){
int p,pid;
int s=1,q=1;
if ((pid = fork()) == 0){
    down(&q);
    printf("c q %d\n",q);
    sleep(1);
    down(&s);
    printf("c s %d\n",s);
    sleep(1);
    printf("child\n");
    up(&q);
    printf("c q %d\n",q);
    sleep(1);
    up(&s);
    printf("c s %d\n",s);
    sleep(1);
    }
else{
    down(&s);
    printf("p s %d\n",s);
    sleep(1);
    down(&q);
    printf("p q %d\n",q);
    sleep(1);
    printf("parent\n");
    up(&s);
    printf("p s %d\n",s);
    sleep(1);
    up(&q);
    printf("p q %d\n",q);
    sleep(1);
    }
return 0;
}

Solution

  • s and q are not being shared between the parent and child. The child makes a copy then continues to run with a different variable.

    Because these do no share variable, you never actually call "down" on an that is less than or equal to 0.