user1533754 February 2016

Jump back to child process after a forked parent exits

Is it possible to "jump back" to a child process after the parent process exits within vfork?
Let's say i have this simple application:

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int main (void)
{
    pid_t cpid = vfork();

    if (cpid < 0) cout << "error with fork\n";

    else if (cpid == 0)
    {
        cout << "cin from child: ";
        int a = 0;
        cin >> a;
        exit (0);
    }

    else
    {
        cout << "cin from parent: ";

        int a, status;

        waitpid (cpid, &status, WNOHANG);

        cin >> a;
    }

    return 0;
}

With this code i need to enter a number first within the child.
After that i need to enter a number within the parent.
And after that i want the child comes up again,
so is this possible?

Answers


Prolle February 2016

I don't really know what you want to describe with "And after that I want the child comes up again" but I assume you want to execute the child part of the code?

In the manpage for vfork you can find:

vfork() differs from fork(2) in that the calling thread is suspended until the child terminates (either normally, by calling _exit(2), or abnormally, after delivery of a fatal signal), or it makes a call to execve(2). Until that point, the child shares all memory with its parent, including the stack. The child must not return from the current function or call exit(3), but may call _exit(2).

Since you exit the child process you either have to fork a new one or call exec from the child and modify the code so that the child only run it's part of it.

Post Status

Asked in February 2016
Viewed 3,458 times
Voted 12
Answered 1 times

Search




Leave an answer