c++等待问题

C++ wait problem

本文关键字:问题 等待 c++      更新时间:2023-10-16

我有一个这样的代码

    if (pid > 0) {
        // Child    
    } else {
        // Parent
    }
while (wait() > 0) {}

还有include

#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <ctime>
#include <sys/types.h>

但是当我尝试用g++ (g++ test.cpp -o test)编译它时,有一个错误:

lab3.cpp: In function «int main(int, char**)»:
lab3.cpp:57:18: error: no match for «operator>» in «{0} > 0»
lab3.cpp:57:18: warning: candidates are:
/usr/lib/gcc/i686-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/stl_pair.h:220:67: замечание: template<class _T1, class _T2> bool std::operator>(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&)
/usr/lib/gcc/i686-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/stl_iterator.h:304:46: замечание: template<class _Iterator> bool std::operator>(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)
/usr/lib/gcc/i686-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/stl_iterator.h:354:47: замечание: template<class _IteratorL, class _IteratorR> bool std::operator>(const std::reverse_iterator<_IteratorL>&, const std::reverse_iterator<_IteratorR>&)
/usr/lib/gcc/i686-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/basic_string.h:2548:58: замечание: template<class _CharT, class _Traits, class _Alloc> bool std::operator>(const std::basic_string<_CharT, _Traits, _Alloc>&, const std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/lib/gcc/i686-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/basic_string.h:2560:27: замечание: template<class _CharT, class _Traits, class _Alloc> bool std::operator>(const std::basic_string<_CharT, _Traits, _Alloc>&, const _CharT*)
/usr/lib/gcc/i686-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/basic_string.h:2572:58: замечание: template<class _CharT, class _Traits, class _Alloc> bool std::operator>(const _CharT*, const std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/lib/gcc/i686-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/stl_vector.h:1303:77: замечание: template<class _Tp, class _Alloc> bool std::operator>(const std::vector<_Tp, _Alloc>&, const std::vector<_Tp, _Alloc>&)

我做错了什么?

您的include间接拉取/usr/include/bits/waitstatus.h,这定义了一个union wait。由于没有wait函数的声明,c++将wait()视为构造函数表达式。这意味着wait()>0调用一个当然不存在的operator>(const wait &,int)。GCC的诊断在这里并没有真正的帮助。添加sys/wait.h来获取等待函数的有效原型

wait()是在sys/wait.h中定义的。

但是这里可能有一些我们无法从你发布的代码中看到的东西。

试着把它改成:

while (::wait() > 0) ...

确保从全局命名空间调用wait()函数,而不是从其他地方导入的其他类或构造。