#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>
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
volatile sig_atomic_t flag = 0;
int value = 0;
int count = 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");
return buf;
}
void *send_function(void *parg)
{
printf("\n Send Thread ");
count++;
return parg;
}
void *receive_function(void *parg)
{
printf("\n Receive Thread ");
count++;
return parg;
}
void my_function(int sig)
{
flag = 1; // set flag
}
int main()
{
char selection; //user input(s or r)
pthread_t send;
pthread_t receive;
while (1)
{
signal(SIGINT, my_function);
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))
{
printf("Error creating thread=%d\n", count);
return 1;
}
}
else if (selection == 'r')
{
if (pthread_create(&receive, NULL, receive_function, NULL))
{
printf("Error creating thread=%d\n", count);
return 1;
}
}
printf("\n MAIN LOOP\n");
//sleep(1);
}
return 0;
//pthread_exit(NULL);
}
输出1:
MAIN LOOP
Receive Thread
MAIN LOOP
Receive Thread
MAIN LOOP
Receive Thread
MAIN LOOP
Receive Thread
Receive Thread
Receive Thread
Receive Thread Error creating thread=380
nivas@balakrishnan-HCL-Desktop:~/C_sample$
OUTPUT2:
MAIN LOOP
MAIN LOOP
MAIN LOOP
Send Thread
Send Thread
Send Thread
Send Thread
Send Thread
MAIN LOOP
Error creating thread=379
在上面的代码中。当我按's'或'r'时,代码应该无限运行它应该相应地打印“发送线程”或“接收线程”无限次,而在此代码中大约380次只有while循环正在运行。我不会我知道它为什么会发生。我使用变量计数进行调试,有人可以帮忙吗?