首页 文章

fork多个子进程来运行其他程序

提问于
浏览
0

我想从父程序(称为守护进程)开始使用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 回答

  • 1

    不要从子节点调用 system() ,而是使用 exec*() 系列函数的成员 .

    fork() ed off子进程调用 execXYZ() 将通过从传递给 execXYZ() 调用的内容创建的新进程替换子进程 .

    请注意,如果 execXYZ() 成功,它会返回 not .


    执行 /bin/ls -alrt *.c 的示例:

    • 该系列的 execl*() 成员期望每个空格分离的命令行选项作为单个参数 .
    execl("/bin/ls", "ls", "-alrt", "*.c", (char*) 0);
    execlp("ls", "ls", "-alrt", "*.c", (char*) 0);
    
    • 该系列的 execv*() 成员期望参数传递给 main() 的方式中每个空格分开的命令行选项:
    char * const argv[] = {
      "ls",
      "-alrt",
      "*.c",
      NULL,
    }
    
    execv("/bin/ls", argv);
    execvp("ls", argv);
    

    exec*p() 系列成员使用环境变量 PATH 来搜索要执行的二进制文件 . 因此,对于此示例(对于系统命令 ls ),需要指定路径 .


    在测试程序:

    #include <unistd.h>  
    #include <stdio.h>
    
    /* This should list the current working directory. */
    
    int main(void)
    {
      execl("/bin/ls", "ls", "-al", "-rt", (char*) 0);
      perror("execl() failed");
      return 0;  
    }
    
  • 2

    忽略 sh -c 条目的最简单方法是:

    sprintf(cmd, "exec ./test %s", argum);
    

    exec 用命令替换 system() 运行的shell,而不是让shell挂起,直到 ./test 进程终止 .

    alk在他的answer中概述了替代方案 - 使用 exec*() 系列函数(系统调用) .

相关问题