2014-03-03 69 views
0

我正在編寫一個基本上是UNIX中「cp」命令的多線程版本的程序。爲此,我創建了用於輸入/輸出的文件,以及初始化的信號(用於分配)來同步共享數據。這裏是我的代碼主:來自多線程cp程序的Seg故障

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

我相信這是我的問題在於,因爲我還沒有開始編寫生產者和消費者線程。任何幫助表示讚賞。謝謝!

+1

段錯在哪裏發生? –

+1

根據上面的代碼,可能會出現很多地方。甚至可能是因爲沒有足夠的參數被傳遞,並且您試圖訪問argv [2] –

+1

我的建議,請對其進行調試。嘗試介入,一步一步。最終你會發現它自己。' – ST3

回答

1

參數用於semaphore_create()用於返回值。也就是說,函數需要知道在哪裏構建信號量對象。您不能只傳入任何正確類型的變量:請閱讀文檔以瞭解其用途。你的情況:

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

一般情況下,學習如何使用調試器,這將確切地告訴你在什麼行段錯誤發生。

同時驗證您的輸入並檢查您的返回值。還有其他地方可能會出現段錯誤。

+0

謝謝你親切的先生 –