簡體   English   中英

在C / Linux中返回什么系統功能和cp命令

[英]What system function and cp command return in 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);
}

所以任何人請向我解釋一下

使用系統的返回值的正確方法是使用特定等待的宏

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

256通常表示存在權限問題

system的手冊頁指出:

返回值出錯時返回的值為-1(例如fork(2)失敗),否則返回命令的返回狀態。 后一種返回狀態采用wait(2)中指定的格式。 因此,該命令的退出代碼將為WEXITSTATUS(status)。 如果無法執行/ bin / sh,則退出狀態將是退出(127)的命令的狀態。

如果command的值為NULL,則如果shell可用,則system()返回非零,否則返回零。 system()不會影響其他任何孩子的等待狀態。

因此,當WIFEXITED(a)為true時,可以使用WEXITSTATUS(a)獲取退出狀態。

通常,命令的可能退出代碼在手冊頁中指定。 對於cp ,沒有任何文檔,因此您不能依賴任何東西。 您可能會考慮使用較低級別的系統命令(例如openlink )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM