Open/run 来自 C 的另一个程序,然后关闭该程序
Open/run another program from C and then close this program
如何从 C 中 execute/open/run 另一个程序,而不是阻止它,但让它同时 运行。然后我想做一些像 server/client 这样的测试,如果已经完成,我只想 kill/close 这个程序。我读过
system() or execv()
但第一个似乎在等待结果,第二个似乎只能在 Linux 上工作?在最好的情况下,我希望有跨平台或最小 MacOS/Windows/Linux(Ubuntu) 工作解决方案。当我不再需要它时,我还需要关闭这个以前打开的程序。
How to execute/open/run another program from C ?:
使用system
How not to block on it?
您必须实施多任务处理,因此请使用 fork
创建另一个进程或 pthread_create
要创建另一个线程,请查看 this
I would like to have cross-platform or minimum macOS/Windows/Linux(Ubuntu) working solution.
system
适用于 linux 和 windows 但我对其他平台没有任何想法
POSIX 方法(也许也可以在 Windows 中使用 -- https://technet.microsoft.com/en-us/library/bb463220.aspx?)
是使用 fork + exec* 组合:
您使用 fork 创建一个复制当前进程的新进程。
您对该进程的句柄是一个 int 进程标识符 (pid):
int pid;
if (0 > (pid=fork()){
perror("fork failed");
return -1;
}
if (0 == pid){
//CHILD PROCESS
printf("I'm the child process, my pid is: %d\n", getpid());
}
//pid > 0 ==> PARENT PROCESS
puts ("I'm the parent process");
printf("The pid of the child I've just spawned is %d\n", pid);
对于子进程中的 运行 可执行文件,使用 exec* 函数替换当前(例如,如果您 运行 在子进程中使用子进程)进程映像从可执行文件加载的过程映像。
在父进程中,您可以使用 pid 句柄来 kill 进程(=要求它终止):
kill(pid, SIGTERM); //please terminate
并且您可以使用 waitpid 在它终止后检索其退出状态。
( system 内部使用 fork
+ execv
(它执行 shell)+ waitpid
。因为 waitpid
部分是'separate in system
,system
让你等待子进程完成。)
您可能还想研究 dup2 and pipe or socketpair 以设置与子进程的基于文件描述符的通信通道(还有其他选项,例如共享内存、消息队列或信号,如果您只需要非常基本的沟通)。
联机帮助页是管理进程和 IPC 的良好资源。
如何从 C 中 execute/open/run 另一个程序,而不是阻止它,但让它同时 运行。然后我想做一些像 server/client 这样的测试,如果已经完成,我只想 kill/close 这个程序。我读过
system() or execv()
但第一个似乎在等待结果,第二个似乎只能在 Linux 上工作?在最好的情况下,我希望有跨平台或最小 MacOS/Windows/Linux(Ubuntu) 工作解决方案。当我不再需要它时,我还需要关闭这个以前打开的程序。
How to execute/open/run another program from C ?:
使用system
How not to block on it?
您必须实施多任务处理,因此请使用 fork
创建另一个进程或 pthread_create
要创建另一个线程,请查看 this
I would like to have cross-platform or minimum macOS/Windows/Linux(Ubuntu) working solution.
system
适用于 linux 和 windows 但我对其他平台没有任何想法
POSIX 方法(也许也可以在 Windows 中使用 -- https://technet.microsoft.com/en-us/library/bb463220.aspx?) 是使用 fork + exec* 组合:
您使用 fork 创建一个复制当前进程的新进程。 您对该进程的句柄是一个 int 进程标识符 (pid):
int pid;
if (0 > (pid=fork()){
perror("fork failed");
return -1;
}
if (0 == pid){
//CHILD PROCESS
printf("I'm the child process, my pid is: %d\n", getpid());
}
//pid > 0 ==> PARENT PROCESS
puts ("I'm the parent process");
printf("The pid of the child I've just spawned is %d\n", pid);
对于子进程中的 运行 可执行文件,使用 exec* 函数替换当前(例如,如果您 运行 在子进程中使用子进程)进程映像从可执行文件加载的过程映像。
在父进程中,您可以使用 pid 句柄来 kill 进程(=要求它终止):
kill(pid, SIGTERM); //please terminate
并且您可以使用 waitpid 在它终止后检索其退出状态。
( system 内部使用 fork
+ execv
(它执行 shell)+ waitpid
。因为 waitpid
部分是'separate in system
,system
让你等待子进程完成。)
您可能还想研究 dup2 and pipe or socketpair 以设置与子进程的基于文件描述符的通信通道(还有其他选项,例如共享内存、消息队列或信号,如果您只需要非常基本的沟通)。
联机帮助页是管理进程和 IPC 的良好资源。