关于第四章测试system命令返回值的工具t_sys

48 views
Skip to first unread message

Li Bin

unread,
Jul 9, 2016, 10:48:35 PM7/9/16
to 《linux环境编程》讨论组
有读者来Email,希望能得到第四章 测试system返回值的小工具的源码。

其实第四章t_sys工具的源码,在书中基本已经给出了大部分。

该小工具,我已经找不到了,不过没关系, 花了10分钟左右重新写了一遍。

Enter code here...#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

void usage()
{
    fprintf(stdout, "Usage: t_sys command\n");
    fprintf(stdout, "Example: t_sys \"ls -al\"\n");
    fprintf(stdout, "NOTICE: NEVER call dangerous command \n");
}

void print_wait_exit(int status)
{
    printf("status = %d\n",status);
    if(WIFEXITED(status))
    {
        printf("normal termination,exit status = %d\n", WEXITSTATUS(status));
    }
    else if(WIFSIGNALED(status))
    {
        printf("abnormal termination,signal number = %d%s\n", WTERMSIG(status),
#ifdef WCOREDUMP
      WCOREDUMP(status)?"core file generated": "");
#else
      "");
#endif
    }
}


int main(int argc ,char* argv[])
{
    if(argc != 2)
    {
        usage();
exit(1);
    }

    /*NOTICE, this is very dangerous ,to try harmful command*/
    int status = system(argv[1]);
    if(status == -1)
    {
        fprintf(stderr, "system() function return -1 (%s)\n", strerror(errno));
    }
    else if(WIFEXITED(status) && WEXITSTATUS(status) == 127)
    {
        fprintf(stderr, "cannot invoke shell to exec command(%s)\n",argv[1]);
    }
    else
        print_wait_exit(status);

    return 0;
}

希望方便大家学习system的返回值部分。

./t_sys
Usage: t_sys command
Example: t_sys "ls -al"
NOTICE
: NEVER call dangerous command


./t_sys "sleep 100"                                                                                                                    1
^Cstatus = 2
abnormal termination
,signal number = 2


./t_sys "nosuchcmd"
sh
: nosuchcmd: command not found
cannot invoke shell to
exec command(nosuchcmd)



t_sys.c

Gao Feng

unread,
Jul 10, 2016, 7:25:48 AM7/10/16
to 《linux环境编程》讨论组
顶~~

Jun Liu

unread,
Jul 12, 2016, 3:01:03 AM7/12/16
to 《linux环境编程》讨论组
👍
Reply all
Reply to author
Forward
0 new messages