简体   繁体   中英

fork/exec: child exits when trying to redirect stdin/stdout

I'm trying to control a shell-like process from my program using fork/exec, using pipes to write commands to the process and read its output. If I create the process without any redirecting, it runs without exiting, as expected - I can see both the parent and the child in the ps output. However, once I add the redirect code in, the child seems to exit immediately (it shows as "defunct" in ps). I'm not sure how to determine why the child process is exiting (I don't see any output from it), so I'm struggling to diagnose the problem.

My code looks something like this:

int in[2], out[2];
FILE *in_fp, *out_fp;

pipe(in);
pipe(out);

if (fork()) {
    close(in[0]);
    close(out[1]);
    in_fp = fdopen(in[1], "w");
    out_fp = fdopen(out[0], "r");

    // Here I'll use in_fp and out_fp to communicate with the child.
} else {
    dup2(in[0], STDIN_FILENO);
    dup2(out[1], STDOUT_FILENO);
    close(in[0]);
    close(in[1]);
    close(out[0]);
    close(out[1]);

    execlp("child_process", NULL);
}

Does anyone know why this might not be working, or suggest how I can get more info about why the child process exits?

edit: So strace reveals the child process is crashing with a SIGSEGV, and looks like it's in Py_SetProgramName - though can't work out why yet (don't have access to the child's symbols).

Probably the problem is in the call to execlp() .

Although technically the list of arguments may be empty, it is standard practice to add always at least one argument, that will be argv[0] in main() , with the actual name used to invoke the program. Likely the python program uses this arg0 as argument to Py_SetProgramName() without checking for NULL .

So write instead:

execlp("child_process", "child_process", (char*)NULL);

Also note that, citing from man execlp :

The list of arguments must be terminated by a null pointer, and, since these are variadic functions, this pointer must be cast (char *)NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM