2013-10-28 31 views

回答

1

您可以通过以下方式使用forkexecv系统调用起来:

if (!fork()){ // create the new process 
    execl(path, *arg, ...); // execute the new program 
} 

fork系统调用创建一个新的进程,而execv系统调用启动在路径中指定的应用程序的执行。 例如,您可以使用以下函数spawn,它们的参数是要执行的应用程序的名称及其参数列表。

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

int spawn (char* program, char** arg_list) 
{ 
pid_t child_pid; 
/* Duplicate this process. */ 
child_pid = fork(); 
if (child_pid != 0) 
    /* This is the parent process. */ 
    return child_pid; 
else { 
    /* Now execute PROGRAM, searching for it in the path. */ 
    execvp (program, arg_list); 
    /* The execvp function returns only if an error occurs. */ 
    fprintf (stderr, “an error occurred in execvp\n”); 
    abort(); 
    } 
} 

int main() 
{ 
/* The argument list to pass to the “ls” command. */ 
    char* arg_list[] = { 
    “ls”, /* argv[0], the name of the program. */ 
    “-l”, 
    “/”, 
    NULL /* The argument list must end with a NULL. */ 
    }; 

    spawn (“ls”, arg_list); 
    printf (“done with main program\n”); 
    return 0; 
} 

本示例摘自本012.的3.2.2章节。 (在Linux中的开发非常好的参考)。

+0

我觉得'fork'会产生一个子进程。但是,我想发起一个由论点给出的新过程。 'execv'足以达到我的目的吗? – doptimusprime

+0

是的。 'Fork'创建一个新的进程,它是父进程的副本。当调用'execv'时,当前的过程映像被替换为新的过程映像。这是linux shell运行新程序的方式 –

+0

您应该注意'fork()'可以返回'<0'来表示错误,而代码无法正确处理。参数列表也应该是'const char *',而不是'char *'。好书;如果我是你,我会倾倒它。 – trojanfoe

1

正如已经指出的那样,您可以使用fork()/exec(),但更近的系统调用是posix_spawn()manpage)。但是,有一些使用它的示例代码是here(请注意,此代码还为Windows提供了使用CreateProcess() API的功能,这可能是您应该使用的功能反正在Windows下使用)。