Utilizing wait() and fork() in C++ leads to mistakes

Appreciation for any assistance provided. In previous versions of C, there existed a default type for undeclared functions which is still supported by most compilers. In contrast, C++ does not feature a default type for undeclared functions, therefore, it triggers an error immediately when such a function is utilized without being declared.

Question:

I’m attempting to incorporate both

wait()

and

fork()

into my C++ program. However, upon doing so, I encounter an error message within
compilation phase
.

../test/my_test.cpp: In member function 'void MYClass::myMethod()':
../test/my_test.cpp:98: error: no matching function for call to 'wait::wait(int*)'
/data/backfire/staging_dir/toolchain-i386_gcc-4.1.2_uClibc-0.9.30.1/lib/gcc/i486-openwrt-linux-uclibc/4.1.2/../../../../i486-openwrt-linux-uclibc/sys-include/bits/waitstatus.h:68: note: candidates are: wait::wait()
/data/backfire/staging_dir/toolchain-i386_gcc-4.1.2_uClibc-0.9.30.1/lib/gcc/i486-openwrt-linux-uclibc/4.1.2/../../../../i486-openwrt-linux-uclibc/sys-include/bits/waitstatus.h:68: note:                 wait::wait(const wait&)

Code:

void MYClass::myMethod()
{
    pid_t pid;
    int status;
    if ((pid = fork()) < 0) {
       printf("error forkn");
       return;
    }
    if (pid == 0) {
        /* cild*/
        ......
    }
    /*parent*/
    while (wait(&status) != pid);
}

How to fix the error?


Solution 1:

The error message suggests that instead of attempting to invoke a function named

wait

, it was trying to generate an instance of an entity referred to as

wait

by converting a pointer.

The issue lies in the absence of the function header declaring

wait

. It is worth noting that another header defines a type named

wait

. In the absence of the function header, the compiler assumes that you are referring to

wait

.

The answer, as stated in the manual for

wait(2)

, is:

#include 
#include 


Solution 2:


It appears that there is an expectation for a constructor. Please attempt.

 while (::wait(&status) != pid);

To invoke the

wait

function, utilize the scope-operator. If this approach does not resolve the issue, it indicates a name-clash, and you must create a unique namespace for your class.

namespace mywait{
  class MyClass {
  };
}


Solution 3:


I concur with “bash.d” that if the “waitstatus.h” file has been self-written and needs to be utilized, enclosing it within a namespace is necessary.

In case you haven’t tried it, consider using
sys/wait.h
as a replacement for waitstatus.h.

Frequently Asked Questions

Posted in Uncategorized