c - 为什么我的简单 pthreads 程序会因段错误而崩溃?

标签 c linux pthreads

#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;  

} 

输出:

 nivas@balakrishnan-HCL-Desktop:~/C_sample$ gcc -pthread -o thread thread.c

 nivas@balakrishnan-HCL-Desktop:~/C_sample$ ./thread

 Choose your terminal S or R

 Send Thread

 Send Thread

 Send Thread

 Send Thread

 Send Thread
 Segmentation fault (core dumped)
 nivas@balakrishnan-HCL-Desktop:~/C_sample$ ^C
 nivas@balakrishnan-HCL-Desktop:~/C_sample$

在上面的程序中,我遇到了段错误。我需要的输出是在我按下 's' 后连续打印 "Send Thread"。我已经研究过以前的类似问题,但找不到答案。谁能帮帮我?

最佳答案

是这一行:

if(pthread_create(&send,NULL,send_function(),NULL))

打字错误? pthread_create 的第三个参数是一个函数指针,线程应该从这里开始。

它应该是:

if(pthread_create(&send,NULL,send_function,NULL))

此外,您创建的线程不会真正退出,除非您将它们的属性位设置为分离,或显式分离它们,或使用 pthread_join 收集状态。

关于c - 为什么我的简单 pthreads 程序会因段错误而崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712112/

相关文章:

c++ - 使用不同线程访问不同子数组而不同步是否安全?

c - (c) 表达式必须是可修改的左值

字符写入数组

linux - 如何对群组中的用户进行排序?

c - 每线程内存分配

c - 如何将线程分配给C中的不同内核?

c - 计算机图形编程中的页面翻转是什么意思?

c++ - 库可以替换 C/C++ 中的本地套接字吗?

c - 没有任何 cpp 选项的系统调用 stat() 转换为 stat64()

linux - socket() 在 C 客户端服务器应用程序中返回 0