如何在 Mac OS 上使用 fork() 和 exec() 创建进程 [英] How to create a process on Mac OS using fork() and exec()

查看:58
本文介绍了如何在 Mac OS 上使用 fork() 和 exec() 创建进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个相对简单、独立的进程启动器",我希望能够在 Windows(XP、Vista、7)、Linux(Ubuntu 10.10),尤其是 Mac OS X (10.6).Linux 和 Windows 基本上可以工作,但我在 Mac 版本上遇到了一些问题.我希望 fork()exec() 函数在 Mac OS 下的工作方式与在 Linux 中的工作方式相同.所以我的第一个问题是:

I am working on a relatively simple, independent "process starter" that I would like to get to work on Windows (XP, Vista, 7), Linux (Ubuntu 10.10) and especially Mac OS X (10.6). Linux and Windows basically work, but I'm having some trouble with the Mac version. I was hoping fork() and exec() functions would work the same way under Mac OS as they work in Linux. So my first question is:

  1. 我应该使用这些来创建一个在 Mac 上处理或有任何平台特定功能用过吗?

我当前用于调试的代码(在 Linux 下运行良好)如下所示:

My current code (which worked fine under Linux) to debug this looks something like this:

pid_t processId = 0;
if (processId = fork()) == 0)
{
    const char * tmpApplication = "/Path/to/TestApplication";

    int argc = 1;
    char * argv[argc + 1];

    argv[0] = tmpApplication;
    argv[1] = NULL;

    execv(tmpApplication, argv);
}else
{
    //[...]
}

不知道这是否也可以在 Mac OS X 下运行,因为我的子进程根本没有启动,而不会出现错误.

谢谢!

推荐答案

以下程序改编自您的代码,在 OS X 下对我来说效果很好:

The following program, adapted from your code, works just fine for me under OS X:

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

int main (void) {
    pid_t processId;
    if ((processId = fork()) == 0) {
        char app[] = "/bin/echo";
        char * const argv[] = { app, "success", NULL };
        if (execv(app, argv) < 0) {
            perror("execv error");
        }
    } else if (processId < 0) {
        perror("fork error");
    } else {
        return EXIT_SUCCESS;
    }
    return EXIT_FAILURE;
}

我建议您从这个简单的片段开始,如果它有效,请继续添加内容,直到找到导致它崩溃的原因.

I suggest you start with this simple fragment, and if it works keep adding things until you find what makes it break.

这篇关于如何在 Mac OS 上使用 fork() 和 exec() 创建进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆