C++ _Mac OS X或Linux上的wspawnl/_spawnl等效文件
我只是将一个代码移植到Mac OS X,它正在Windows上使用C++ _Mac OS X或Linux上的wspawnl/_spawnl等效文件,c++,c,linux,macos,posix,C++,C,Linux,Macos,Posix,我只是将一个代码移植到Mac OS X,它正在Windows上使用\u tspawnl 在Mac OS X或Linux上是否有与\u tspawnl等价的东西 或者是否有任何posix等效于\u tspawnl您可以通过以下方式同时使用fork和execv系统调用: if (!fork()){ // create the new process execl(path, *arg, ...); // execute the new program } fork系统调用创建一个新进
\u tspawnl
在Mac OS X或Linux上是否有与\u tspawnl
等价的东西
或者是否有任何posix等效于
\u 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;
}
#包括
#包括
#包括
#包括
int spawn(字符*程序,字符**参数列表)
{
pid_t child_pid;
/*重复此过程*/
child_pid=fork();
如果(子pid!=0)
/*这是父进程*/
返回子对象;
否则{
/*现在执行程序,在路径中搜索它*/
execvp(程序、参数列表);
/*execvp函数仅在发生错误时返回*/
fprintf(stderr,“execvp中发生错误”);
中止();
}
}
int main()
{
/*要传递给“ls”命令的参数列表*/
char*arg_list[]={
“ls”,/*argv[0],程序的名称*/
“-l”,
“/”,
NULL/*参数列表必须以NULL结尾*/
};
产卵(“ls”,arg_列表);
printf(“使用主程序完成”);
返回0;
}
本示例摘自本手册第3.2.2章。(对于Linux开发来说,这是一个很好的参考) 如前所述,您可以使用fork()/exec()
,但是更接近的系统调用是posix_spawn()
()
然而,设置起来可能有点麻烦,但是有一些示例代码使用它(请注意,此代码还使用
CreateProcess()
API为Windows提供了功能,这可能是您在Windows下无论如何都应该使用的)。我想fork
将生成一个子进程。但是,我想启动一个新的过程,由论点给出。execv
是否足以满足我的需要?是的Fork
创建一个新进程,它是父进程的副本。调用execv
时,当前进程映像将替换为新进程映像。这就是linux shell运行新程序的方式。您应该注意,fork()
可以返回<0
表示错误,而代码没有正确处理该错误。此外,参数列表应该是const char*
,而不是char*
。伟大的书;如果我是你,我会把它扔了。