【问题标题】:Ensure children finish before parent ends确保孩子在父母结束之前完成
【发布时间】:2013-11-07 02:50:39
【问题描述】:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

(不是 pthread 或信号量)

如果以上是我使用的唯一库,我如何确保读取器在从共享缓冲区加载之前等待第一个写入器输入?

当我运行程序时,读取器会在写入器调用用户输入之前打印缓冲区中的垃圾值。而scanf 不起作用,它不等待任何用户输入并且继续运行。 看起来主流程在所有孩子完成之前就结束了,如果发生这种情况,孩子就会停止输入,那么有没有办法解决?

喜欢:

@ubuntu.....(returned?)
reader gets the data:1
Enter your data:
reader gets the data:1

我的源代码如下:

void reader(int i) 
{
   int data;
   if(nextp == N)
      nextp=0;
   printf("\nEnter the data(writer %d) :",i);
   scanf("%d",(buffer+nextp));
   nextp++;
}

void writer(int i)
{
   int g;
   if(nextc == N)
      nextc=0;
   g=*(buffer+nextc++);
   printf("\nreader %d gets the data:%d\n",i,g);
}

in main():
int k;
for(k=RW;k>0;--k)//RW is number of readers and writers
{
   pid = fork();
   if(!pid)
   {
      pid = fork();
      if(pid>0)//writer (child)
      {
         for(i=0;i<N;i++)
         {
            P(empty); 
            P(mutex); // Entering critical section
            P(write);
            writer(k);
            V(write);
            V(mutex); // Exit from critical section
            V(full); 
         }
         wait();
      }

      if(pid==0)//reader (grandchild)
      {

         int readsize;
         readsize = N*RW;
         for(i=0;i<readsize;i++)
         {
            P(full);
            P(mutex); // Entering critical section
            P(rd_count);
            if(N-1 == (j=sem_val(rd_count))) /* Write lock for first reader */
               P(write); /* Once we have it, it keeps writers at bay */
            V(mutex); 
            reader(k);
            P(mutex);
            V(rd_count);
            if(N == (j=sem_val(rd_count))) /* When last reader leaves: */
               V(write);                   /* Allow writers */
            V(mutex);
            V(empty); // Exit from critical section
         }
         wait();
      }
   }
}

sem_val 是自定义的getval 函数。

P 是自定义的-1 semop 函数。

V 是自定义 +1 semop 函数。

如有逻辑或语法错误,欢迎指出。提前致谢!

【问题讨论】:

  • 你遇到了什么问题?
  • 对我来说看起来不错。如果遇到任何问题,请提出来。
  • 当我运行程序时,读取器会在写入器调用用户输入之前打印缓冲区中的垃圾值。
  • 如果我多次调用 scanf 并且它不小心陷入 \n 从而无法获得任何输入,我会不会有问题?

标签: c linux semaphore


【解决方案1】:

因为fork创建进程时,内存资源不共享。不如试试vfork

每个子进程在fork创建时都有自己的内存。

请确保使用的信号量也应该同步进程。

【讨论】:

  • 感谢您的建议。 vfork 在减少内存大小方面很有用,但我仍然无法阻止读者打印垃圾。我应该清除缓冲区吗?
  • 首先确保正在使用相同的内存。
  • shmid=shmget(1000,BUFSIZE,IPC_CREAT | 0666) 对于这种情况,如果1000保持不变,那么内存是否不变?
  • 是的。应该是一样的。
  • 当我有多个写入器-读取器对时,不知何故写入器不会获取最后一个输出。最后一个循环中的读取器(获取它的最后一个输入)的行为类似于上面的输出。
猜你喜欢
  • 2014-10-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多