将聊天复制到缓冲区时出错

时间:2014-12-01 15:54:40

标签: c multithreading

我在将一个字符串从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]为null,而file_to_open也为null

    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);
    }

每个片段都使用不同的线程和缓冲区声明为

char* buffer[BUFFER_SIZE];

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

2 个答案:

答案 0 :(得分:1)

如果要将buffer用作字符指针数组,则问题是filename是仅在该特定循环内有效的局部变量。您正在保存指向该局部变量的指针,但是当您尝试访问它时,它无效。您需要为指针动态分配内存,将其设置为static或将其设置为全局,以便可以从该范围外部访问。

如果你想要"字符串"要改为保存在缓冲区中,您需要将strlcpy / strncpy字符串改为缓冲区,并将buffer的类型更改为char buffer[SIZE],使其成为一个数组字符,而不是字符指针。

答案 1 :(得分: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);
}