-1

process.hpp

#define HPROCESS int
class Process {
    private:
        int exitCode;
        HPROCESS hProcess;
    public:
        static void waitEnd(Process* proc) {
            int w = waitpid(proc->hProcess, &(proc->exitCode), 0);
            Debug::debug(w);
        }
};

main.cpp

int main() {
    Process* process = NULL;
    while(!process) {
        cout<<endl<<"Waiting for second process.\nPress any key";
        getchar();
        getchar();
        process = Process::takeExisting("process");
    }
    Process::waitEnd(process);
    cout<<endl<<"second process ended";
    cout<<endl<<endl;
    return 0;
}

I expected: stop main, wait for process, continue main. It isn't waiting for process, waitpid returns -1, why?

Nikita
  • 1,019
  • 2
  • 15
  • 39
  • You should explicitly be checking for errors anyway. Are you sure `waitpid()` isn't returning -1? Also, your function won't do what you expect: Process is passed *by value*, not *by reference*, so the modifications to `exitCode` do nothing. – andlabs Jun 23 '16 at 17:25
  • @andlabs I've corrected the code and check for -1, you were right. – Nikita Jun 23 '16 at 18:55
  • That code doesn't even compile. – melpomene Jun 23 '16 at 19:32
  • @Nikita now check `errno` to see what happened with the call; `man waitpid` for more info – andlabs Jun 23 '16 at 19:36
  • @andlabs Thanks, the situation becomes cleaner) Errno code - 10, no child processes, so waitpid not suit if I need to wait for not child process. – Nikita Jun 23 '16 at 21:57
  • @melpomene This was just a piece of code without headers and some methods of my Process class. Of course it would not compile it you just copied it. – Nikita Jun 23 '16 at 22:00
  • @Nikita I'm talking about the call `Process::waitEnd(*process)`, which is a type error. – melpomene Jun 24 '16 at 04:55
  • @melpomene Sorry, I forgot to correct code at call Process::waitEnd() after first changes, thanks. – Nikita Jun 24 '16 at 08:25

1 Answers1

1

Waitpid works only with child processes, that were launched with fork(), exec().

In this case errno code will be 10 after call, because it was an attempt to use waitpid on other process, not child.

BTW It is not solve my problem, but it another question: Linux WaitForSingleObject?

Community
  • 1
  • 1
Nikita
  • 1,019
  • 2
  • 15
  • 39