gpt4 book ai didi

c - 未命名信号量 POSIX IPC

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:49 24 4
gpt4 key购买 nike

我分配了一个整数大小的共享内存段。

标准输出的预期结果应该是:

P: 1
C: 2

但它是:

C: 1
P: 2

为什么在父进程完成并解锁共享内存段之前子进程不会被阻塞?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <semaphore.h>

#define SHMSEGSIZE sizeof(int)

int main(void){

pid_t pid;
int shmID;
int *shared_mem;

/* initializing shared memory */
shmID = shmget(IPC_PRIVATE, SHMSEGSIZE, IPC_CREAT | 0644);
shared_mem = (int *)shmat(shmID, 0, 0);
*shared_mem = 0;

/* initializing semaphore */
sem_t sem;
int pshared = 1; // !=0 for processes, =0 for threads
int value = 1; // number of processes at a time
sem_init(&sem, pshared, value); // initialize the semaphore

pid = fork();

if(pid>(pid_t)0){ // parent
sem_wait(&sem);
sleep(6);
*shared_mem += 1;
printf("P: %d\n", *shared_mem);
sem_post(&sem);
exit(EXIT_SUCCESS);
} // parent

if(pid==(pid_t)0){ // child
sleep(3);
sem_wait(&sem);
*shared_mem += 1;
sem_post(&sem);
printf("C: %d\n", *shared_mem);
exit(EXIT_SUCCESS);
} // child

/* fork() failed */
printf("Failed to fork().");
exit(EXIT_FAILURE);
}

编译:

gcc -o executable sem.c -pthread

最佳答案

sem_t 本身必须在共享内存中才能被“pshared”。

struct my_shared_mem {
sem_t sem;
int value;
};

... later ...

struct my_shared_mem *shared;

shmID = shmget(IPC_PRIVATE, sizeof(*shared), ...);
shared = shmat(shmID, ...);
shared->value = 0;
sem_init(&shared->sem, 1, 1);
...

关于c - 未命名信号量 POSIX IPC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29950001/

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