WIn32 api - 2 process write to console - c

I have an issue with write to the same console with two processes(1 parent create child process) that interacts between them with a pipe.
every process has multiple threads and has to write to the console.
sometimes I find that one process start to write and the other process stops it in the middle and writes in its place and so it turns out that the text is blurred.
of course, every process has his own semaphores for his own threads but the problem is between the two processes.
There is a way to fix this issue?

Related

Forked processes order of execution

I know there's another thread with the same name, but this is actually a different question.
When a process forks multiple times, does the parent finish executing before the children? Vice versa? Concurrently?
Here's an example. Lets say I have a for loop that forks 1 parent process into 4 children. At the end of that for loop, I want the parent process to feed some data to the children via pipes. The data is written to each child process' respective stdin.
Will the parent send the data first, before any of the children execute their code? This is important, because we don't want it to start working from an invalid stdin.
The order of the execution is determined by the specific OS scheduling policy and not guaranteed by anything. In order to synchronize the processes there are special facilities for the inter-process communication (IPC) which are designed for this purpose. The mentioned pipes are one example. They make the reading process to actually wait for the other process to write it, creating a (one-way) synchronization point. The other examples would be FIFOs and sockets. For simpler tasks the wait() family of functions or signals can be used.
When a process forks multiple times, does the parent finish executing before the children? Vice versa? Concurrently? -
Concurrently and depends on the scheduler and its unpredictable.
Using pipe to pass integer values between parent and child
This link explains in detail about sharing data between parent process and child.
Since you have four child process you may need to create different individual pipes between each child process.
Each byte of data written to a pipe will be read exactly once. It isn't duplicated to every process with the read end of the pipe open.
Multiple child processes reading/writing on the same pipe
Alternatively you can try shared memory for the data transfer.
They will execute concurrently. This is basically the point of processes.
Look into mutexes or other ways to deal with concurrency.

Record and write processes onto a file using C (linux)

Can someone help me with this small problem please? I am trying to create a fork bomb and record how many processes a computer creates before something weird happens, but I can't figure out how to write the processes into a text file. I looked around the internet and couldn't find a solution for my problem and I tried doing different things but that didn't work with me also. If you guys can help me out on this matter that would be awesome! Here's my code so far (far from perfect, I know.. D: ).
while(1)
{
fork(); // Fork bomb
write(fd, '\n', sizeof(buf));
}
Thanks in advance
Open a file for write+append.
Each forked process will inherit the file descriptor.
In each forked child process, write a single null byte to the file descriptor.
When everything crashes, the size of the file, in bytes, will tell you how many processes were started.
Another idea that would write the number of processes, instead of writing that many bytes
This is a bit complex. I'm writing this answer just for the sake of completeness(and fun!).
Use a process as the "master process". (The easiest way is using the starting process.) Each time a new process is created, a signal(you can use SIGUSR1) would be sent to the master process, so the master process can increment its process counter. (note that incrementing the counter in every process wouldn't work because their memory are not shared.) Once fork() has failed, another signal is sent to the master. Once all children have failed(a child would signal the failure only once and the master would have a failure counter in addition to the process counter), the master will write the process counter to the file, and kill all processes in its process group(kill() can kill not only a single process but also a process group).
Cautions:
You may need to use nice() to avoid the children from preventing the master to execute.
In order to prevent the children from forking again before all children are killed, you may need to suspend the children before terminating them.

Output written to stdout via forked processes

I have a process that forks, performs computation and writes out data to stdout. The child process also writes out data to stdout after performing some computation. Currently, the output from the parent and the child come out separately. However, I'm concerned that the output from the child may be printed mixed with the output from the parent.
I.e. I have this line in both the child and the process :-
fprintf(stdout, "%s\n", do_computation());
Is there any neat way to prevent the writes from being interleaved? It hasn't happened so far, however I'm concerned that it may.
This is the standard multitasking issue, and is solved the same way any other shared resource is protected: it's your responsibility to create and manage semaphores so the processes can negotiate periods of exclusive access to shared resources such as these streams, or to arrange similarly safe mechanisms for them to communicate amongst themselves (eg having the child processes respond not to stdout but via a pipe per process back to the parent, and having the parent poll those pipes and report their results as complete messages become available).
There should be plenty of good tutorials on the web on multiprocess programming in C.
Conceptually, you want to achieve before-or-after atomicity for the fprintf calls in different process. You can in the parent process, waitpid for the child process right before the fprintf call so that the call in parent process is guaranteed to be executed after the child terminates without reducing the parallelism of the computation.

Wait for part of child process to finish?

I have a fork occurring in a loop, and above the fork I prompt for a user's input. In my forked process, there's also some printing. Because there's no guarantee to the order the processes will run in, I often (or always) get lines from the child process printing between my prompt to the user and the place where they can enter information.
I.e., I get something like this:
Enter info: <OUTPUT FROM CHILD>
_
(where the _ indicates that the user is free to enter an input.)
Since I'm trying to allow my parent process to fork many children process (each based on piece of information given by the user) that run simultaneously, I can't wait for the child to end before letting the parent continue. Is there a way to make the parent wait for part of the child to complete before moving on?
A lot depends on what you're really trying to do, but you can't use waitpid() or wait() to wait for part of a process to finish. The wait family of functions wait on moribund processes, or processes that have been stopped due to a signal (SIGSTOP, SIGTTIN, SIGTTOU, etc).
Some questions:
Should the output from the child processes be sent to the screen, which leads to this confusion, or should it be sent to a file?
Or, should the program have a pipe from each child so that it can read the output from the child and display it on an appropriate portion of the screen when it is convenient?
Or, in a windowing environment, should the children's messages be sent to a different window (like the console window)?
Or should the children write to the syslog daemon?
Or should the children be made to hang on a SIGTTOU signal?
A lot depends on the purpose of the messages, and the importance of immediate display of the messages.
The other answers are definitely more general, and the proper way to solve this problem would involve some kind of pipe, but my case was actually very simple, and just needed the parent to wait for a while, so I added a usleep() line, to make the parent wait a few milliseconds for the child to finish printing. It's definitely not perfect, but it worked.

backgrounding a threaded application with fork()

So I have an application which uses threads. Now when the program first starts up, I want it to go through setting up database connections and whatnot before it backgrounds itself so that whatever/whoever starts the program can know if there was an error starting up.
I did some looking around and have found some resources that say 'do not mix fork and threads', while others say that forking in linux will only duplicate the main thread and leave the others alone.
In the case of the latter (where it just duplicates the main thread), how then do the threads access file level (global) variables? Will the threads not be able to access the variables that are now in the forked process's address space?
Ultimately the goal is to have the application background itself after threads have been created. If this is not possible, I can put the fork before the thread creation, just would like to do it as late as possible.
Note: at the time of the fork, the threads will be doing a sleep() loop until the main thread puts data into a shared variable for them to process. So if the sleep gets interrupted, they wont be harmed.
There is no way to duplicate threads as part of the fork, and the parent's threads will all terminate when the parent exits, so even if they could access the child's memory, it wouldn't help you. You need to either create your threads after forking, or use pthread_atfork to register handlers that will recreate them in the child process. I would recommend just waiting until after forking to create your threads since it's a lot simpler and more efficient.
Why is it that you want to delay forking as long as possible? If you want to maintain connection to a terminal or something until initialization is finished, you can just have the parent process wait to terminate until the child process (with its threads) is done initializing and ready to be "in the background". Various synchronization tools could be used to accomplish this. One simple one would be opening a pipe through which the child sends its output back to the parent to display; the parent could simply exit when it receives EOF on this pipe.
Forking a process creates two different processes and threads in one process will not be able to access memory in the second process. If you want different processes to access the same memory, you want something called shared memory.
When a thread in a process calls fork(), a new process is created by copying, among other things, (1) the full address space of the process and (2) the (one) thread that called fork. If there are other threads in the process, they don't get copied. This will almost certainly lead to bugs in your program. Hence the advice not to mix threads and forks.
If you want to create a background process with many threads, you must fork it before spawning any other thread. Then, the two processes behave normally, like any two isolated processes: threads within one process share the same memory, but your background threads and your foreground process won't share any memory (by default).

Resources