Reputation: 31
I'm trying to make a little chat program after reading Beej's guide to programming.
And then I was thinking about the basics of the program itself, and I don't know how to print output of recv() and get input for send() at the same time, because the client can always write something and send, but how is it possible to also print something while he's trying to input ?
I thought about threads, and I learned a little bit about them, and I created 2 simple threads: The first one, prints a sentence every 3 seconds, and the second one get input, this little program of-course had a lot of issues, for ex. if you started typing, and the other thread needs to print something, it will simply take what you wrote, and print it with itself output.
Here is the code, I tried to recreate it, I hope you guys can help me ..
pthread_t tid[2];
void* printse();
void* getinput();
int main(int argc, char *argv[])
{
int error;
error = pthread_create(&(tid[1]), NULL, &getinput, NULL);
if(error != 0)
{
printf("ERROR\n");
} else {
printf("NOERROR\n");
}
error = pthread_create(&(tid[2]), NULL, &printse, NULL);
if(error != 0)
{
printf("ERROR\n");
} else {
printf("NOERROR\n");
}
sleep(5000);
return 0;
}
void* printse()
{
while(1)
{
printf("POTATO\n");
sleep(3);
}
return NULL;
}
void* getinput()
{
char *input;
while(scanf("%s", input) != EOF)
{
printf("-%s\n", input);
}
return NULL;
}
Upvotes: 0
Views: 540
Reputation: 409166
You have undefined behavior in your code: You haven an uninitialized pointer input
in getinput
.
Uninitialized (non-static) local variables have an indeterminate value, and it will seem to be random. As the value is indeterminate (and seemingly random) the scanf
call will write to some unknown place in memory, overwriting whatever was there.
You could easily solve this by making input
an array.
Upvotes: 1