gpt4 book ai didi

c - sem_wait 在我的程序中被忽略

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:00:15 36 4
gpt4 key购买 nike

我在 Linux 中写了一个关于共享内存的简单项目。两个程序共享内存,一个是向其中写入字母,第二个是从中读取字母。我决定使用信号量以确保在读取新字母之前不会生成新字母。

问题是当 sem_wait(reading) 的值为 0 并且它应该等待时,我的编写器进程忽略了它。它在读者开始之前就完成了它的工作。我通过 ./writer & ./reader 运行它。

我附上代码。这里有一些未使用的元素,因为它还不是最终版本。然而问题已经出现了。

/* writer.c */
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <unistd.h>
#include <stdlib.h>
#include <semaphore.h>

int main( int argc, char *argv[] )
{
key_t shmkey = 0xF00;
int bytes = sizeof(char)*3 + sizeof(sem_t) * 3;
int shmid;
char* sharedMemory;
sem_t *writing, *reading, *working;

if ( (shmid = shmget( shmkey, bytes, IPC_CREAT | IPC_EXCL | 0666 )) < 0 )
{
shmdt( (void*) sharedMemory );
shmctl( shmid, IPC_RMID, NULL );
return 1;
}
if ( (sharedMemory = (char*) shmat( shmid, NULL, 0 )) == (char*) -1 )
{
shmdt( (void*) sharedMemory );
shmctl( shmid, IPC_RMID, NULL );
return 1;
}

writing = (sem_t*)(sharedMemory + 3);
reading = writing + 1;
working = reading + 1;

sem_init( writing, 0, 0 );
sem_init( reading, 0, 0 );

sharedMemory[2] = 'w'; // writer is running
char c;
for( c = 'a'; c <= 'z'; ++c )
{
*sharedMemory = c;
sem_post( writing );
sem_wait( reading );
}
sharedMemory[2] = 'q';
while ( sharedMemory[2] != 'w' );
sharedMemory[2] = 'q';
shmdt( (void*) sharedMemory );
shmctl( shmid, IPC_RMID, NULL );
return 0;
}

还有读者,

/* reader.c */
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <unistd.h>
#include <stdlib.h>
#include <semaphore.h>

int main( int argc, char *argv[] )
{
key_t shmkey = 0xF00;
int bytes = sizeof(char)*3 + sizeof(sem_t) * 3;
int shmid;
char* sharedMemory;
sem_t *writing, *reading, *working;

sleep(1); // wait until writer allocates fresh memory
if ( (shmid = shmget( shmkey, bytes, 0666 )) < 0 )
{
shmdt( (void*) sharedMemory );
return 1;
}
if ( (sharedMemory = (char*) shmat( shmid, NULL, 0 )) == (char*) -1 )
{
shmdt( (void*) sharedMemory );
return 1;
}

if ( sharedMemory[2] != 'w' ) // is writer running?
{
shmdt( (void*) sharedMemory );
return 1;
}

writing = (sem_t*)(sharedMemory + 3);
reading = writing + 1;
working = reading + 1;

//sleep(5); //@REMOVE

char c;
do
{
sem_wait( writing );
c = *sharedMemory;
sem_post( reading );
printf( "%c\n", c );
} while ( sharedMemory[2] == 'w' );
sharedMemory[2] = 'w';
shmdt( (void*) sharedMemory );
return 0;
}

最佳答案

sharedMemory + 3 未正确对齐类型 sem_t。由于您不知道 sem_t 的对齐要求,因此您需要确保您的 sem_t 对象从共享内存段中的偏移量开始,该偏移量是 sizeof(sem_t)(这是有效的,因为任何对象的对齐要求均分其大小)。

请注意,您应该检查 sem_waitsem_post 的返回值。然后你可以检查 errno 如果它们失败了,这会给你关于它们失败原因的信息(但是在你的情况下我怀疑 errno 值可能没有帮助).

关于c - sem_wait 在我的程序中被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21010454/

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