我在 Linux 平台上开发。
我想在我的库中创建一个新进程而不替换当前正在执行的镜像。
因为我正在开发一个库,所以我没有 main 函数。
我想在调用者应用程序关闭后继续新进程(就像 CreateProcess
Windows API)。
在 Linux 下可以吗?
类似于这个函数:
void Linux_CreateProcess(const char* app_name)
{
// Executing app_name.
// ???????? what is the code ??????
// app_name is running and never close if current application close.
return;
}
注意:
system()
阻塞当前进程,不好。我想继续当前的流程。exec()
族替换当前正在执行的图像,不好。popen()
在当前进程关闭时关闭新进程。
最佳答案
前面已经提到了fork
/exec
组合,但还有posix_spawn
可以用作 fork
+ exec
的替代品的函数系列,并且更直接地等效于 CreateProcess
。这是两种可能性的示例:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <spawn.h>
#include <sys/wait.h>
extern char **environ;
void test_fork_exec(void);
void test_posix_spawn(void);
int main(void) {
test_fork_exec();
test_posix_spawn();
return EXIT_SUCCESS;
}
void test_fork_exec(void) {
pid_t pid;
int status;
puts("Testing fork/exec");
fflush(NULL);
pid = fork();
switch (pid) {
case -1:
perror("fork");
break;
case 0:
execl("/bin/ls", "ls", (char *) 0);
perror("exec");
break;
default:
printf("Child id: %i\n", pid);
fflush(NULL);
if (waitpid(pid, &status, 0) != -1) {
printf("Child exited with status %i\n", status);
} else {
perror("waitpid");
}
break;
}
}
void test_posix_spawn(void) {
pid_t pid;
char *argv[] = {"ls", (char *) 0};
int status;
puts("Testing posix_spawn");
fflush(NULL);
status = posix_spawn(&pid, "/bin/ls", NULL, NULL, argv, environ);
if (status == 0) {
printf("Child id: %i\n", pid);
fflush(NULL);
if (waitpid(pid, &status, 0) != -1) {
printf("Child exited with status %i\n", status);
} else {
perror("waitpid");
}
} else {
printf("posix_spawn: %s\n", strerror(status));
}
}
关于c++ - Linux 创建进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5883462/