gpt4 book ai didi

linux - 如何使用系统调用 "execvp"为另一个程序运行命令

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:36 24 4
gpt4 key购买 nike

我编写了一个 comp.out,它接受主 argv 的 2 个参数并在文件之间进行比较。 main 必须返回值 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);
}

最佳答案

根据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.

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

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

关于linux - 如何使用系统调用 "execvp"为另一个程序运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29429622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com