# IPC之System V 信号量（后续代码实现）

gan1007 分享于

1、概述：System V信号量用三个函数，semget，semop，semctl，分别是信号量集的夺取，操作，控制。其操作对象是信号量集合，semop操作的集合中，这些对象要么全

int val;

struct semid_ds *buf;

short *array;};void child1(int semid);void child2(int semid);int main(){

int ret;

pid_t pid1,pid2;

int semid1,semid2;

struct sembuf sem;

union semun sem_val;

if((semid1 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){

perror("semget semid1 error!\n");

}

if((semid2 = semget(IPC_PRIVATE,1,IPC_CREAT|0666)) < 0){

perror("semget semid2 erroe!\n");

}

sem_val.val = 0;

ret = semctl(semid1,0,SETVAL,sem_val);

if(ret < 0){

perror("semctl1 error!\n");

}

ret = semctl(semid2,0,SETVAL,sem_val);

if(ret < 0){

perror("semctl2 error!\n");

}

pid1 = fork();

if(pid1 < 0){

perror("fork pid1 error\n");

}

else if(pid1 == 0){

child1(semid1);

}

pid2 = fork();

if(pid2 < 0){

perror("fork pid2 error\n");

}

else if(pid2 == 0){

child2(semid2);

}

sem.sem_num = 0;

sem.sem_op

= 1;

sem.sem_flg = SEM_UNDO;

while(1)

{

sleep(1);

if(semop(semid1,&sem,1) == -1){

perror("semop semid1\n");

}

if(semop(semid2,&sem,1) == -1){

perror("semop semid2\n");

}

}

return 0;}void child1(int semid1){

struct sembuf sem1;

sem1.sem_num = 0;

sem1.sem_op

= -1;

sem1.sem_flg = SEM_UNDO;

while(1)

{

if(semop(semid1,&sem1,1) == -1){

perror("semop semid1\n");

}

printf("this is the child1\n");

sleep(1);

}}void child2(int semid2){

struct sembuf sem2;

sem2.sem_num = 0;

sem2.sem_op

= -5;

sem2.sem_flg = SEM_UNDO;

while(1)

{

if(semop(semid2,&sem2,1) == -1){

perror("semop semid2\n");

}

printf("this is the child2\n");

sleep(1);

}}

this is the child1

this is the child1

this is the child1

this is the child1

this is the child1

this is the child2

this is the child1

this is the child1

this is the child1

this is the child1

this is the child1

this is the child2

×
• 登录
• 注册

×