Reputation: 2368
Here i used below in code on linux. using cp command in system function.
I know about system function it will return the 0 if command successfully executed.otherwise it will return error code.
If here i use proper source and destination path than i got output like this
Number == 0
If i give wrong source and destination path than i got
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
Here i want to know the error code of cp
command what cp command return here.
My questions are here
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.
code :
#include <stdlib.h>
#include <stdio.h>
void main()
{
int a;
a = system("cp /home/sam/main/test /home/sam");
printf("Number == %d\n",a);
}
So any body please Explain me about this all
Upvotes: 0
Views: 8325
Reputation: 36049
The man page of system
states:
RETURN VALUE The value returned is -1 on error (e.g. fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127).
If the value of command is NULL, system() returns nonzero if the shell is available, and zero if not. system() does not affect the wait status of any other children.
So, you can get the exit status with WEXITSTATUS(a)
whene WIFEXITED(a)
is true.
In general, the possible exit codes of a command are specified in the manpage. For cp
, there is no documentation, so you can't rely on anything. You might think of going with lower-level system commands (such as open
or link
).
Upvotes: 1
Reputation: 182619
The correct way to user the return value of system is with the wait-specific macros.
if (WIFEXITED(a)) {
int rc;
rc = WEXITSTATUS(a);
printf("Exit with status: %d\n", rc);
} else {
/* Killed by a signal. */
}
Upvotes: 4