Return value of System Function [duplicate]

2019-08-10 05:38发布

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?

2条回答
小情绪 Triste *
2楼-- · 2019-08-10 06:01

The return value is the exit status of the shell, see sh(1), bash(1) or whatever you have configured in SHELL 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 the Ctrl-C key or sent a signal to the process. Check in the manual page for the exit value of the shell on these cases.

查看更多
唯我独甜
3楼-- · 2019-08-10 06:09

You forgot to read the whole section.

[T]he return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED() WEXITSTATUS() and so on).

查看更多
登录 后发表回答