gpt4 book ai didi

c - 确保 child 在 parent 结束之前完成

转载 作者:行者123 更新时间:2023-11-30 18:14:00 24 4
gpt4 key购买 nike

#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 函数。

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

最佳答案

因为,fork创建进程时,内存资源并不共享。而是尝试vfork

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

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

关于c - 确保 child 在 parent 结束之前完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com