【问题标题】:Seg fault from multi-threaded cp program来自多线程 cp 程序的 Seg 错误
【发布时间】:2014-03-03 15:12:33
【问题描述】:

我正在编写一个程序,它本质上是 UNIX 中“cp”命令的多线程版本。为此,我为输入/输出创建了文件,并初始化了信号量(分配所需)以同步共享数据。这是我的主要代码:

int main(int argc, const char * argv[])
{
    //input/output file descriptors
    int fdIn, fdOut;

    //open files with proper rights
    fdIn = open(argv[1], O_RDONLY);
    fdOut = open(argv[2], O_WRONLY| O_CREAT | O_TRUNC, 0666);

    //create and initialize semaphores
    semaphore_t *empty = nullptr,*full = nullptr;
    semaphore_create(mach_task_self(), empty, SYNC_POLICY_FIFO, 2);
    semaphore_create(mach_task_self(), full, SYNC_POLICY_FIFO, 0);

    //create and initialize structs to pass args to threads
    threadDataConsumer.fd = fdOut;
    threadDataConsumer.empty = empty;
    threadDataConsumer.full = full;
    threadDataProducer.fd = fdIn;
    threadDataProducer.empty = empty;
    threadDataProducer.full = full;
    pthread_t tid1, tid2;

    //create a thread for the producer and consumer
    pthread_create(&tid1, NULL, Producer, (void *)&threadDataProducer);
    pthread_create(&tid2, NULL, Consumer, (void *)&threadDataConsumer);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}

我相信这就是我的问题所在,因为我什至还没有开始编写生产者和消费者线程。任何帮助表示赞赏。谢谢!

【问题讨论】:

  • 段错误发生在哪里?
  • 根据上面的代码,有很多地方可能会出现。甚至可能是没有传递足够的参数并且您正在尝试访问 argv[2]
  • 我的建议,调试一下。尝试步入,跨过。最终你会自己找到它。`

标签: c multithreading unix


【解决方案1】:

semaphore_create()semaphore_t * 参数用于返回值。也就是说,函数需要知道在哪里构建信号量对象。您不能只传入任何正确类型的变量:阅读文档以了解它的用途。在你的情况下:

semaphore_t sem_empty, sem_full;
semaphore_create(mach_task_self(), &sem_empty, SYNC_POLICY_FIFO, 2);
semaphore_create(mach_task_self(), &sem_full, SYNC_POLICY_FIFO, 0);

一般来说,学习如何使用您的调试器,它将准确地告诉您段错误发生在哪一行。

同时验证您的输入并检查您的返回值。还有其他地方可能会出现段错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多