涉及的相关命令
查看当前运行的进程: ps aux | grep 进程的名字
查看当前运行的轻量级进程(线程):ps -aL | grep 进程的名字
查看当前主线程和新线程的关系: pstree -p 主线程id
进程栈的跟踪: pstack 进程pid
gdb中执行涉及的命令
!!!切记,gcc编译的时候一定要加上-g,否则无法使用gdb进行调试
查看线程: info threads
切换线程: thread 线程id
调试指定pid的进程: gdb attach pid
只运行当前线程: set scheduler-locking on
运行全部的线程: set scheduler-locking off
指定某线程执行某gdb命令: thread apply 线程id cmd
全部的线程执行某gdb命令: thread apply all cmd
利用core文件来分析
默认我们的系统是关闭生成core文件的,我们可以在命令行中输入ulimit -c 来查看是否打开了生成core文件的功能,如果输出的是大于0的数字,例如50,意思是限制core的文件大小不能超过50kb,可以使用ulimit -c unlimited 来取消限制;若输出结果为0的话,就是默认情况,即程序异常停止不输出core文件。
这里处理的是生产者消费者死锁问题
下面给出的程序是一个死锁的程序,只需把消费者的上锁和P操作位置调换一下,便可以处理死锁。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define M 1 /*缓冲数目*/
#define P(x) sem_wait(&x)
#define V(x) sem_post(&x)
int in = 0; /*生产者放置产品的位置*/
int out = 0; /*消费者取产品的位置*/
int buff = 0; /*缓冲初始化为0, 开始时没有产品*/
sem_t empty_sem; /*同步信号量,当满了时阻止生产者放产品*/
sem_t full_sem; /*同步信号量,当没产品时阻止消费者消费*/
pthread_mutex_t mutex; /*互斥信号量, 一次只有一个线程访问缓冲*/
/*
*output the buffer
*/
void print() {
printf("%d ", buff);
printf("\n");
}
/*
*producer
*/
void *producer() {
for(;;) {
sleep(1);
P(empty_sem);
pthread_mutex_lock(&mutex);
in = in % M;
printf("(+)produce a product. buffer:");
buff = 1;
print();
++in;
pthread_mutex_unlock(&mutex);
V(full_sem);
}
}
/*
*consumer
*/
void *consumer() {
for(;;) {
sleep(1);
pthread_mutex_lock(&mutex);
P(full_sem);
out = out % M;
printf("(-)consume a product. buffer:");
buff = 0;
print();
++out;
pthread_mutex_unlock(&mutex);
V(empty_sem);
}
}
void sem_mutex_init() {
/*
*semaphore initialize
*/
int init1 = sem_init(&empty_sem, 0, M);
int init2 = sem_init(&full_sem, 0, 0);
if( (init1 != 0) && (init2 != 0)) {
printf("sem init failed \n");
exit(1);
}
/*
*mutex initialize
*/
int init3 = pthread_mutex_init(&mutex, NULL);
if(init3 != 0) {
printf("mutex init failed \n");
exit(1);
}
}
int main() {
pthread_t id1;
pthread_t id2;
int i;
int ret;
sem_mutex_init();
/*create the producer thread*/
ret = pthread_create(&id1, NULL, producer, NULL);
if(ret != 0) {
printf("producer creation failed \n");
exit(1);
}
/*create the consumer thread*/
ret = pthread_create(&id2, NULL, consumer, NULL);
if(ret != 0) {
printf("consumer creation failed \n");
exit(1);
}
pthread_join(id1,NULL);
pthread_join(id2,NULL);
exit(0);
}
接下来的是我在调试的时候的情况