Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用C程序调用linux命令cmp_C_Linux_Fork_Cmp - Fatal编程技术网

用C程序调用linux命令cmp

用C程序调用linux命令cmp,c,linux,fork,cmp,C,Linux,Fork,Cmp,我正在尝试制作一个程序,它将文件的2个路径发送到main,并调用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; //ch

我正在尝试制作一个程序,它将文件的2个路径发送到main,并调用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;
}
#包括
#包括
#包括
#包括
int main(int argc,const char*argv[]
{
pid_t pid;
int stat;
//子进程
如果((pid=fork())==0)
{
execl(“/usr/bin/cmp”、“/usr/bin/cmp”、“-s”、argv[1],argv[2],NULL);
}
//父进程
其他的
{
WEXIT状态(stat);
如果(stat==0)
返回2;
else if(stat==1)
return 1;//永远不要到达这里
}
printf(“%d\n”,stat);
返回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);
  // ...
这样做:

//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);
在代码中:

WEXITSTATUS(&stat);
尝试从指针提取状态,但
WEXITSTATUS()
int
作为参数

必须是:

WEXITSTATUS(stat);

有一个宏,
WEXITSTATUS
用于获取返回值。还要确保cmp在出错时返回1,而不是
非零
。在出错时返回>1,如果文件不同,则返回1。为什么?P.S改为WEXITSTATUS,现在它总是返回2(stat==0总是)@Jjang你能用
WEXTISTATUS
编辑并添加WEXITSTATUS而不是等待来显示你的新代码吗。但是仍然不起作用有一个宏,
WEXITSTATUS
用于获取返回值。还要确保cmp在出错时返回1,而不是
非零
。在出错时返回>1,如果文件不同,则返回1。为什么?P.S改为WEXITSTATUS,现在它总是返回2(stat==0总是)@Jjang你能用
WEXTISTATUS
编辑并添加WEXITSTATUS而不是等待来显示你的新代码吗。但仍然不起作用