Execute a terminal command from a Cocoa app

后端 未结 12 2315
既然无缘
既然无缘 2020-11-22 06:34

How can I execute a terminal command (like grep) from my Objective-C Cocoa application?

12条回答
  •  忘了有多久
    2020-11-22 06:58

    fork, exec, and wait should work, if you're not really looking for a Objective-C specific way. fork creates a copy of the currently running program, exec replaces the currently running program with a new one, and wait waits for the subprocess to exit. For example (without any error checking):

    #include 
    #include 
    


    pid_t p = fork();
    if (p == 0) {
        /* fork returns 0 in the child process. */
        execl("/other/program/to/run", "/other/program/to/run", "foo", NULL);
    } else {
        /* fork returns the child's PID in the parent. */
        int status;
        wait(&status);
        /* The child has exited, and status contains the way it exited. */
    }
    
    /* The child has run and exited by the time execution gets to here. */
    

    There's also system, which runs the command as if you typed it from the shell's command line. It's simpler, but you have less control over the situation.

    I'm assuming you're working on a Mac application, so the links are to Apple's documentation for these functions, but they're all POSIX, so you should be to use them on any POSIX-compliant system.

提交回复
热议问题