[英]how to run a command usig sys call “execvp” for another program
我寫了一個comp.out,它接受2個主argv參數並在文件之間進行比較。 主機必須返回值1,2,3,其中3表示相同,2表示幾乎相同,1表示不相同。 exmp:在另一個程序中,我試圖應用我編寫的“ comp.out”。./comp.out /home/demo/code/1.txt /home/demo/code/2.txt 問題是我需要知道它的返回狀態並使其工作。 我注意到我在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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.