在C / Linux中返回什么系统函数和cp命令

时间:2012-03-21 11:07:25

标签: c linux

这里我在linux下的代码中使用了以下代码。 在系统函数中使用cp命令。

我知道系统函数,如果命令成功执行,它将返回0。否则它将返回错误代码。

如果在这里我使用正确的源和目标路径,而不是像我这样输出

Number == 0

如果我提供错误的来源和目的地路径

cp: cannot create regular file `/home/sam/test/test': No such file or directory
Number == 256

cp: cannot stat `/home/sam/main/test2/test': Not a directory
Number == 256

这里我想知道cp的错误代码命令cp命令返回此处。

我的问题在这里

1 System function return error code of cp command?
2 Can i get error code of cp command from source code of cp command?
3 i want to handle all types of error in this cp command.

代码:

#include <stdlib.h>
#include <stdio.h>

void main()
{
    int a;
    a = system("cp /home/sam/main/test /home/sam");
    printf("Number == %d\n",a);
}

所以任何身体都请向我解释这一切

3 个答案:

答案 0 :(得分:4)

使用wait-specific macros的正确方法来使用系统的返回值。

if (WIFEXITED(a)) {
    int rc;
    rc = WEXITSTATUS(a);
    printf("Exit with status: %d\n", rc);
} else {
    /* Killed by a signal. */
}

答案 1 :(得分:1)

system的手册页:

  

返回值          错误时返回的值为-1(例如fork(2)失败),否则返回命令的返回状态。后者回归          status的格式为wait(2)中指定的格式。因此,命令的退出代码将是WEXITSTATUS(状态)。如果          无法执行/ bin / sh,退出状态将是退出(127)的命令。

     

如果command的值为NULL,如果shell可用,则system()返回非零值,否则返回0。   system()不会影响任何其他孩子的等待状态。

因此,当WEXITSTATUS(a)为真时,您可以使用WIFEXITED(a)获取退出状态。

通常,在联机帮助页中指定命令的可能退出代码。对于cp,没有文档,因此您不能依赖任何内容。您可能会考虑使用较低级别的系统命令(例如openlink)。

答案 2 :(得分:1)

256通常表示存在权限问题