我只是将一个代码移植到在Windows上使用_tspawnl
的Mac OS X。_wspawnl/_spawnl在Mac OS X或Linux上相当于
在Mac OS X或Linux上是否有与_tspawnl
等价的东西?
或有任何等效POSIX到_tspawnl
我只是将一个代码移植到在Windows上使用_tspawnl
的Mac OS X。_wspawnl/_spawnl在Mac OS X或Linux上相当于
在Mac OS X或Linux上是否有与_tspawnl
等价的东西?
或有任何等效POSIX到_tspawnl
您可以通过以下方式使用fork
和execv
系统调用起来:
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中的开发非常好的参考)。
我觉得'fork'会产生一个子进程。但是,我想发起一个由论点给出的新过程。 'execv'足以达到我的目的吗? – doptimusprime
是的。 'Fork'创建一个新的进程,它是父进程的副本。当调用'execv'时,当前的过程映像被替换为新的过程映像。这是linux shell运行新程序的方式 –
您应该注意'fork()'可以返回'<0'来表示错误,而代码无法正确处理。参数列表也应该是'const char *',而不是'char *'。好书;如果我是你,我会倾倒它。 – trojanfoe