【问题标题】:Output synchronization using sys semaphores使用 sys 信号量进行输出同步
【发布时间】:2017-04-10 21:25:00
【问题描述】:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "display.h"
#include <sys/ipc.h>
#include <sys/sem.h>

int main()
{
   int i;
   struct sembuf up = {0,1,0};
   struct sembuf down = {0,-1,0};
   int sem0 = semget(IPC_PRIVATE,1,0600);
   int sem1 = semget(IPC_PRIVATE,1,0600);
   if (fork())
   {
       for (i=0;i<10;i++)
           display("ab");
           semop(sem1,&up,1);
           semop(sem0,&down,1);
           wait(NULL);
   }
   else
   {
        for (i=0;i<10;i++)
           semop(sem1,&down,1);
           display("cd\n");
           semop(sem0,&up,1);
           semop(sem1,&down,1);
   }
   semctl(sem0,0,IPC_RMID);
   semctl(sem1,0,IPC_RMID);
   return 0;
}

我希望输出是
abcd
abcd
abcd
...
没有信号量,我得到的不是乱码输出。上面的代码是我到目前为止所做的,但它似乎不起作用,因为我认为我没有正确放置起伏。我是整个过程同步和互斥体主题的新手,这是练习的一部分,因此任何与信号量无关的代码都不能更改。如果你能详细说明你的答案,那就太好了。

编辑:如果需要,那就是头文件中的显示功能。

void display(char *str)
{
  char *p;
  for (p=str; *p; p++)
  {
    write(1, p, 1);
    usleep(100);
  }
}

【问题讨论】:

    标签: c synchronization mutex semaphore shared-memory


    【解决方案1】:

    您的代码存在一些问题,请参考代码中的cmets进行描述。

    int main()
    {
       int i;
       struct sembuf up = {0,1,0};
       struct sembuf down = {0,-1,0};
       int sem0 = semget(IPC_PRIVATE,1,0600);
       int sem1 = semget(IPC_PRIVATE,1,0600);
       if (fork())
       {
           for (i=0;i<10;i++)
           {
               display("ab");
               semop(sem1,&up,1);
               semop(sem0,&down,1);
               //wait(NULL); //MAYUR: wait() suspends the execution until one of its children terminates. But this was unnecessary here. I removed it. 
           } //MAYUR: There was no brackets for "for loop". Added it in both the blocks.
       }
       else
       {
            for (i=0;i<10;i++)
            {
               semop(sem1,&down,1);
               display("cd\n");
               semop(sem0,&up,1);
               //semop(sem1,&down,1); //MAYUR: You are doing wait for sem1 in two places. This is was leading to deadlock. Removed it.
            }
       }
       semctl(sem0,0,IPC_RMID);
       semctl(sem1,0,IPC_RMID);
       return 0;
    }
    

    输出:

    abcd
    abcd
    abcd
    abcd
    abcd
    abcd
    abcd
    abcd
    abcd
    abcd
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多