【发布时间】:2016-12-03 16:48:19
【问题描述】:
我使用信号量为一个 unix 项目创建了一个代码。我的代码是这样的:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include "display.h"
#include <semaphore.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct {
sem_t p1;
sem_t p2;
}SemPair ;
int main ( int argc, char *argv[]) {
SemPair *sem = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED |MAP_ANONYMOUS , -1, 0);
int i=0;
sem_init(&(sem->p1),1,0);
sem_init(&(sem->p2),1,0);
pid_t pid = fork();
if (!pid)
{
for( i=0;i<10;i++) {
sem_wait(&(sem->p2));
display("Hello world\n");
sem_post(&(sem->p1)); }
}
else
{
for( i=0;i<10;i++) {
sem_post(&(sem->p2));
sem_wait(&(sem->p1));
display("Goodnight world\n");
sleep(1);}
}
sem_destroy(&(sem->p1));
sem_destroy(&(sem->p2));
return 0;
}
如您所见,我的问题是我不想让显示按顺序排列,而是随机显示。所以我的输出是这样的。
Hello world
Goodnight world
Hello world
Goodnight world
Hello world
Goodnight world
....
相反,我希望进程不按顺序执行,因此输出将是这样的:
Hello world
Hello world
Hello world
Goodnight world
Hello world
Goodnight world
Goodnight world
....
【问题讨论】:
-
看看什么信号量在什么时候等待什么。
标签: c process semaphore shared