我正在做一个作业,我们需要使用信号量,以使父进程的第二次打印等到子进程首先执行。这是第一次使用信号量,我当然理解它们是如何工作的,但是我认为我在 sem_open() 的初始化方面遇到了问题。
按照以下步骤:
sem_t *sem_open(const char *name, int oflag);
我创建了这个:
sem_t *sem = sem_open("MYSEM", O_CREAT , 2);
但是,在执行我的 sem_wait 时被忽略。这是我的整个程序:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
/* void ChildProcess(void) ChildProcess prototype */
/* void ParentProcess(void) ParentProcess prototype */
int main(int argc, char ** argv){
int pid;
pid = fork();
sem_t *sem = sem_open("MYSEM", O_CREAT , 2);
if (pid<0)
{
printf("Cannot create a child process");
exit(EXIT_FAILURE);
}
else if (pid==0)
{
printf("I am the child process. \n");
printf("The child process is done. \n");
sem_post(sem);
exit(EXIT_SUCCESS);
}
else
{
printf("I am the parent process. \n");
sem_wait(sem);
printf("The parent process is done. \n");
}
sem_destroy(sem);
exit (EXIT_SUCCESS);
}
打印的是:
I am the parent process.
The parent process is done.
I am the child process.
The child process is done.
应该打印的是这样的:
I am the parent process.
I am the child process.
The child process is done.
The parent process is done.
最佳答案
在父级中:创建一个信号量,打印一条消息,然后等待信号量。
在子进程中:创建一个信号量,打印 2 条消息,关闭信号量并退出。
现在父级可以从等待中返回。
参见http://man7.org/linux/man-pages/man3/sem_wait.3.html举一个简单的例子
关于c - 信号量无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255970/