C 信号灯工作不正常

C 信号灯工作不正常,c,process,parent-child,semaphore,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 <

我正在处理一个赋值,在这个赋值中,我们需要使用信号量,以便使父进程的第二次打印等待子进程第一次执行。这是第一次使用信号量,我当然理解它们是如何工作的,但是我认为我对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.
I am the child process. 
The child process is done.
The parent process is done. 

在父级:您创建一个信号量,打印一条消息,然后等待信号量。
在子系统中:创建一个信号量,打印两条消息,关闭信号机并退出。
现在,家长可以从等待中返回


请参阅一个简单的示例

那么您所说的是在parrent过程之后添加一个sem_post(sem)?发生了一些非常奇怪的事情。我在父项的末尾添加了一个sem_post(sem),它工作了一次,然后返回错误的打印,忽略了wait and post。您没有检查
sem_open
的返回值,请先检查-我发现的
sem_open
调用有4个参数(linux人)这就是我试图检查返回值的方式:
sem\u unlink(mySem);sem_t*sem;sem=sem_open(“mySem”,0_CREAT,S_IRUSR | S|u IWUSR,3);如果(sem==sem_FAILED){perror(“sem_open”);exit(exit_faile)}
它仍然不能工作。
I am the parent process.
I am the child process. 
The child process is done.
The parent process is done.