2

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.

Jonis Maurin Ceará
  • 449
  • 1
  • 4
  • 11
  • study this thread: http://stackoverflow.com/questions/5883462/linux-createprocess#5884588 – cmks Apr 16 '17 at 17:51
  • You can use daemon(3) and safe pid to some file, like other deamons – fghj Apr 16 '17 at 17:54
  • 1
    Using `fork()` plus one of the `exec*()` functions is the normal way to do this. It's more straight-forward than `posix_spawn()` if you need to reorganize the I/O or close pipe descriptors or anything else. You can manipulate those with `posix_spawn()`, but it is hard work. – Jonathan Leffler Apr 16 '17 at 23:57

1 Answers1

2

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;
}
Elias Kosunen
  • 433
  • 7
  • 20
  • This looks exactly what I need! I'll test and report here :) Tks! – Jonis Maurin Ceará Apr 16 '17 at 20:56
  • There's just one small problem....I can't kill this proccess :( What am I doing wrong? I've changed the command to open executable directly (without 'sh') and everything is working fine, PID is returned and I can confirm using htop that pid is correct. But every signal that I send (either using C or command line) doesn't do anything, proccess still running. – Jonis Maurin Ceará Apr 19 '17 at 01:13