posix_spawn_⽤C语⾔在Linux上创建⼦进程的posix_spawn⽰
exitedposix_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 <stdlib.h>
#include <stdio.h>
#include <.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 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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。