Is there a way to not wait for a system() command to finish? (in c) [duplicate]

馋奶兔 提交于 2019-11-27 14:35:06

system() simply passes its argument to the shell (on Unix-like systems, usually /bin/sh).

Try this:

int a = system("python -m plotter &");

Of course the value returned by system() won't be the exit status of the python script, since it won't have finished yet.

This is likely to work only on Unix-like systems (probably including MacOS); in particular, it probably won't work on MS Windows, unless you're running under Cygwin.

On Windows, system() probably invokes cmd.exe, which doesn't accept commands with the same syntax used on Unix-like systems. But the Windows start command should do the job:

int a = system("start python -m plotter");

As long as you're writing Windows-specific code (start won't work on Unix unless you happen to have a start command in your $PATH), you might consider using some lower-level Windows feature, perhaps by calling StartProcess. That's more complicated, but it's likely to give you more control over how the process executes. On the other hand, if system() meets your requirements, you might as well use it.

There's no way in the standard library, but you can fork out or create a separate thread that would run it on the background, if your OS supports it.

I believe if you add a '&' to the end of the command it will work. '&' tells the command to run in the background

int a = system("python -m plotter &");

"System" command on Linux will let the rest of code execute only when it has done executing itself.

You should use fork() if you want simultaneous processing.

The word for this is an Asynchronous function/method call. C and C++ don't have such a feature so you have to either call the function in a separate thread or use a system call that will run it in a separate process. Both of these methods tend to be platform specific, although there are cross platform threading libraries.

I know that in unix to do this in a separate process you would use fork(2) to create a new process and exec(3) to execute a new program in that process. I do not know what system calls would be required in Windows, but should be something similar.

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