[英]sem_wait is ignored in my program
我在linux上的共享內存上編寫了一個簡單的項目。 兩個程序共享內存,一個程序向其中寫入字母,第二個程序從中讀取它們。 我決定使用信號量,以確保在讀取之前不會產生新的字母。
問題是我的編寫器進程在其值為0且應等待時忽略了sem_wait(reading)。 它甚至在讀者開始之前就完成了工作。 我通過./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_wait
和sem_post
的返回值。 然后,您可以檢查errno
是否失敗,這將為您提供有關它們失敗原因的信息(但是,在您的情況下,我懷疑errno
值可能沒有幫助)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.