linux应用程序中,如何运行可执行程序,并获取其返回值?参考代码如下:
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
/*
*****************************************************************************************
* 函 数 名: main
* 功能说明: 创建子进程运行可执行程序,并获取其返回值
* 形 参:无
* 返 回 值: 非-1:子进程返回值
* -1:失败
*****************************************************************************************
*/
int main(void)
{
int ret = 0;
int status;
/* 创建子进程运行可执行程序,并获取其返回值 */
pid_t child = fork();
if (child == 0) { //子进程
execl("./donga_test", NULL); //运行可执行程序
printf("run_program: execv failed: %s\n", strerror(errno));
_exit(-1);
}
waitpid(child, &status, 0); //等待子进程执行结束
if (WIFEXITED(status)) { //非0表明子进程正常结束
if (WEXITSTATUS(status) != 0) {

本文介绍了如何在Linux应用程序中通过C语言的fork()和execv()创建子进程运行可执行程序,并使用waitpid()等待其结束,同时捕获并处理子进程的正常退出和异常退出情况,获取返回值。

875

被折叠的 条评论
为什么被折叠?



