日期:2014-05-16  浏览次数:20788 次

信号量 段错误 编译过了,运行提示段错误!!! 大神们,急救啊!!!!
#define __LIBRARY__
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>


#define MAX 1000


int main(){
int i,j,k;
int count;
int temp1[10],temp2[10];
int num,last_num;
int num_cp = 0;
int pid = 100;
FILE *gjw = NULL;
sem_t *empty, *mutex, *full;

empty = sem_open( "empty", O_CREAT, 0644, MAX);
mutex = sem_open( "mutex", O_CREAT, 0644, 1);
full = sem_open( "full", O_CREAT, 0644, 0);

gjw = fopen( "guojunwu.txt", "wb+");

for( i = 0; i < 10; i++) {
if( pid > 0) {
pid = fork();
num_cp++;
}
}

//父进程 Producer
if( pid > 0) {
for( j = 0; j < MAX; j++) {
fseek( gjw, 0L, SEEK_END);
count = ftell(gjw);
if(count < 10) {
sem_wait(mutex);
sem_wait(empty);

fseek( gjw, count * sizeof(int), SEEK_SET);
fwrite( &j, sizeof(int), 1, gjw);
fflush(gjw);

sem_post(full);
sem_post(mutex);
}
}
while(num_cp>0) {
wait(NULL);
num_cp--;
}
exit(0);
}


/*
fseek( gjw, sizeof(int), SEEK_END);
fread( &last_num, sizeof(int), 1, gjw);
*/


//子进程 Consumer
else if( pid == 0) {
while(1) {
sem_wait(mutex);
sem_wait(full);

fseek( gjw, 0L, SEEK_END);
count = ftell(gjw);
if(count) {
fseek( gjw, 0L, SEEK_SET);
fread( &num, sizeof(int), 1, gjw);
printf( "%d: %d\n", getpid(), num);
fflush(stdout);


fseek( gjw, 0L, SEEK_SET);
fread( &temp1, sizeof(int), count, gjw);
for( k = 0; k < count - 1; k++) {
temp2[k] = temp1[k+1];
}
fseek( gjw, 0L, SEEK_SET);
fwrite( &temp2, sizeof(int), count - 1, gjw);
fflush(gjw);
}

sem_post(empty);
sem_post(mutex);
}
}


else {
printf("\nerror!");
}

sem_unlink("empty");
sem_unlink("mutex");
sem_unlink("full");


fclose(gjw);
return 0;
}


------解决方案--------------------
fread( &temp1, sizeof(int), count, gjw);


==>count是文件大小,应该是count/4吧?不然越界了。

------解决方案--------------------
count = ftell(gjw);
if(count < 10) {
sem_wait(mutex);
sem_wait(empty);

fseek( gjw, count * sizeof(int), SEEK_SET);
fwrite( &j, sizeof(int), 1, gjw);
fflush(gjw);

count是字节数,count*sizeof(int)跑哪里去了。。。

应该是count/4求总共有n个int,然后fseek(k*sizeof(int))位置,k<n;