Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在程序中使用sem_wait_C_Operating System - Fatal编程技术网

C 在程序中使用sem_wait

C 在程序中使用sem_wait,c,operating-system,C,Operating System,我编写了这个简单的程序,创建了一个子进程,并在其中打印了一些消息: #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() {

我编写了这个简单的程序,创建了一个子进程,并在其中打印了一些消息:

#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");
}
}}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
sem_t*init;
int main()
{
init=sem_open(“/mysem”,O_CREAT,0644,1);
pid_t c,c2;
c=fork();
如果(c==0){
sem_wait(init);

对于(int i=0;i这里的问题是posix信号量在程序运行期间是持久的。第一次运行时,它就工作了。后续运行时,初始化值被忽略,因为信号量已经存在,因此保持值为零。请尝试此修改,在程序结束时取消信号量的链接。注意,它可能会第一次运行时无法工作,因为您的计算机上可能存在信号量。它将在后续执行中工作:

#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");
  }
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
sem_t*init;
int main()
{
init=sem_open(“/mysem”,O_CREAT,0644,1);
pid_t c,c2;
c=fork();
如果(c==0)
{
printf(“扫描前等待()\n”);
sem_wait(init);
printf(“sem_uwait()\n”)之后);
对于(int i=0;i