2014-12-01 70 views
0

我有一些麻烦从stdin复制一个字符串到一个缓冲区,该字符串的大小为12个字符HS1234-0.txt供以后使用,这里是我的代码:将聊天复制到缓冲区时出错

while(1) { 
    sem_wait(&escsem); 
    pthread_mutex_lock(&esctrin); 
    char filename[12]; 
    read(STDIN_FILENO,filename,12); //this is where I read from the stdin 
    lseek(STDIN_FILENO,13,SEEK_SET); 
    buffer[bufferpos]=filename; //this is where I try to copy 
    bufferpos=(bufferpos+1) % BUFFER_SIZE; 
    conta++; 
    pthread_mutex_unlock(&esctrin); 
    sem_post(&lesem); 
} 

这里是我尝试访问它,但它口口声声说缓存[bufferpos]是空的,file_to_open也为空

char* file_to_open; 
    while(1){ 
    sem_wait(&lesem); 
    pthread_mutex_lock(&lertrin); 
    file_to_open=buffer[bufferpos];//this is where i try to copy the string 
    printf("buffer %s file %s\n",buffer[bufferpos],file_to_open);//and here it return null on both 
    bufferpos=(bufferpos+1) % BUFFER_SIZE; 
    conta++; 
    pthread_mutex_unlock(&lertrin); 
    sem_post(&escsem); 
    } 

每个片段是由不同的线程和缓存使用宣布为

​​

希望你能以某种方式帮助我感谢球员提前

+1

char buffer [BUFFER_SIZE]; – DRC 2014-12-01 16:00:37

+0

'buffer [bufferpos] =文件名; //这是我试图复制的地方'那不会复制任何东西。这只是设置'buffer [bufferpos]'等于'filename',这是一个指针。 – 2014-12-01 16:24:06

+0

我以为他知道这一点,因为缓冲区是一个'char *'类型的数组。 – Jite 2014-12-01 16:24:51

回答

1

如果你想使用buffer的字符指针数组,那么问题是filename是一个局部变量只有特定环路内有效。您正在保存一个指向该局部变量的指针,但是当您尝试访问它时,它是无效的。您需要为指针动态分配内存,使其具有static或使其成为全局的,以便从该范围外可访问。

如果你想在“串”到缓冲区内保存相反,你需要strlcpy/strncpy串到你的缓冲区,而不是和改变buffer类型char buffer[SIZE]使其字符,而不是字符指针数组。

1
char* file_to_open; 
while(1) 
{ 
    // why use both a semaphore AND a mutex? 
    sem_wait(&lesem); 
    pthread_mutex_lock(&lertrin); 

    file_to_open=buffer[bufferpos]; 

    // per the input code, buffer[bufferpos] is a pointer to 
    // a non-null terminated array of characters (not a string due to no terminator) 
    // so this will keep outputting characters until a (random) '\0' 
    // char is encountered. this is undefined behaviour 
    printf("buffer %s file %s\n",buffer[bufferpos],file_to_open); 

    bufferpos=(bufferpos+1) % BUFFER_SIZE; 
    conta++; 
    pthread_mutex_unlock(&lertrin); 
    sem_post(&escsem); 
}