本文共 2287 字,大约阅读时间需要 7 分钟。
posix_spawn
The functions create a new child process from the specified process constructed from a regular executable file. It can be used to replace the relative complex “fork-exec-wait” methods with and . However, compared to fork()
and exec()
, posix_spawn()
is less introduced if you search on the Web. The 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.
函数根据由常规可执行文件构造的指定过程创建新的子过程。 它可以用来用和代替相对复杂的“ fork-exec-wait”方法。 但是,与fork()
和exec()
,如果在Web上搜索,则不会引入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#include #include <.h>#include #include #include 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 by exec()
,它返回新的子进程的pid,您可以通过waitpid()
. Of course, waitpid()
等待。 当然, () ()
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 from .
与fork()
/ vfork()
不同之处在于,您实现的逻辑在同一进程内,因此您无需考虑子进程执行哪段代码以及父进程执行哪段代码。 它还避免了来自问题。
翻译自:
posix_spawn
转载地址:http://pplwd.baihongyu.com/