c++ - system() 是否会在内部执行类似 sem_post 的调用?

标签 c++ c linux

我认为我的代码不会打印文本

oh why come here!\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,uninitialized garbage can be deadly .

关于c++ - system() 是否会在内部执行类似 sem_post 的调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16432494/

相关文章:

linux - 使用 2 个参数在 BASH 中执行 C 程序

c++ - 是否可以强制不内联函数?

c - C 参数值中的单链表

java - java中是否需要启用/etc/fstab中的 "atime"才能获得正确的上次访问时间?

c - 在内核中高效分配内存

c - 地址 0x0 中的 0xdeadbeef 是什么意思?

c++ - 静态库中变量的 init_priority 属性

c++ - 错误: no matching function for call to 'function namel'

c# - C# 中 C++ 程序员的指针替代

c++ - 在 OpenCV 中获取 Z "depth"的简单方法