2013-03-24 83 views
0

我正在尝试制作一个程序,该程序获取2个文件到main的程序,并调用linux的cmp命令来比较它们。用C程序调用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,如果他们不同,那么为什么这不起作用?

+1

有一个宏,'WEXITSTATUS'用于获取返回值。还要确保cmp在错误时返回一个,而不是“非零”。 – Aneri 2013-03-24 10:44:41

+0

错误时返回> 1,文件不同时返回1。为什么? – Jjang 2013-03-24 10:45:46

+0

P.S改为WEXITSTATUS,现在总是返回2(stat == 0总是) – Jjang 2013-03-24 10:47:40

回答

2

做这样的:

//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); 
    // ... 
1

在您的代码:

WEXITSTATUS(&stat); 

尝试提取从一个指针状态,但WEXITSTATUS()需要int作为参数。

必须是:

WEXITSTATUS(stat);