c++ - Linux 创建进程?

标签 c++ c linux createprocess

我在 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/

相关文章:

linux - shell脚本不打印值

c - 为什么 bits/libc-header-start.h 文件夹包含在 stdio.h header 中

c++ - 按顺序查找boost::multi_index,按顺序获取下一个元素

c++ - 可以将 std::streambuf 的自定义实现中的异常传递给流用户吗?

c++ - 将调用什么重载的 C++ 函数?

c - 为什么这段代码不能识别任何 if 语句?

linux -/usr/include/linux和linux内核源码中的include文件夹有什么区别?

c++ - 使用 OpenCV 在图像上悬停时打印鼠标指针的像素坐标

c - 如何清除linux中的socket缓冲区

c - 错误 : expected '=' , ',' , ';' , 'asm' 或 '__attribute__' 在 C 中的 '*' token 之前