在停止和等待协议实现中使用pthread时的SIGSEGV

时间:2013-02-26 03:17:54

标签: linux sockets pthreads

我是一名大学生,作为网络作业的一部分,我需要实施停止等待协议。问题陈述需要使用2个线程。我是线程新手,但在浏览了pthreads API的手册之后,我编写了基本代码。但是,在成功创建线程后(在执行传递给pthread_create()作为参数的函数的第一行时),我得到了一个分段错误。

typedef struct packet_generator_args
{
    int max_pkts;
    int pkt_len;
    int pkt_gen_rate;
} pktgen_args;

/* generates and buffers packets at a mean rate given by the
pkt_gen_rate field of its argument; runs in a separate thread  */
void *generate_packets(void *arg)
{
    pktgen_args *opts = (pktgen_args *)arg; // error occurs here
    buffer = (char **)calloc((size_t)opts->max_pkts, sizeof(char *));
    if (buffer == NULL)
        handle_error("Calloc Error");
    //front = back = buffer;
    ........

    return 0;
}

主线程从此缓冲区读取数据包并运行停止和等待算法。

pktgen_args thread_args;
thread_args.pkt_len = DEF_PKT_LEN;
thread_args.pkt_gen_rate = DEF_PKT_GEN_RATE;
thread_args.max_pkts = DEF_MAX_PKTS;

/* initialize sockets and other data structures */
.....
pthread_t packet_generator;
pktgen_args *thread_args1 = (pktgen_args *)malloc(sizeof(pktgen_args));
memcpy((void *)thread_args1, (void *)&thread_args, sizeof(pktgen_args));
retval = pthread_create(&packet_generator, NULL, &generate_packets, (void *)thread_args1);
if (retval != 0)
    handle_error_th(retval, "Thread Creation Error");
.....
/* send a fixed no of packets to the receiver wating for ack for each. If
the ack is not received till timeout occurs resend the pkt */
.....

我尝试使用gdb进行调试,但无法理解为什么在generate_packets()函数的第一行发生了分段错误。希望你们中的一个可以提供帮助。如果有人需要其他上下文,则可以在http://pastebin.com/Z3QtEJpQ获取整个代码。我在这里花了好几个小时在这里。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您将buffer初始化为NULL

 char **buffer = NULL;

然后在main()中进一步做,你试着解决它:

while (!buffer[pkts_ackd]); /* wait as long as the next pkt has not

基本上我的半受教育的猜测是你的线程还没有生成任何数据包,你试图访问NULL中的元素时崩溃。

[162][04:34:17] vlazarenko@alluminium (~/tests) > cc -ggdb -o pthr pthr.c 2> /dev/null
[163][04:34:29] vlazarenko@alluminium (~/tests) > gdb pthr
GNU gdb 6.3.50-20050815 (Apple version gdb-1824) (Thu Nov 15 10:42:43 UTC 2012)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries .. done

(gdb) run
Starting program: /Users/vlazarenko/tests/pthr 
Reading symbols for shared libraries +............................. done

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x000000010000150d in main (argc=1, argv=0x7fff5fbffb10) at pthr.c:205
205         while (!buffer[pkts_ackd]); /* wait as long as the next pkt has not
(gdb)