C-在后台启动外部Programa并获取pid [英] C - start external programa in background and get pid

查看:104
本文介绍了C-在后台启动外部Programa并获取pid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,运行外部程序并获取该程序的PID的最佳方法是什么? 我在这里看到了有关使用fork()的一些答案……但是据我了解,fork()复制了当前过程并创建了一个子代.如果可能的话,我想创建一个完全分离的上下文……而获得PID的原因是将来会杀死这个确切的过程.当服务器可以发送命令以启动客户端上的某些程序时,我正在构建客户端/服务器程序.这些程序是外部程序,多个具有相同名称/可执行文件的c程序可以同时运行(这就是为什么我无法尝试"通过程序名找到pid的原因).另外,这些程序应在后台"运行....我的意思是,我无法锁定我的调用函数. 我不确定在这种情况下fork()是否能帮到我.

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.

推荐答案

我想做的是使用

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-在后台启动外部Programa并获取pid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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