根据条件在C中异步运行外部程序

时间:2015-10-19 03:56:39

标签: c process exec fork

到目前为止,我认为我采取了一种很好的方法。在这段代码中,我希望条件导致aflag设置为1或2.然后根据数字,将启动相应的程序。所以如果aflag为1,那么/path/to/app1需要在后台启动,这个程序需要继续。如果aflag为2则需要启动/path/to/app2

我可以确定该进程是否来自fork(),但我不想在我的main函数中执行fork(),因为我不想在它之前执行后台进程启动该计划。

我也希望尽可能避免使用pthread和系统函数,因为我正在寻找资源最少的答案,人们说fork() + exec()是可行的方法。

如何确定主要流程是否为孩子?我希望它能够知道要运行的程序。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

    static char *app1="/path/to/app1";
    static char *app2="/path/to/app2";
    static char *app;

    int otherfunction(){
      int aflag=0;
      //do something (will fill in later)
      if (aflag==1){
        //run app 1
        app=app1;
        fork();
      }
      if (aflag==2){
        //run app 2
        app=app2;
        fork();
      }

    }

int main(){
      int imachild=???;
      if (imachild==1){
        execl(app,NULL);
        return 0;
      }
      while(1){
      otherfunction();
      }
    }

1 个答案:

答案 0 :(得分:0)

希望下面的代码会给你一些想法。显然这只是带有infinete循环的示例代码。真实代码可能会让父接受输入来设置aflag值。但它说明了父线程如何分离新进程以及新子进程如何决定运行哪个应用程序。父进程返回到下一个fork操作。

static char *app1="/path/to/app1";
static char *app2="/path/to/app2";

int main(void)
{
    pid_t pid;
    int aflag = SOME_VALUE_OBTAINED_FROM_SOMEWHERE;
    const char *app = NULL;

    while (1) {
        pid = fork();
        if (pid == -1) {
            printf("fork error\n");
        } else if (pid > 0) { 
            /* This is child code. */
            switch (aflag) {
            case 0:
                app = app1;        
                break;
            case 1:
                app = app2;
                break;
            }
            if (app) {
                execl(app, NULL);
                /* execl does not return on success */
                printf("execl error\n");
            } 
        } else {
            /*
             * This is the parent code - no exec. Just do 
             * something else.
             */
        }
    }

}

相关问题