系统相关
首页 > 系统相关> > c – Linux CreateProcess?

c – Linux CreateProcess?

作者:互联网

我在linux平台上开发.

我想在我的库中创建一个新进程而不替换当前正在执行的图像.

因为我正在开发一个库,所以我没有主要功能.

我想在调用程序应用程序关闭后继续新进程(就像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()是标准解决方案.

使用fork()(或vfork())启动一个单独的进程,该进程将是父进程的克隆.在子进程和父进程中,继续执行,但fork在两种情况下都返回不同的值,允许您区分.然后,您可以在子进程中使用exec().

但请注意 – 从我自己的一篇博文(http://davmac.wordpress.com/2008/11/25/forkexec-is-forked-up/):

There doesn’t seem to be any simple standards-conformant way (or even a generally portable way) to execute another process in parallel and be certain that the exec() call was successful. The problem is, once you’ve fork()d and then successfully exec()d you can’t communicate with the parent process to inform that the exec() was successful. If the exec() fails then you can communicate with the parent (via a signal for instance) but you can’t inform of success – the only way the parent can be sure of exec() success is to wait() for the child process to finish (and check that there is no failure indication) and that of course is not a parallel execution.

如果在您的情况下出现问题,可以解决此问题:

[…] use pipe() to create a pipe, set the output end to be close-on-exec, then fork() (or vfork()), exec(), and write something (perhaps errno) to the pipe if the exec() fails (before calling _exit()). The parent process can read from the pipe and will get an immediate end-of-input if the exec() succeeds, or some data if the exec() failed.

(请注意,如果子进程的运行优先级低于父进程,则此解决方案容易导致优先级倒置).

还有其他答案中提到的posix_spawn,但它的可移植性稍差(特别是旧系统不可用)并且无法解决上述问题,因为它通常以fork / exec的方式实现并且可以返回成功在exec()阶段失败之前.

标签:c,linux,createprocess
来源: https://codeday.me/bug/20190929/1831309.html