linux创建进程的命令,Linux下创建进程

节选自《Advanced Linux Programming》

通常有两种方式,第一种是使用system函数,位于stlib.h头文件下,system 建立了一个运行着标准Bourne shell( /bin/sh)的子进程,然后将命令交由它执行 。

因为 system 函数使用 shell 调用命令,它受到系统 shell 自身的功能特性和安全缺陷的限制 ,因此, fork 和exec 才是推荐用于创建进程的方法。

运行一个子程序的最常见办法是先用 fork 创建现有进程的副本,然后在得到的子进程中用 exec 运行新程序。这样在保持原程序继续运行的同时,在子进程中开始运行新的程序。

示例代码:

#include

#include

#include

#include

int spawn(char *program, char **arg_list)

{

pid_t child_pid;

child_pid = fork(); //复制当前进程

if (child_pid != 0) //父进程

return child_pid;

else

{

execvp(program, arg_list);

fprintf(stderr, "an error occurred in execvp\n");

abort();

}

}

int main()

{

char *arg_list[] =

{

"ls", //argv[0]

"-l",

"/",

NULL //参数列表必须以 NULL 指针结束

};

spawn(arg_list[0], arg_list);

printf("done with main program\n");

return 0;

}

标签:child,创建,Linux,pid,list,arg,进程,include

来源: https://www.cnblogs.com/castor-xu/p/14373678.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值