tkill program in chapter 6

15 views
Skip to first unread message

Li Bin

unread,
Dec 30, 2016, 4:04:06 AM12/30/16
to 《linux环境编程》讨论组
前两日高峰给我说有人提到,第六章用到了tkill做实验,但是书中并未提供tkill的源码。
这两日处理一个比较棘手的bug,所以一直拖到今日才腾出空来处理此事。

原始的代码已经找不到了,因为核心代码就一句话,
    int ret = syscall(SYS_tkill, tid, signo); 

所以我也没仔细找,干脆花了点时间重写了一遍。

给读者带来不便,请多担待。


#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/syscall.h>
#include <string.h>
#include <errno.h>


void usage(char *program)
{
    printf("Usage: %s [OPTIONS] \n", program);
    printf("    -p target_pid \n");
    printf("    -s signal number (0~64) \n");
}

int tkill(int tid, int signo)
{
    int ret = syscall(SYS_tkill, tid, signo); 
    if(ret)
    {
        fprintf(stderr,"PID(%d) ------sig(%d)----->PID(%d)  failed (%s)\n",getpid(), signo, tid, strerror(errno));
    }
    return ret;
}

int main(int argc,  char* argv[])
{
    int c ;

    static struct option long_options[] = {
        {"target_pid",  required_argument, 0, 'p'},
        {"signal",  required_argument, 0, 's'},
        {0, 0 , 0, 0}
    };

    const char* short_options = "h?p:s:";

    int option_index = 0;

    int target_pid = -1 ;
    int signal_id = -1;
    int ret = -1; 

    while((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1)
    {
        switch(c)
        {
        case 'p':
            target_pid = atoi(optarg);
            break;
        case 's':
            signal_id = atoi(optarg); 
            break;
        case 'h':
        case '?':
            usage(argv[0]);
            return 0;
            break;
        default:
            break;
        }

    }

    if(optind < argc)
    {
        fprintf(stderr,"Non-Option ARGV parameter: ");
        while((optind < argc))
        {
            fprintf(stderr, "%s ", argv[optind++]);
        }
        fprintf(stderr,"\n");
        usage(argv[0]);
        return 1;
    }


    if(target_pid <= 0)
    {
        fprintf(stderr, "invalid target pid %d\n", target_pid);
        return 2;
    }

    if(signal_id < 0 || signal_id > 64)
    {
        fprintf(stderr, "invalid signal number %d\n", signal_id);
        return 3;
    }

    ret = tkill(target_pid, signal_id);
    return ret;

}



读者可以从https://github.com/gfreewind/aple_codes 里面找到代码。


Feng Gao

unread,
Dec 30, 2016, 10:22:32 PM12/30/16
to Li Bin, 《linux环境编程》讨论组
为李彬加好~~
> --
> 您收到此邮件是因为您订阅了Google网上论坛上的“《linux环境编程》讨论组”群组。
> 要退订此群组并停止接收此群组的电子邮件,请发送电子邮件到linux_aple+...@googlegroups.com
> 要在网络上查看此讨论,请访问https://groups.google.com/d/msgid/linux_aple/c365f8c7-4142-461a-b12a-38422bb2263b%40googlegroups.com
> 要查看更多选项,请访问https://groups.google.com/d/optout
Reply all
Reply to author
Forward
0 new messages