[修改] 测试
This commit is contained in:
@ -6,4 +6,6 @@
|
||||
```shell
|
||||
# Top
|
||||
cmake -S . -B output -G "Unix Makefiles"
|
||||
```
|
||||
|
||||
make -C output
|
||||
```
|
||||
|
||||
21
test_sem.c
21
test_sem.c
@ -12,10 +12,10 @@
|
||||
|
||||
int main(){
|
||||
int pid1,pid2;
|
||||
sem_t *resource1;
|
||||
sem_t *resource2;
|
||||
sem_t *resource1;
|
||||
sem_t *resource2;
|
||||
char inpipe[200],outpipe1[100],outpipe2[100];
|
||||
int fd[2]; //0为读出段,1为写入端
|
||||
int fd[2]; //0为读出段,1为写入端
|
||||
pipe(fd); //建立一个无名管道
|
||||
|
||||
pid1 = fork();
|
||||
@ -32,11 +32,12 @@ int main(){
|
||||
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); // 线程退出
|
||||
sem_post(resource1); // 信号量开锁,name_sem1
|
||||
sem_close(resource1); // 有名信号量关闭,name_sem1
|
||||
|
||||
exit(0); // 线程退出
|
||||
}
|
||||
|
||||
|
||||
pid2 = fork();
|
||||
if(pid2<0){
|
||||
printf("error in the second fork!\n");
|
||||
@ -48,11 +49,11 @@ int main(){
|
||||
sem_wait(resource1);
|
||||
printf("Pid of PID[2]: %u\n", getpid());
|
||||
close(fd[0]);
|
||||
lockf(fd[1],1,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);
|
||||
lockf(fd[1],0,0);
|
||||
sem_post(resource2);
|
||||
|
||||
sem_close(resource1);
|
||||
sem_close(resource2);
|
||||
|
||||
Reference in New Issue
Block a user