我正在尝试使用信号量来保护代码的关键区域。该区域由两个过程引用。 现在,我需要确保这两个进程不会同时执行读写操作。这两个过程 有自己的主要功能。
在sem_init()函数中,我将第二个变量用作非零值,这是否足以在两个进程之间共享信号量?例如:
sem_init(&sema_name, 1, 1)
这是一个例子:
semaphoreFunctions.h
#include <semaphore.h>
int init_sema(sem_t sema_name);
int get_sem_value(sem_t sema_name);
sem_t mySemaphore;
process_1.c
#include <stdio.h>
#include <unistd.h>
#include "semaphoreFunctions.h"
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
static int sem_status ;
int init_sema(sem_t sema_name)
{
if(sem_init(&sema_name, 1, 1) != 0 ){
slgError("process_1: Error in sema_init");
}
return 0;
}
int get_sem_value(sem_t sema_name)
{
if(sem_getvalue(&sema_name, &sem_status) != 0 )
{
printError("process_1:sem_getvalue did not worked");
}
return sem_status;
}
int main()
{
if(init_sema(mySemaphore) == 0){
printError( "process_1: sem_init_worked with sema_value= %d\n",get_sem_value(mySemaphore));
}
else
{
printError( "process_1: sem_init_failed");
}
printf("this is first process doing critical operation \n");
sem_wait(&mySemaphore)
//do action of shared resources between two processes
//
//
sem_post(&mySemaphore)==0
/* rest of the code
..
*/
}
process_2.c
#include <stdio.h>
#include <unistd.h>
#include "semaphoreFunctions.h"
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
int main()
{
printf("this is second process\n");
sem_wait(&mySemaphore)
//do action of shared resources between two processes
//
//
sem_post(&mySemaphore)==0
}
问题;这种方法正确吗? ,如果没有,那么有什么建议吗?