简体   繁体   English

在程序中使用sem_wait

[英]Use of sem_wait in a program

I wrote this simple program that creates a child process and prints some messages inside: 我编写了这个简单的程序来创建子进程并在其中打印一些消息:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
sem_t *init;


int main()
{
init=sem_open("/mysem", O_CREAT, 0644, 1);
pid_t c,c2;
c=fork();
if(c==0){
sem_wait(init);
for(int i=0;i<5;i++){
printf("critical1 \n");
}
}}

I read that sem_wait checks the value of the semaphore and if it is greater than 0 decrements it and proceed and if it is 0 it get's stuck there until this value is increased.So after initializing semaphore's value to 1 i expect sem_wait to continue normally and not block the program.However,in this case this program prints nothing and terminates(not just pause).What am i missing? 我读到sem_wait检查信号量的值,如果它大于0,则递减它并继续,如果它为0,它就会卡在那里直到这个值增加。所以在将信号量的值初始化为1后,我希望sem_wait正常继续,不阻止程序。但是,在这种情况下,这个程序不打印任何内容并终止(不只是暂停)。我错过了什么?

The problem here is that posix semaphores are persistent across program runs. 这里的问题是posix信号量在程序运行中是持久的。 The first time you run, it works. 你第一次跑,它的工作原理。 Subsequent runs the initialization value is ignored since the semaphore already exists and is therefore maintaining a value of zero. 随后的运行将忽略初始化值,因为信号量已经存在,因此保持值为零。 Try this modification which unlinks the semaphore when the program ends. 尝试此修改,在程序结束时取消链接信号量。 Note that it might not work the first time you run it since the semaphore might exist on your computer. 请注意,由于您的计算机上可能存在信号量,因此第一次运行它时可能无法正常工作。 It will work on subsequent executions: 它将适用于后续执行:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
sem_t *init;


int main()
{
  init=sem_open("/mysem", O_CREAT, 0644, 1);
  pid_t c,c2;
  c=fork();

  if(c==0)
  {
    printf("before sem_wait()\n");
    sem_wait(init);
    printf("after sem_wait()\n");

    for(int i=0;i<5;i++)
    {
      printf("critical1 \n");
    }
    sem_close(init);
  }
  else
  {
    sleep(5);
    printf("main() exiting.\n");
    sem_close(init);
    sem_unlink("/mysem");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM