如何使用系统调用运行命令" execve#34;另一个节目

时间:2015-04-03 09:33:56

标签: linux system-calls

我写了一个comp.out,它接受主argv的2个参数,并在文件之间进行比较。主要必须返回值1,2,3,其中3表示相同,2表示相同,1表示不相同。 exmp:./ comp.out /home/demo/code/1.txt /home/demo/code/2.txt 在另一个程序中,我正在尝试应用这个“comp.out”我写的。 问题是,我需要知道它的返回状态是什么,并使其工作。 我注意到我在execvp命令中收到了“-1”。这是我到目前为止编写的代码。

那么如何执行“comp.out”命令?

感谢帮助者!

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);
} 

1 个答案:

答案 0 :(得分:0)

根据man waitpid,您为状态传递的参数并未完全设置为子进程的返回代码,而是可以通过各种宏检查的值,包括

   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.

所以你的代码应该是这样的:

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));