This question already has an answer here:
I Experimented the system function call. It is used to execute the command with in the program. The man page contains the following information about the return value of system.
RETURN VALUE
The value returned is -1 on error (e.g. fork(2) failed), and the return status of the command otherwise.
As per the man page reference, I checked the following program.
Program:
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("System returns: %d\n",system("ls a"));
}
Output:
$ ./a.out
ls: cannot access a: No such file or directory
System returns: 512
$ ls a
ls: cannot access a: No such file or directory
mohanraj@ltsp63:~/Advanced_Unix/Chapter8/check$ echo $?
2
$
The above output shows that, return value of system function is 512 and the exit status of ls a
command is 2. As per the
reference, I expect the return value of system function is equal to exit status of the ls command. But the value becomes different.
Why?
The return value is the exit status of the shell, see
sh(1)
,bash(1)
or whatever you have configured inSHELL
environment variable. By the way, the shell usually returns the last command executed exit value, but that can not be the case if you have hit theCtrl-C
key or sent a signal to the process. Check in the manual page for the exit value of the shell on these cases.You forgot to read the whole section.