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節。