C - Get PID of process opened with popen

2019-02-25 08:58发布

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.

2条回答
倾城 Initia
2楼-- · 2019-02-25 09:11

Just write your own implementation of popen that returns the PID. It's much less ugly than some crazy hackery around the existing popen. You can find source code to popen implementations all over the net. Here's one.

查看更多
萌系小妹纸
3楼-- · 2019-02-25 09:29

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 rewrite popen, then you can stick a call to setitimer in there. stdout is less straightforward; but if you are logging stdout with a shell redirect then I think ulimit -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.

查看更多
登录 后发表回答