I'm trying to make a program which is getting 2 pathes for files to main, and calling linux' cmp command in order to compare them.
If they equal, I want to return 2, and if they're different, 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;
}
For some reason if the files are the same, I do succeed in returning 2, but if they're different, it won't go into if(stat==1), but to return 0. Why is this happening? I checked that cmp on the files through terminal does truly return 1 if they're different, so why this doesnt work?
Do it like this:
//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);
// ...