Creating and communicating with a child process using std/stdout

I posted some example code on my wiki that shows how to create a child process on a posix system, and communicate with it using stdin/stdout. Read it here:

http://trac2.assembla.com/pkaudio/wiki/ChildProcessStdinStdout

Some notable snippets:

static int child_pid = -1;
static int child_status = 0;
static int child_crashed = 0;

int child_exited(int wait=0)
{
int status = 0;
// printf("PARENT: waitpid %in", child_pid);
pid_t waitResult = 0;
if(wait)
{
do {
waitResult = waitpid(child_pid, &status, 0);
} while(waitResult == -1);
}
else
waitResult = waitpid(child_pid, &status, WNOHANG);
// printf("PARENT: waitpid!!! %in", waitResult);
if(waitResult > 0)
{
child_crashed = !WIFEXITED(status);
child_status = WEXITSTATUS(status);
return 1;
}
else
return 0;
}

...

else
{
// child
dup2(childWrite, STDOUT_FILENO);
dup2(childRead, STDIN_FILENO);
close(childWrite);
close(childRead);

char *c_argv[] = { "child", 0 };
execve("child", c_argv, 0);
fprintf(stderr, "CHILD: ERROR spawning processn");
abort();
By | 2010-04-16T19:29:00+00:00 April 16th, 2010|Uncategorized|0 Comments

Leave A Comment

69 − = 65