gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:50:31 26 4
gpt4 key购买 nike

我想执行一个可执行文件,其 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: %d\n", system(command));

return 0;
}

test1

#include <stdio.h>

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

return 2;
}

这就是我想要的

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

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

最佳答案

system的返回值其实就是POSIX下waitpid()的返回值。

status 其实里面嵌入了很多信息:

来自 system(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: %d\n", WEXITSTATUS(status));
}
else if (WIFSIGNALED(status)) {
printf("The program exited because of signal (signal no:%d)\n", WTERMSIG(status));
}
return 0;
}

关于c - system() 的返回值不是执行程序的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24810889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com