0

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を返すことを確認しましたが、なぜこれが機能しないのですか?

4

2 に答える 2

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);
  // ...
于 2013-03-24T10:54:09.223 に答える
1

あなたのコードでは:

WEXITSTATUS(&stat);

ポインタからステータスを抽出しようとしますWEXITSTATUS()int、パラメータとして使用します。

でなければなりません:

WEXITSTATUS(stat);
于 2013-03-24T10:55:12.733 に答える