[英]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);
}
所以任何人請向我解釋一下
256通常表示存在權限問題
system
的手冊頁指出:
返回值出錯時返回的值為-1(例如fork(2)失敗),否則返回命令的返回狀態。 后一種返回狀態采用wait(2)中指定的格式。 因此,該命令的退出代碼將為WEXITSTATUS(status)。 如果無法執行/ bin / sh,則退出狀態將是退出(127)的命令的狀態。
如果command的值為NULL,則如果shell可用,則system()返回非零,否則返回零。 system()不會影響其他任何孩子的等待狀態。
因此,當WIFEXITED(a)
為true時,可以使用WEXITSTATUS(a)
獲取退出狀態。
通常,命令的可能退出代碼在手冊頁中指定。 對於cp
,沒有任何文檔,因此您不能依賴任何東西。 您可能會考慮使用較低級別的系統命令(例如open
或link
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.