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

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

22
23int main(int argc,char** argv)
24{
25    int status;
26    char commd[255]="";
27    int i;
28    if(argc<2)
29    {
30        printf("command-line argument required\n");
31        return -1;
32    }

33    for(i=1;i<argc;i++)
34    {
35        strcat(commd,argv[i]);
36        commd[strlen(commd)]=' ';
37    }

38    if((status=system(commd))<0)
39    {
40        printf("Command error");
41        return -1;
42    }

43
44    pr_exit(status);
45    return 0;
46}

47

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

以上程序是根据APUE里的例子来实现的。可以参考8.6和8.13节。
posted @ 2008-04-18 16:31  shipfi  阅读(1301)  评论(0编辑  收藏  举报