How do I make a system call and resume execution without waiting for the call to return?

孤者浪人 提交于 2019-12-24 21:07:21

问题


Basically I want to use system(), exec(), back-ticks or something to make a system call, but then to immediately resume execution in the calling script without caring about the result of the call and whether or not it returns, dies, stalls, whatever.

Is it possible to do this without threading/forking?


回答1:


Short answer, no. This is the entire point of fork(). The only question is whether you call fork() directly, or get something else to do that for you.

As mentioned, you could use the shell's backgrounding operator (&) to do that, but then you're using the shell, and that comes with the usual string-injection attack problem

system("some command with args &");

More directly, you could just do the usual fork() and exec() and then not perform the waitpid() that normally happens, which is where the blocking occurs:

if(fork() == 0) {
  exec("some", "command", "with", "args") or die "Cannot exec - $!";
}
# No waitpid here so no waiting

If you're doing that, best also to put a SIGCHLD handler in to ignore when the child does eventually exit, so as not to leave zombies hanging around. At some point near the beginning of the code, put

$SIG{CHLD} = 'IGNORE';



回答2:


Use the shell's background operator &:

system("some command &");


来源:https://stackoverflow.com/questions/22523543/how-do-i-make-a-system-call-and-resume-execution-without-waiting-for-the-call-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!