C语言写出使用信号量阻塞子进程的代码
时间: 2023-08-21 07:06:47 浏览: 44
当使用信号量阻塞子进程时,可以使用信号量来实现同步和互斥操作。下面是一个使用信号量阻塞子进程的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <semaphore.h>
sem_t semaphore; // 信号量
int main() {
// 初始化信号量
if (sem_init(&semaphore, 0, 0) == -1) {
perror("sem_init");
exit(1);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
} else if (pid == 0) {
// 子进程
printf("Child process is running.\n");
// 子进程执行一些操作...
sem_post(&semaphore); // 发送信号量,解除阻塞
printf("Child process is done.\n");
exit(0);
} else {
// 父进程
printf("Parent process is waiting for child process.\n");
sem_wait(&semaphore); // 等待信号量,阻塞父进程
printf("Parent process continues.\n");
wait(NULL); // 等待子进程结束
sem_destroy(&semaphore); // 销毁信号量
printf("Parent process is done.\n");
exit(0);
}
}
```
在这个例子中,父进程创建了一个子进程,并使用信号量来进行同步操作。父进程等待子进程发送信号量,而子进程执行一些操作后发送信号量来解除父进程的阻塞。注意要在父进程结束前销毁信号量。