Pergunta

There is a program (c#) that starts my script via System.Diagnostics.Process and then calls WaitForExit() on it. The script (python in this case, though could be anything) then spawns a child process and exits. I expected the program to continue, but it hangs until the child process exits.

I have tried many ways of starting subprocesses, from python's os.fork to writing a shell script wrapper, but every method causes the program to hang. I can't change the code of the c# program, what do I need to do to the child process to allow the program to continue?

Note: I do not know if it matters, but the c# program is running in mono on ubuntu.

Edit: After further review of the c# code right before WaitForExit is call there is a while (!process.StandardOutput.EndOfStream) loop, could this be the problem?

Foi útil?

Solução

WaitForExit seems to hang on open stdout/stderr. I used this script to make my script async:

#!/bin/bash

~/foo.py "$@" >&- 2>&- &

Hope this helps the next person to come along.

Outras dicas

The simplest way to do this is to have the child process setsid(), which will remove all of its connections to you—it becomes a session leader of a new session, and a group leader of a new process group, and detaches from your stdio, all in one call.

If you can't modify the child process's code, you can do it from your Python parent by explicitly forking, then calling setsid, then execing, instead of the various usual cleaner methods like subprocess. Like this:

pid = os.fork()
if not pid:
    sid = os.setsid()
    os.execv(path, args)

I believe it's the process group that matters to System.Diagnostics.Process, but I don't actually know that for sure, so I figured better to be safe than sorry. If you want to try just os.setpgrp(), you can try it. If that works, you can actually spawn/subprocess/etc. the child and then just setpgid(pid, pid) on it.


Meanwhile, it sounds like you're just forking a child and continuing the same script in that child, in which case you can just add the setsid (or maybe setpgrp) after the fork and you should be done.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top