C (linux) - Emulate / Skip scanf input - c

I have a program running 2 threads. The first is waiting for user input (using a scanf), the second is listening for some data over an udp socket. I would like to emulate user input to handle a specific notification with the first thread everytime I recive a specific udp packet. I know I can share variables between threads, so my question is: can I force the scanf to take input from a different thread? Can I skip the scanf in the first thread?

I believe scanf() by definition reads from stdin. Like you said, though, the different threads share memory so it's easy to pass information between them. Maybe have some shared variable and some sort of boolean value indicating whether or not the information has been updated from the thread reading from the network. It all depends on what you're specifically trying to do, but you may want to have some other mechanism for simulation that bypasses the scanf().

Since you've specifically mentioned Linux, I'm going to suggest a novelty here.
You can open (/proc/%d/fd/%d, getpid(), STDIN_FILENO) and write to it. This will actually open the input of the terminal. I wouldn't recommend this for a real program, but then again, scanf shouldn't be used in real programs either.

Related

Getting user input in 2 child processes in C

I'm just wondering if it is possible to create two children processes, and in both of these processes ask the user for input? Or would it be stuck waiting forever?
It depends on the precise implementation of “asking user for input”. If this is readline, which implements shell-like input with the prompt and editing, it won’t work. The reason is that the library messes up with the terminal configuration. If two processes are doing the same thing simultaneously they will step on each other’s foot.
If we are talking about simply reading from standard input, that will work, but with a few quirks. First, without external synchronization it’s not known in which order processes are going to consume the input. It is even possible that process A grabs a few chunks from the input line, while process B grabs the rest.
Second, standard streams are buffered, therefore a process might consume more input than immediately obvious. E.g. the program reads a single line of input, but internally more data is read from the OS, since there’s no way to ask for bytes until the new line. The other process reading input simultaneously won’t get the input the other process consumed, even if the later only done it due to buffering and didn’t use the input.
To conclude, probably better to avoid having multiple processes consume input simultaneously.

how to interrupt a Scanf() in c, To exit from a scanf

I want to find a way to exit from a scanf() without interrupting the program running, I mean I want that program still running even if any data is typed. I am working on Linux
Here is the C Code :
char chaine1[256];
char chaine2[] = "exit";
int i;
do {
//The loop allows to control if the data is coming
//and send it continuously trough ethernet.
printf("preparing to send informations, exit to stop !\n");
scanf("%s", &chaine1);
i = strcmp(chaine1, chaine2); // Building the condition to exit
printf ("i= %d\n",&i);
} while (i!=0);
Thank you in advance for your help !
PS : I am a beginner in c and I have no idea in multiplexing syscalls and double threads so if you can guive me a concrets solution in your answer I would be thankfull
NO BODY SEEMS TO HAVE THE ANSWER !!
I am desperate PLEAASE HELP ME !
There are two approaches that could work:
use scanf in a separate thread from your main work. It will still block, but only that thread. If the user types "exit", your scanf thread will send some message to your worker thread telling it to shut down
use synchronous I/O multiplexing to interleave your main and user I/O operations in a single thread (this only really works if your main operations are indeed I/O dominated). The select/poll/etc. family of calls allow you to monitor both STDIN_FILENO and file descriptors associated with sockets simultaneously. You'll have to handle reading from STDIN_FILENO manually though, when it is readable, instead of using scanf/fscanf (and should use non-blocking reads).
The second option sounds more complex, but if you're doing I/O dominated work, you'll often have the framework in place already.
Note that neither of these involve interrupting scanf which, although possible, is a terrible option.
NB. I see that you're asking for concrete code - but both these approaches involve a significant amount of setup. You'll need to do some research and come back with a question that isn't just "please write all my code for me".
There still isn't enough context for me to know which of the two options is more appropriate for you anyway, and if you're reduced to describing your whole program and getting a stranger to re-write it for you, I don't know what to suggest. Maybe hire someone?

How to break out of fgets?

I am writing a simple instant messaging client & server to get the handle of socket programming.
My client has two threads:
Thread A has a streaming socket connection with the server and
performs a readline in a loop, printing out lines of text it receives
from the server. If the readline returns EOF, the loop exits.
Thread B listens to keyboard input from the user using fgets in a loop. When the user presses enter, it sends the line to the server (so it can forward it to the other client).
When a user presses Ctrl-D, the client sends a special message to the server saying "the client wants to disconnect" at which point the server closes the connection file descriptor for that user. This causes thread A to exit the loop since the readline function returns EOF. Thread A then closes the connection file descriptor and completes.
Meanwhile, thread B is still listening to keyboard input from the user until they hit enter. Ideally, the fgets would break early and let the user know that the other client disconnected.
Is there anyway to do or do I need to use a different input function or library?
Firstly, if you are trying to write socket functions, do not use fgets() or anything else that uses buffered IO, otherwise known as a FILE *. Instead use file descriptors (fd). Generally, every libc function beginning with 'f' is to be avoided. You want read and write.
Secondly, you want to read up on asynchronous I/O with select(), rather than work out how to 'break out' of fgets().
Thirdly, I could give you a tutorial here, or I could tell you to google, or look at http://en.wikipedia.org/wiki/Asynchronous_I/O but really what you want to find is a copy of Stephens (from memory "Advanced Programming in the Unix Environment" is what you want but really you should buy all of them and tape them to your body whilst you sleep in the hope of learning by osmosis).
Fourthly, I know you said you wanted to do this with threads. You can kill a thread with pthread_cancel() if you really want to do that, and restart it. Don't. Do it properly. You don't need threads.
In a Windows environment, fgets is a "blocking" call. Thus, the thread that issues it iwll wait until it has some input.
Not a problem, as long as, fgets enters into an "Alertable Wait" so that the waiting I/O can be cancelled by an ExitThread(0) statement.
Again, in Windows the way to have an ExitThread(0) statement get issued in a thread that is in a wait is to schedule an APC (i.e. QueueUserAPC()) for the thread and have that scheduled method issue the ExitThread() statement.
I just did this for some code I'm writing. I know that an APC will cause a thread to exit, if that thread has issued an alterable wait. I don't know if fgets does this in Windows, that is something you will need to figure out. If not then use an I/O statement that does. Note. In Windows your code can issue an Alertable wait with WaitSingleObjectEx() on the handle of an object when the handle is signaled when I/O is available for the object.
Do an internet search on "MSDN APC" and you will find all kinds of documentation from Microsoft about this.
Pthreads? Use pthread_kill to send a SIGHUP. This will cause fgets to quit with errno set to EINTR. Send it from thread A before it exits to thread B. You might have to play with the signal handlers and masks via pthread_sigmask and sigaction, depending on how fancy you want to get.

Writing and reading from terminal using pthreads

I want to create a multithreaded application in C using pthreads. I want to have a number of worker threads doing stuff in the background, but every once in a while, they will have to print something to the terminal so I suppose they will have to
"acquire the output device" (in this case stdout)
write to it
release the output device
rinse and repeat.
Also, I want the user to be able to "reply" to the output. For the sake of simplicity, I'm going to assume that nothing new will be written to the terminal until the user gives an answer to a thread's output, so that new lines are only written after the user replies, etc. I have read up on waiting for user input on the terminal, and it seems that ncurses is the way to go for this.
However, now I have read that ncurses is not thread-safe, and I'm unsure how to proceed. I suppose I could wrap everything terminal-related with mutexes, but before I do that I'd like to know if there's a smarter and possibly more convenient way of going about this, maybe a solution with condition variables? I'm somewhat lost here, so any help is welcome.
Why not just have a thread whose job is to interact with the terminal?
If other threads want to send message or get replies from the terminal, they can create a structure reflecting that request, acquire a mutex, and add that structure to a linked list if structures. The terminal thread will walk the linked list, outputting data as needed and getting replies as needed.
You can use a condition variable to signal the terminal thread that there's now data that needs to be output. The structure in the linked list can include a response condition variable that the terminal thread can signal when it has the reply, if any.
For output that gets no reply, the terminal thread can delete the structure after it outputs its contents. For output that gets a reply, the terminal thread can signal the thread that's interested in the output and then let that thread delete the structure once it has copied the output.
You can use fprintf on terminal. fprintf takes care of the concurrency issues, like it will use mutex locks on stdout before writing to the output device.

do while infinite loop stop on keyboard input - C

there is any way to run an infinite cycle that stops only on user input from keyboard
without asking every cycle to continue? in a C program
(I'm developing a C chat that read the entries with a for(;;) loop and I need to stop it only when the user want to type and send a message) hi all!
You didn't specify the OS so I will assume some POSIX compliant OS.
You can use select. This can be used to block on a set of file descriptors (in your case, stdin) with a finite timeout or indefinite blocking.
My guess is, since this is a chat program, you would also want to do this on some other file descriptor, like your chat tcp socket. So you can test for input on both with one call.
In case of windows console, you should be able to use GetStdHandle and WaitForSingleObject/WaitForMultipleObjects if select does not work for you.
There are a number of ways of doing this in Windows. Assuming you're using VC++, the easiest way is probably to use _kbhit(). If you want to use the Win32 API directly instead, you could call GetNumberOfConsoleInputEvents() and see whether the return is non-zero.
You could also do an overlapped read, and each time through the loop call WaitForSingleObject with a timeout value of 0. The zero wait means it'll return immediately whether there's input or not. The return value will tell you whether you have any data: WAIT_TIMEOUT means no data has been read yet, and WAIT_OBJECT0 means you have some data waiting to be processed.

Resources