[英]Calling linux command cmp with C program
我正在嘗試制作一個程序,該程序獲取文件到main的2條路徑,並調用linux'cmp命令以進行比較。
如果它們相等,我想返回2,如果它們不同,則返回1。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, const char* argv[])
{
pid_t pid;
int stat;
//child process
if ((pid=fork())==0)
{
execl("/usr/bin/cmp", "/usr/bin/cmp", "-s",argv[1], argv[2], NULL);
}
//parent process
else
{
WEXITSTATUS(stat);
if(stat==0)
return 2;
else if(stat==1)
return 1; //never reach here
}
printf("%d\n",stat);
return 0;
}
由於某些原因,如果文件相同,我確實會成功返回2,但是如果它們不同,它將不會進入if(stat == 1),而是返回0。為什么會這樣? 我檢查了通過終端在文件上的cmp是否確實返回1(如果它們不同),那么為什么這不起作用?
像這樣做:
//parent process
else
{
// get the wait status value, which possibly contains the exit status value (if WIFEXITED)
wait(&status);
// if the process exited normally (i.e. not by signal)
if (WIFEXITED(status))
// retrieve the exit status
status = WEXITSTATUS(status);
// ...
在您的代碼中:
WEXITSTATUS(&stat);
試圖從指針中提取狀態,但是WEXITSTATUS()
將int
作為參數。
一定是:
WEXITSTATUS(stat);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.