一個通用的調用shell命令及列印退出狀態的C語言實現

來源:互聯網
上載者:User
 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節。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.