【问题标题】:SegFault with Producer/Consumer File Copy带有生产者/消费者文件复制的 SegFault
【发布时间】:2012-10-20 08:44:00
【问题描述】:

返回另一个段错误。不知道为什么,因为这个 readdir 行与我在其他文件复制分配中使用的行相同。下面是我编写的代码来代替共享的分配here。我已经评论了段错误发生的地方,希望帮助更好的人找到我的缺陷!

这是copyDirs.cpp

//cmd: ./a.out [#ofConsumerThreads] [src directory] [dest directory]

#include "copyDirs.h"

int main(int ac,char* av[])
{
pthread_mutex_init(&buflock,NULL);
pthread_t prodT;

if(ac == 4)
{
    int consNum = atoi(av[1]);

    pthread_t thread[consNum];

    strcpy(f1,av[2]);
    strcpy(f2,av[3]);

    directory = opendir(f1);
    pthread_create(&prodT,NULL,producer,NULL); //segfault happens in producer function

        pthread_join(prodT, NULL);

    for(int i=0;i<consNum && buffer.size() > 0;i++)
    {
        pthread_create(&thread[i],NULL,consumer,NULL);
            pthread_join(thread[i],NULL);
    }

    closedir(directory);
}
else cout<<"Try that again ;)"<<endl;

pthread_mutex_destroy(&buflock);
pthread_exit(NULL);

return 0;
}

以及相关的头文件;

#ifndef COPYDIRS_H
#define COPYDIRS_H 

#include <iostream>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
#include <pthread.h>
#include <time.h>
#include <stack>

using namespace std;

struct FD
{
public:
char* i ;
char* o;

FD(){}

FD(char* input, char* output)
{
    i=input;
    o=output;
}
};

char f1[PATH_MAX];
char f2[PATH_MAX];

struct dirent *curDir;
DIR* directory = NULL;

pthread_mutex_t buflock;
stack <FD> buffer;

void* producer(void*)
{
cout<<"SegTest"<<endl;
    //shows

while (curDir = readdir(directory)) //segfault on this line
{
    cout<<"SegTest"<<endl;
        //doesn't show

    char* file = curDir -> d_name;
    char* i = new char[256];
    char* o = new char[256];

    strcpy(i,f1);
    strcpy(o,f2);
    strcat(i,file);
    strcat(o,file);
    FD prodFD(i,o);

    cout<<"Pushing "<<file<<" to buffer!"<<endl;
    pthread_mutex_lock(&buflock);
        buffer.push(prodFD);
    pthread_mutex_unlock(&buflock);

    i = NULL;
    o = NULL;
}

pthread_exit(NULL);
}

void* consumer(void*)
{
FD consFD;
char c;

consFD = buffer.top();
buffer.pop();
    //ERROR: "statement cannot resolve address of overloaded function

cout << "Copying file: "<<consFD.i<<endl;
pthread_mutex_lock(&buflock);
    FILE * consIF = fopen(consFD.i,"r");
    FILE * consOF = fopen(consFD.o,"w");
pthread_mutex_unlock(&buflock);

pthread_exit(NULL);
}
#endif 

【问题讨论】:

  • 重构。现在重构! .h 文件中的方法?数以万计的全球人?将 i & o(顺便说一下有用的名称)设置为 NULL 而不是删除?如果你的代码是可读的,你会发现它更容易调试!
  • @John3136,我知道我对头文件的使用并不传统,但在小型作业中,我发现以这种方式组织起来要容易得多。我还可以做一些其他的事情来改进代码:embarrassed:

标签: c++ segmentation-fault variable-assignment producer-consumer file-copying


【解决方案1】:

在调用readdir 之前尝试检查directory 的值不为NULL。你有这条线

 directory = opendir(f1);

但不检查返回值是否为 NULL,这可能是段错误的原因。至少,如果您为目录传递了无效的命令行参数,这将防止出现段错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    相关资源
    最近更新 更多