posix_spawn
The posix_spawn() and posix_spawnp() functions create a new child process from the specified process image constructed from a regular executable file. It can be used to replace the relative complex “fork-exec-wait” methods with fork() and exec(). However, compared to fork() and exec(), posix_spawn() is less introduced if you search on the Web. The posix_spawn() manual provides details. However, it is still not sufficient especially for beginners. Here, I give an example of C program using posix_spawn() to create child processes.
posix_spawn()和posix_spawnp()函数根据由常规可执行文件构造的指定过程映像创建新的子过程。 它可以用来用fork()和exec()代替相对复杂的“ fork-exec-wait”方法。 但是,与fork()和exec() ,如果在Web上搜索,则不会引入posix_spawn() 。 posix_spawn()手册提供了详细信息。 但是,对于初学者来说,这仍然是不够的。 在这里,我举一个使用posix_spawn()创建子进程的C程序示例。
The program is to run the command by /bin/sh -c that you pass as the first argument to the program. The run.c source code is as follows.
该程序将通过/bin/sh -c运行命令,并将其作为第一个参数传递给该程序。 run.c源代码如下。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <spawn.h>
#include <sys/wait.h>
extern char **environ;
void run_cmd(char *cmd)
{
pid_t pid;
char *argv[] = {"sh", "-c", cmd, NULL};
int status;
printf("Run command: %s\n", cmd);
status = posix_spawn(&pid, "/bin/sh", NULL, NULL, argv, environ);
if (status == 0) {
printf("Child pid: %i\n", pid);
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));
}
}
int main(int argc, char* argv[])
{
run_cmd(argv[1]);
return 0;
}
From the example, you can find the posix_spawn() has its advantages and flexibility over other similar ones although it is a little tedious with 6 arguments.
从该示例中,您可以发现posix_spawn()具有优于其他类似优点和灵活性的优点,尽管它有6个参数有点乏味。
system()system()exec(), it returns the new child process’ pid which you can wait byexec(),它返回新的子进程的pid,您可以通过waitpid(). Of course,waitpid()等待。 当然,system()system ()Difference from
fork()/vfork(), the logic you implement is within the same process and you do not need to think about which piece of code is executed by the child process and which is executed by the parent process. It also avoid problems fromvfork().与
fork()/vfork()不同之处在于,您实现的逻辑在同一进程内,因此您无需考虑子进程执行哪段代码以及父进程执行哪段代码。 它还避免了来自vfork()问题。
翻译自: https://www.systutorials.com/a-posix_spawn-example-in-c-to-create-child-process-on-linux/
posix_spawn
本文介绍了如何使用C语言在Linux上通过`posix_spawn`函数创建子进程,作为替代传统的`fork-exec-wait`方法。虽然`posix_spawn`需要6个参数,但其具有灵活性和优势,程序逻辑都在同一进程中执行,避免了`fork()`可能带来的问题。

239


被折叠的 条评论
为什么被折叠?



