博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
posix_spawn_用C语言在Linux上创建子进程的posix_spawn示例
阅读量:2517 次
发布时间:2019-05-11

本文共 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/

你可能感兴趣的文章
HTTP协议
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
Laravel 的生命周期
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
jxl写入excel实现数据导出功能
查看>>
linux文件目录类命令|--cp指令
查看>>
.net MVC 404错误解决方法
查看>>
linux系统目录结构
查看>>
git
查看>>
btn按钮之间事件相互调用
查看>>
Entity Framework 4.3.1 级联删除
查看>>
codevs 1163:访问艺术馆
查看>>
冲刺Noip2017模拟赛3 解题报告——五十岚芒果酱
查看>>
并查集
查看>>