C - start external programa in background and get

2019-09-13 19:51发布

问题:

In C, what's the best approach to run an external program and get PID of this program? I saw some answer here about using fork()......but as I understood, fork() copy's current proccess and create a children. If possible, I would like to create a totally separated context......and the reason to get the PID is to kill this exactly proccess in the future. I'm building a client/server program when my server can send commands to start some programs on the client. These programs are external and more then one cwith the same name/executable could run at same time (this is why I can't 'try' do find pid by program name). Also, These programs should run in 'background'....I mean, I can't lock my calling function. I'm not sure if fork() will help me in this scenario.

回答1:

What I like to do is to use posix_spawn. It's much easier to use than fork and IMO feels a lot more intuitive:

#include <spawn.h>
#include <string.h>
#include <stdio.h>

extern char **environ;

int main() {
    pid_t pid;
    char *argv[] = {"gcc", "file.c" (char*)0};

    int status = posix_spawn(&pid, "/usr/bin/gcc", NULL, NULL, argv, environ);
    if(status != 0) {
        fprintf(stderr, strerror(status));
        return 1;
    }
    return 0;
}


标签: c linux fork