#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include<signal.h>
#include<unistd.h>//getch();
#include <termios.h>//getch();
#include <pthread.h>
volatile sig_atomic_t flag = 0;
char getch()
{
int buf=0;
struct termios old= {0};
fflush(stdout);
if(tcgetattr(0, &old)<0)
perror("tcsetattr()");
old.c_lflag&=~ICANON;
old.c_lflag&=~ECHO;
old.c_cc[VMIN]=1;
old.c_cc[VTIME]=0;
if(tcsetattr(0, TCSANOW, &old)<0)
perror("tcsetattr ICANON");
if(read(0,&buf,1)<0)
perror("read()");
old.c_lflag|=ICANON;
old.c_lflag|=ECHO;
if(tcsetattr(0, TCSADRAIN, &old)<0)
perror ("tcsetattr ~ICANON");
//printf("%c\n",buf);//to print the value typed.
return buf;
}
void *send_function()
{
printf("\n Send Thread \n");
//return 0;
}
void my_function(int sig)
{ // can be called asynchronously
flag = 1; // set flag
}
int main()
{
char selection;//user input(s or r)
pthread_t send;
while(1)
{
signal(SIGINT, my_function);
//printf("\n Before SIGINT \n");
if(flag)
{
printf("\n Choose your terminal S or R \n");
selection=getch();
flag = 0;
}
if(selection=='s')
if(pthread_create(&send,NULL,send_function(),NULL))
{
fprintf(stderr, "Error creating thread\n");
return 1;
}
else if(selection=='r')
printf("Receive Function is received");
//printf("\n After SIGINT \n");
}
return 0;
}
Выход:Почему моя простая программа pthreads врезается с ошибкой сегментации?
[email protected]:~/C_sample$ gcc -pthread -o thread thread.c
[email protected]:~/C_sample$ ./thread
Choose your terminal S or R
Send Thread
Send Thread
Send Thread
Send Thread
Send Thread
Segmentation fault (core dumped)
[email protected]:~/C_sample$ ^C
[email protected]:~/C_sample$
В приведенной выше программе я получаю ошибку сегментации. Мой требуемый вывод состоит в том, чтобы печатать "Send Thread"
непрерывно, как только я нажимаю 's'
. Я рассмотрел предыдущие подобные вопросы, но я не могу найти ответ. Может кто-нибудь мне помочь?
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Biffen