一个通用的调用shell命令及打印退出状态的C语言实现

本文介绍了一个C语言程序,该程序通过system函数执行Shell命令,并能够获取并打印出命令执行后的退出状态。这对于诊断Shell命令的执行情况非常有用。

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

 1None.gif#include <stdio.h>
 2None.gif#include <stdlib.h>
 3None.gif#include <unistd.h>
 4None.gif#include <string.h>
 5None.gif#include <sys/wait.h>
 6None.gif
 7None.gif
 8None.gifvoid pr_exit(int status)
 9ExpandedBlockStart.gifContractedBlock.gifdot.gif{
10InBlock.gif    if(WIFEXITED(status))
11InBlock.gif        printf("normal termination exit status=%d\n",WEXITSTATUS(status));
12InBlock.gif    else if(WIFSIGNALED(status))
13InBlock.gif        printf("abnormal termination,signal number=%d%s\n",WTERMSIG(status),
14InBlock.gif    #ifdef WCOREDUMP
15InBlock.gif            WCOREDUMP(status) ?" (core file gernerated) ":"");
16InBlock.gif    #else
17InBlock.gif            "");
18InBlock.gif    #endif
19InBlock.gif    else if(WIFSTOPPED(status))
20InBlock.gif        printf("child stopped,signal number=%d\n",WSTOPSIG(status));
21ExpandedBlockEnd.gif}

22None.gif
23None.gifint main(int argc,char** argv)
24ExpandedBlockStart.gifContractedBlock.gifdot.gif{
25InBlock.gif    int status;
26InBlock.gif    char commd[255]="";
27InBlock.gif    int i;
28InBlock.gif    if(argc<2)
29ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
30InBlock.gif        printf("command-line argument required\n");
31InBlock.gif        return -1;
32ExpandedSubBlockEnd.gif    }

33InBlock.gif    for(i=1;i<argc;i++)
34ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
35InBlock.gif        strcat(commd,argv[i]);
36InBlock.gif        commd[strlen(commd)]=' ';
37ExpandedSubBlockEnd.gif    }

38InBlock.gif    if((status=system(commd))<0)
39ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
40InBlock.gif        printf("Command error");
41InBlock.gif        return -1;
42ExpandedSubBlockEnd.gif    }

43InBlock.gif
44InBlock.gif    pr_exit(status);
45InBlock.gif    return 0;
46ExpandedBlockEnd.gif}

47None.gif

程序有两个功能:
1. 使用system函数调用shell命令,shell命令在启动程序参数中给出。
2. shell程序退出时可以获得其退出状态。

以上程序是根据APUE里的例子来实现的。可以参考8.6和8.13节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值