【问题标题】:_wspawnl/_spawnl equivalent on Mac OS X or LinuxMac OS X 或 Linux 上的 _wspawnl/_spawnl 等效项
【发布时间】:2013-10-28 11:03:35
【问题描述】:

我只是将代码移植到在 Windows 上使用 _tspawnl 的 Mac OS X。

在 Mac OS X 或 Linux 上是否有与 _tspawnl 等效的内容?

或者是否有任何等同于_tspawnl的posix

【问题讨论】:

    标签: c++ c linux macos posix


    【解决方案1】:

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

    此示例取自book 的第 3.2.2 章。 (对于在 Linux 中的开发来说真的很好的参考)。

    【讨论】:

    • 我认为fork 会产生一个子进程。但是,我想启动一个由参数给出的新进程。 execv 是否足以满足我的目的?
    • 是的。 Fork 创建一个新进程,它是父进程的副本。当execv 被调用时,当前过程映像被一个新的过程映像替换。这就是 linux shell 运行新程序的方式
    • 您应该注意fork() 可以返回&lt; 0 以表示错误,代码没有正确处理。参数列表也应该是const char *,而不是char *。好书;如果我是你,我会扔掉它。
    【解决方案2】:

    您可以使用fork()/exec(),正如已经指出的那样,但是更接近的系统调用是posix_spawn() (manpage)。

    设置起来可能有点麻烦,但是有一些使用它的示例代码是here(请注意,此代码还使用CreateProcess() API 为 Windows 提供功能,这可能是无论如何你应该在 Windows 下使用什么)。

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 2010-09-05
      • 2010-10-08
      • 1970-01-01
      • 2012-06-06
      相关资源
      最近更新 更多