[新增] 信号量测试Demo

This commit is contained in:
gaoyang3513
2023-07-11 20:04:17 +08:00
commit 649283de15
5 changed files with 148 additions and 0 deletions

86
test_sem.c Normal file
View File

@ -0,0 +1,86 @@
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<semaphore.h>
#include<sys/sem.h>
#include <sys/stat.h>
#include<fcntl.h>
int main(){
int pid1,pid2;
sem_t *resource1;
sem_t *resource2;
char inpipe[200],outpipe1[100],outpipe2[100];
int fd[2]; //0为读出段,1为写入端
pipe(fd); //建立一个无名管道
pid1 = fork();
if(pid1<0){
printf("error in the first fork!");
}
else if(pid1==0){ //子进程1
printf("[%s|%u]Current: %u\n", __FUNCTION__, __LINE__, getpid());
printf("Pid of PID[1]: %u\n", getpid());
resource1=sem_open("name_sem1",O_CREAT,0666,0); // 有名信号量打开name_sem1
close(fd[0]); //关掉读出端
lockf(fd[1],1,0); // 管道持锁, 锁定从当前偏移量到文件结尾的区域
sprintf(outpipe1,"Child process 1 is sending a message!\n");
write(fd[1],outpipe1, strlen(outpipe1));
lockf(fd[1],0,0); // 管道解锁
sem_post(resource1); // 信号量开锁name_sem1
sem_close(resource1); // 有名信号量关闭name_sem1
exit(0); // 线程退出
}
pid2 = fork();
if(pid2<0){
printf("error in the second fork!\n");
}else if(pid2==0){ // 子进程2
printf("[%s|%u]Current: %u\n", __FUNCTION__, __LINE__, getpid());
resource1=sem_open("name_sem1",O_CREAT,0666,0);
resource2=sem_open("name_sem2",O_CREAT,0666,0);
sem_wait(resource1);
printf("Pid of PID[2]: %u\n", getpid());
close(fd[0]);
lockf(fd[1],1,0);
sprintf(outpipe2,"Child process 2 is sending a message!\n");
write(fd[1],outpipe2, strlen(outpipe2));
lockf(fd[1],0,0);
sem_post(resource2);
sem_close(resource1);
sem_close(resource2);
exit(0);
}
if(pid1 > 0 && pid2 >0){
printf("[%s|%u]Current: %u\n", __FUNCTION__, __LINE__, getpid());
resource2=sem_open("name_sem2",O_CREAT,0666,0);
sem_wait(resource2); // 信号量持锁source2
printf("Current: %u\n", getpid());
waitpid(pid1,NULL,0); // 等待子线程1状态变化(退出)
waitpid(pid2,NULL,0); // 等待子线程2状态变化(退出)
close(fd[1]); //关掉写端
read(fd[0],inpipe,200);
printf("%s\n",inpipe);
sem_close(resource2);
exit(0); // 进程退出,正常
}
sem_unlink("name_sem1"); // 信号量销毁,
sem_unlink("name_sem2");
return 0;
}