我有一个代码,该代码从共享内存中读取一个整数,然后确定子进程中的数字。我正在使用信号量来锁定此关键区域,以便仅在没有其他进程不增加整数的情况下才增加整数。所以我得到一个稳定的整数值。
我使用了SYSTEM V Semaphore,但是我无法使其正常工作,因为我对该功能的使用似乎没有任何作用。
该程序仅生成100个processeces,其中每个进程将共享内存中的整数增加1。(该共享内存段最初是由另一个程序创建的,请告诉我是否也需要它!)
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sem.h>
#include <unistd.h>
#include <sys/wait.h>
#define FIFO_PATH "/tmp/RESULT_FIFO"
#define PROC_NUM 10
#define MAX_ITERATIONS 1
#define SHM_SIZE 1024
#define SHM_KEY 23423
int shmid, *shmdata, semid;
struct sembuf semaphore;
int main() {
FILE *fp_fifo;
/* Initialize Semaphore */
semid = semget (2134L, 0, IPC_PRIVATE);
if(semid <0) {
semid = semget (2134, 1, IPC_CREAT | IPC_EXCL | 0666);
if (semid < 0) { …Run Code Online (Sandbox Code Playgroud)