简体   繁体   English

如何为另一个程序运行命令usig sys调用“ execvp”

[英]how to run a command usig sys call “execvp” for another program

i've written a comp.out which accept 2 arguments to the main argv and compare between the files. 我写了一个comp.out,它接受2个主argv参数并在文件之间进行比较。 the main must return the values 1,2,3 where 3 means identical, 2 almost identical and 1 not identical. 主机必须返回值1,2,3,其中3表示相同,2表示几乎相同,1表示不相同。 exmp : ./comp.out /home/demo/code/1.txt /home/demo/code/2.txt in another program i'm trying to apply this "comp.out" i've written. exmp:在另一个程序中,我试图应用我编写的“ comp.out”。./comp.out /home/demo/code/1.txt /home/demo/code/2.txt the thing is that i need to know what is its return status and to make it work. 问题是我需要知道它的返回状态并使其工作。 I've noticed i had recieved "-1" in the execvp command. 我注意到我在execvp命令中收到了“ -1”。 this is the code i've written so far. 这是我到目前为止编写的代码。

so how do I execute the "comp.out" command? 那么如何执行“ comp.out”命令?

Thanks for the helpers! 感谢您的帮手!

void compareOutputFiles(char *path, char *arg2) {
    pid_t   runner;
    char *cmd [] = {"./comp.out",path, arg2, NULL};
    int status;
    int savedFD     = dup(0);
    int dirchange   = chdir(path);
    int fdin, fdout;

    strcat(path, "/output.txt");
    cmd[1] = path;
    fdin    = open(path,O_RDONLY);


    dup2(fdin,  0);


    if ((runner = fork()) < 0) {perror("could not make fork");}
    else if (runner == 0) {
                execvp(cmd[0],cmd); ->>>>>>>>>>>>returns -1
                exit(0);
    } else if (runner != 0) {
        waitpid(runner,&status,0);
        printf("return val :%d\n", (status));

    }
    dup2(savedFD, 0);
    close(fdin);
} 

According to man waitpid , the parameter you pass for status is not set exactly to the return code of the child process but the value that can be checked by various macros including 根据man waitpid说法,您传递给status的参数未完全设置为子进程的返回码,而是可以由各种宏检查的值,包括

   WIFEXITED(status)
          returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().

   WEXITSTATUS(status)
          returns  the  exit status of the child.  This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as
          the argument for a return statement in main().  This macro should be employed only if WIFEXITED returned true.

so your code should probably look like this: 因此您的代码应该看起来像这样:

waitpid(runner,&status,0);
printf("status: %d\n", (status));
//probably exit here or return error if child died
printf("finished normally: %d\n", WIFEXITED(status));
printf("return code: %d\n", WEXITSTATUS(status));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM