我想从父程序(称为守护进程)开始使用args测试程序的5个子进程(所有5个并行,不等待完成) .
我有以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char* argv[]){
//missing irrelevant part where argum is set
int status,i;
char cmd[512];
pid_t process_id = 0;
for (i=0; i<=5;i++)
{
process_id = fork();
if (process_id < 0)
{
printf("fork failed - %d!\n",i);
continue;
}
else if(process_id > 0) {
printf("process_id of child process %d \n", process_id);
}
else
{
sprintf(cmd,"./test %s",argum);
status = system(cmd);
exit(0);
}
}
return 0;
}
它启动它们但是当我运行ps -aux来查看进程时,除了好的进程(例如:./ test [args])之外还有一些重复项:sh -c ./test [args]
How can I get rid of those starting with "sh -c" ?
2 回答
不要从子节点调用
system()
,而是使用exec*()
系列函数的成员 .从
fork()
ed off子进程调用execXYZ()
将通过从传递给execXYZ()
调用的内容创建的新进程替换子进程 .请注意,如果
execXYZ()
成功,它会返回 not .执行
/bin/ls -alrt *.c
的示例:execl*()
成员期望每个空格分离的命令行选项作为单个参数 .execv*()
成员期望参数传递给main()
的方式中每个空格分开的命令行选项:exec*p()
系列成员使用环境变量PATH
来搜索要执行的二进制文件 . 因此,对于此示例(对于系统命令ls
),需要指定路径 .在测试程序:
忽略
sh -c
条目的最简单方法是:exec
用命令替换system()
运行的shell,而不是让shell挂起,直到./test
进程终止 .alk在他的answer中概述了替代方案 - 使用
exec*()
系列函数(系统调用) .