加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

system()的返回值不是执行程序的返回值

发布时间:2020-12-16 10:10:03 所属栏目:百科 来源:网络整理
导读:我想执行一个可执行文件,其main()使用system()返回2. 这就是我做的 #include stdio.h#include string.hint main(int argc,char *agrv[]){ char command[7]; strcpy(command,"./test1"); printf("The return value: %dn",system(command)); return 0;} 和tes
我想执行一个可执行文件,其main()使用system()返回2.
这就是我做的

#include <stdio.h>
#include <string.h>

int main(int argc,char *agrv[])
{
    char command[7];
    strcpy(command,"./test1");
    printf("The return value: %dn",system(command));

    return 0;
}

和test1是

#include <stdio.h>

int main(void)
{
    printf("test1 has been executed and its return value is 2n");

    return 2;
}

这就是我得到的

test1 has been executed and its return value is 2
The return value: 512

我的问题是为什么我得到512.

解决方法

系统的返回值实际上是POSIX下waitpid()的返回值.

status实际上嵌入了很多信息:

从系统(3)手册页:

The following macros may be used to test the manner of exit of the
process. One of the first three macros will evaluate to a non-zero
(true) value:

WIFEXITED(status)

True if the process terminated normally by a call to _exit(2) or exit(3).

WIFSIGNALED(status)

True if the process terminated due to receipt of a signal.

WIFSTOPPED(status)

True if the process has not terminated,but has stopped and can be restarted.
This macro can be true only if the wait call specified the
WUNTRACED option or if the child process is being traced (see ptrace(2)).

Depending on the values of those macros,the following macros produce
the remaining status information about the child process:

WEXITSTATUS(status)

If WIFEXITED(status) is true,evaluates to the low-order 8 bits of the argument passed to _exit(2) or exit(3) by the child.

WTERMSIG(status)

If WIFSIGNALED(status) is true,evaluates to the number of the signal that caused the
termination of the process.

WCOREDUMP(status)

If WIFSIGNALED(status) is true,evaluates as true if the termination of the process was accompanied by the creation of a core file containing an image of the process when the signal was received.

WSTOPSIG(status)

If WIFSTOPPED(status) is true,evaluates to the number of the signal that caused the process to stop.

#include <stdio.h>
#include <string.h>
#include <limits.h>

int main(int argc,char *argv[])
{
    int status;
    char command[PATH_MAX]; /* PATH_MAX is defined in sys/syslimits.h,included by limits.h */
    strcpy(command,"./test1");
    status = system(command);
    if ( WIFEXITED(status) ) {
          printf("The return value: %dn",WEXITSTATUS(status));
    }
    else if (WIFSIGNALED(status)) {
          printf("The program exited because of signal (signal no:%d)n",WTERMSIG(status));
    } 
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读