有时这种程序错误带有分段错误。什么是分段错误?为什么会发生?我该如何解决它?信号量和同步中的分段错误
我期待的输出为:
I am consumer
I am producer
I am consumer
I am producer
(etc.)
然而,这种情况并非如此。任何人都可以向我解释这个吗?
#include<stdio.h>
#include<semaphore.h>
#include<sys/stat.h>
#include<fcntl.h>
sem_t* mutex;
sem_t* null;
main()
{
int temp;
int pid;
pid = fork();
sem_unlink("/mutex");
sem_unlink("/null");
null = (sem_t*)sem_open("/null",O_CREAT,S_IWUSR|S_IWGRP|S_IWOTH,0);
mutex =(sem_t*)sem_open("/mutex",O_CREAT,S_IWUSR|S_IWGRP|S_IWOTH,1);
if (pid != 0)
while(1)
{
sem_post(null);
sem_wait(mutex);
printf("\nIam In Producer\n");
scanf("%d",&temp); // just for my verification that where i am during execution
sem_post(mutex);
sem_wait(null);
}
else
while(1)
{
sem_post(null);
sem_wait(mutex);
printf("\nIam In consumer\n");
scanf("%d",&temp); // just for my verification that where i am during execution
sem_post(mutex);
sem_wait(null);
}
}
首先,将“null”信号量的名称更改为其他值。你也可以考虑检查sem_open调用是否成功。 – Throwback1986 2011-03-05 16:46:38
您应该为'fork()'包含''。 –
Doddy
2011-03-05 17:20:21