【问题标题】:Trying to write a buffer to a file, but keep getting segmentation faults and I can't figure out why尝试将缓冲区写入文件,但不断出现分段错误,我不知道为什么
【发布时间】:2020-03-02 03:42:37
【问题描述】:

我有一些代码,其目标是打开/创建一个文件,读入消息,然后将这些消息写入打开/创建的文件。直到写入文件的所有内容似乎都可以正常工作。这是我的代码。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include "message-lib.h"

int usage( char name[] );
void * recv_log_msgs( void * arg );
sem_t mutex;
int log_fd; 

void * recv_log_msgs( void * arg ){ 
    sleep(1);
    sem_wait(&mutex);
    char buffer[1024];
    int number_bytes_read;
    FILE *fp = log_fd;
    do{
        number_bytes_read = read_msg(arg, buffer, 1024);
        printf("in recv\n");
        printf(buffer);
        fwrite(&buffer, 1, sizeof(buffer)/sizeof(buffer[0]), fp);
    }while(number_bytes_read > 0);
    if(number_bytes_read == 0){
        close_connection(arg);
    }
    sem_post(&mutex);
    return NULL;
}

int usage( char name[] ){
    printf( "Usage:\n" );
    printf( "\t%s <log-file-name> <UDS path>\n", name );
    return 1;
}

int main( int argc, char * argv[] )
{
    int connection;
    pthread_t tid;
    if ( argc != 3 )
        return usage( argv[0] );

    log_fd = creat(argv[1], S_IRUSR | S_IWUSR);
    if(log_fd == -1){
        perror(argv[1]);
        return 1;
    }

    int listener = permit_connections(argv[2]);
    if(listener == -1){
        return -1;
    }
    sem_init(&mutex, 0, 1);
    do{
        connection = accept_next_connection(listener);
        if(connection == -1){
            return -1;
        }
        pthread_create(&tid, NULL, recv_log_msgs, connection);
    }while(connection != -1);

    close_connection(connection);    

    close_listener(listener);


    fclose(log_fd);

    return 0;
}

permit_connections、accept_next_connection 和 read_msg 都来自提供给我的库。我猜我的问题出在 recv_log_msgs 中,但我不确定它会是什么。

【问题讨论】:

  • @ryyker int creat(const char *pathname, mode_t mode) 是用于在 UNIX 中创建文件的原始系统调用的签名。上面的代码可能还有其他明显错误的地方,但是creat没问题。

标签: c file pthreads fwrite


【解决方案1】:

这是你问题的根源:

FILE *fp = log_fd;

log_fd 是一个文件描述符,fp 是一个FILE 指针。 两者不可互换,您需要做的是使用write(...) 系统调用写入日志文件,或以其他方式创建日志文件以获取指向它的FILE指针。

FILE *fp = fopen(argv[1], "w"),可能会成功。

编辑:正如@DarrenSmith 在 cmets 中向我指出的那样,您也可以使用 fp = fdopen(log_fd, "w") 并保持其余代码不变。

【讨论】:

  • 或使用fdopen从int文件描述符转到FILE对象
  • @DarrenSmith 你是对的 - 我会把它添加到我的答案中。
  • 写好了,非常感谢!唯一有趣的是,现在正在写入的文件中包含数据,还有大量随机零和其他字符。你以前见过这样的事情吗?
  • @Withdrawnbean 我猜你在文件中看到垃圾的原因是因为你在写垃圾。如果您写入与刚刚读取的相同数量的字节,您可能会得到您想要的结果。试试fwrite(buffer, 1, number_bytes_read, fp);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多