我必须创建三个使用共享内存的进程 A、B 和 C。A 和 B 在共享内存中写入 100 个整数,C 读取它们并将它们写入二进制文件。那是我做的,但它不能正常工作。我包括<stdio.h>
、<math.h>
和<fcntl.h>
。<time.h>
如何让它发挥作用?
struct sync
{
int n;
int lock;
int generated;
char process;
} *b;
int testandset(int* lockPtr)
{
int oldValue = *lockPtr;
return 0 != oldValue;
}
int main()
{
struct sync buff;
int pid, ppid, fp, i;
srand(time(NULL));
b = (struct sync*)malloc(666);
b->n = 0;
b->lock = 0;
b->generated = 0;
i = 0;
printf("Generating numbers\n");
pid = fork();
if (0 == pid)
{
while (100 >= b->generated)
{
while (testandset(&(b->lock)))
{
}
buff.n = rand() % 1001;
buff.process = 'A';
fp = open("db", O_RDWR | O_APPEND);
if (-1 == fp)
fp = open("db", O_CREAT);
write(fp, &buff, sizeof(struct sync));
close(fp);
b->generated++;
b->lock = 0;
}
}
if (0 < pid)
{
ppid = fork();
if (0 == ppid)
{
while (100 >= b->generated)
{
while (testandset(&(b->lock)))
{
}
buff.n = rand() % 1001;
buff.process = 'B';
printf("No: %d %d \n", ++i, buff.n);
fp = open( "db", O_RDWR | O_APPEND );
if (-1 == fp)
fp = open("db", O_CREAT);
write(fp, &buff, sizeof(struct sync));
close(fp);
b->generated++;
b->lock = 0;
}
}
if (0 < ppid)
{
wait();
i = 0;
fp = open("db", O_RDONLY, 0755);
printf("Reading from file\n");
while (read(fp, &buff, sizeof(struct sync)))
{
if ('A' == buff.process)
i++;
}
close(fp);
int vals[i];
i = 0;
fp = open("db", O_RDONLY, 0666);
while (read(fp, &buff, sizeof(struct sync)))
{
if ('A' == buff.process)
vals[i++] = buff.n;
}
close(fp);
fp = open("db", O_RDONLY, 0455);
int i;
for(i = 0; i < i; i++)
write((const void*) &vals[i],sizeof(int),1,fp);
}
wait();
}
return 0;
}