信号量不能正常工作

时间:2017-02-15 17:13:12

标签: c process parent-child semaphore

我正在进行一项任务,我们需要使用信号量,以使父进程的第二次打印等到子进程首先执行。这是第一次使用信号量,我当然明白它们是如何工作的,但是我认为我对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. 

1 个答案:

答案 0 :(得分:0)

父母中的

:您创建一个信号量,打印一条消息,然后等待信号量 在孩子中:你创建一个信号量,打印2条消息,关闭semaphone并退出 现在父母可以从等待中返回。

请参阅http://man7.org/linux/man-pages/man3/sem_wait.3.html了解一个简单的例子

相关问题