有時這種程序錯誤帶有分段錯誤。什麼是分段錯誤?爲什麼會發生?我該如何解決它?信號量和同步中的分段錯誤
我期待的輸出爲:
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