根据system函数返回值确定命令是否执行成功

本文介绍了一个使用C语言实现的简单系统命令执行程序。该程序通过调用system函数执行外部命令,并利用wait和WIFEXITED宏来检查子进程的状态。文章提供了完整的源代码示例,包括错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>

int system_cmd(char *cmd)
{
    pid_t status;

    status = system(cmd);

    if (-1 == status)
    {
        printf("create child process fail!\n");
        return -1;
    }
    else
    {
        //printf("exit status value = [0x%x]\n", status);

        if (WIFEXITED(status))
        {
            if (0 != WEXITSTATUS(status))
            {
                printf("run shell script fail.\n");
                return -1;
            }

        }
        else
        {
            printf("exit status = [%d]\n", WEXITSTATUS(status));
            return -1;
        }
    }

}


int main()
{
    system_cmd("twe");
    return 0;
}

任务描述 熟读本关的相关知识,了解 system 函数执行过程和返回值。 本关任务: 执行touch test.dat命令; 检查命令是否执行成功。 相关知识 为了简化执行命令的复杂程度, Linux 系统提供 system 系统调用,原理是通过 fork 的方式产生一个子进程,在这个子进程中执行系统调用过程中参数里面设定的 command 。 system函数 #include <stdlib.h> int system(const char *command); 功能:利用 fork 创建子进程,然后用execl来执行/bin/sh sh -c command指令。system 函数的主进程必须等待子进程执行完后再退出,并返回执行状态。 参数: command:需要执行命令的字符串,比如需要查看当前目录下的文件信息,则将 command 设定为ls -l。 返回值: 出现异常时返回 -1; 子进程正常退出,返回 0 或者其他值。 为了更好的理解system()函数返回值,需要了解其执行过程,实际上system()函数执行了三步操作: fork一个子进程; 在子进程中调用 exec 函数执行 command ; 在父进程中调用 wait 去等待子进程结束。对于 fork 失败,system()函数返回 -1。如果 exec 执行成功,则返回 command 通过 exit 或 return 返回的值。 #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() { ...... system("date");//打印当前系统时间 ...... } 有兴趣的读者可以查看system函数的源码: int system(const char * cmdstring) { pid_t pid; int status; if(cmdstring == NULL){ return (1); } if((pid = fork())<0){ status = -1; } else if(pid == 0){
最新发布
05-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值