簡體   English   中英

system()是否在內部執行類似sem_post的調用?

[英]Does system() do a call like sem_post inside?

我認為我的代碼不會打印文本

哦,為什么要來這里!\\ n

但確實如此。

system()是否有“問題”? 因為,當我刪除它時,代碼按我的意願運行,停止了。

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>

pthread_t id0, id1;
sem_t sp; 

void *fun0(void *) {
    // When erasing the following line "system("");",
    // it block up, and doesn't print "oh why come here!\n".
    // But with it, it print the text!
    system("");
    return NULL;
}

void *fun1(void *) {
    sem_wait(&sp);
    fprintf(stderr, "oh why come here!\n");
    return NULL;
}
int main() {
    sem_init(&sp, 0, 0); 
    pthread_create(&id0, 0, fun0, NULL);
    pthread_create(&id1, 0, fun1, NULL);
    void *stat0, *stat1;
    pthread_join(id0, &stat0);
    pthread_join(id1, &stat1);
    return 0;
}

編譯器:gcc 4.1.2 Linux內核:2.6.18


我使用gcc 4.6.3,內核3.2.0對其進行了編譯,並且還可以根據需要運行。 所以我認為這是因為gcc 4.1.2或內核2.6.18。

system()調用與此無關。 我的靈性告訴我sem_wait失敗,並顯示錯誤代碼,而不是等待—檢查返回值。 例如,我可以在Mac OS X上重現您的結果,因為在Mac OS X上, sem_init()始終因ENOSYS (“未實現功能”)而失敗,這導致對sem_wait的調用隨后因EBADF (“錯誤的文件描述符”而失敗) “)。

如果添加一些錯誤檢查,您會發現問題出在哪里:

if(sem_init(&sp, 0, 0) < 0)
    fprintf(stderr, "sem_init failed: %s\n", strerror(errno));
...
if(sem_wait(&sp) < 0)
    fprintf(stderr, "sem_wait failed: %s\n", strerror(errno));

您還應該提高編譯器的警告級別-如果您想捕獲更多可能的問題,我絕對建議使用-Wall-Wextra -pedantic 當前,代碼無法通過未從fun0fun1函數返回值來調用未定義的行為-Wall會警告您。 這種錯誤可能不會在x86上引起任何明顯的問題,但是在其他架構(例如IA64)上, 未初始化的垃圾可能是致命的

您的代碼出現問題的原因是sem_wait手冊頁中的sem_wait(),它說:

“ sem_wait()遞減(鎖定)sem指向的信號量。如果該信號量的值大於零,則該減量繼續進行,該函數立即返回。如果該信號量當前的值為零,則調用將阻塞直到或者可以執行減量操作(即,信號量值增加到零以上),或者信號處理程序中斷調用。”

在代碼上,您已使用sp初始化為0,當sem_wait()減1時,它將阻塞並且永遠不會返回,因為沒有其他線程增量sp變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM