I have a program written in C, which opens another program using popen. I 'd like to get the pid of that program or some kind of handler for it, so as to kill it after a certain time limit, or if it exceeds some ram, and stdout limits. I think this must be done with ptrace, which needs the PID, which I don't know how to obtain.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Just write your own implementation of
popen
that returns the PID. It's much less ugly than some crazy hackery around the existingpopen
. You can find source code topopen
implementations all over the net. Here's one.You might also be able to use ulimits and other tricks to achieve the desired functionality without using ptrace. You can do this by writing your command to be something akin to
"sh -c 'ulimit [ulimit strings]; whatever-command'"
.ulimit -v
takes care of RAM limit. CPU time limit (ulimit -t
) might be able to approximate time limit; if not, and if you're willing to rewritepopen
, then you can stick a call tosetitimer
in there. stdout is less straightforward; but if you are logging stdout with a shell redirect then I thinkulimit -f
will do it. If you're reading child's stdout in the parent you can track it yourself, and kill with a signal if they go too long.