【发布时间】:2015-04-29 16:57:10
【问题描述】:
我分配了一个整数大小的共享内存段。
stdout 的预期结果应该是:
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
【问题讨论】: