Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

c - How to create a process on Mac OS using fork() and exec()

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. Should I use these to create a process on the Mac or are there any platform specific functions to be used?

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
{
    //[...]
}

Any idea if this could work under Mac OS X as well, because my child process is simply not being launched, while there are no errors that would come up.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...