Linux下创建进程

节选自《Advanced Linux Programming》

通常有两种方式,第一种是使用system函数,位于stlib.h头文件下,system 建立了一个运行着标准Bourne shell( /bin/sh)的子进程,然后将命令交由它执行 。
因为 system 函数使用 shell 调用命令,它受到系统 shell 自身的功能特性和安全缺陷的限制 ,因此, fork 和exec 才是推荐用于创建进程的方法。
运行一个子程序的最常见办法是先用 fork 创建现有进程的副本,然后在得到的子进程中用 exec 运行新程序。这样在保持原程序继续运行的同时,在子进程中开始运行新的程序。

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

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;
}

 

posted @ 2021-02-04 16:58  castor_xu  阅读(645)  评论(0编辑  收藏  举报