How to read the PID of the previous executed process in C? - c

I would like to read the PID of the previous executed process in C.
For example, I have process 1 which sleeps for 1s and when wakes up reads the PID of the process executing before the context switch. Process 1 runs with higher priority than the other processes so as when the sleep time finishes it immediately scheduled to run.
How can I get the information on which process PID run before its execution was interrupted so as process 1 executes?

I would like to read the PID of the previous executed process in C.
How can one determine which process was executed before or after, more on in a multiprocessor architecture in which several threads (even in the same process) can be executing fork() at the same time?
For example, I have process 1 which sleeps for 1s and when wakes up reads the PID of the process executing before the context switch.
how can it get the pid of the process that was executing before that context switch? In a context switch the process deciding the next process to execute doesn't tell the next process to execute which was the last. Even when a context switch happens by means of a hardware interrupt in which the process is not making a sleep()/wait()/pause() system call. System calls return information on how the system call went, but there's no place to store what process lead to a context switch and provide the number of the process id (indeed, it should be the thread id, as a process can have several threads and not only one)
Process 1 runs with higher priority than the other processes so as when the sleep time finishes it immediately scheduled to run.
Why do you assume process 1 runs at higher priority if the scheduler assigns priorities dynamically when considering which process to run next?
How can I get the information on which process PID run before its execution was interrupted so as process 1 executes?
You cannot. It's impossible as the context switch can happen because a hardware interrupt, when your process is not capable of storing it anywhere. Even signal handlers run in user mode, so there's no way in which you can have access to the last executed process. More because in a multiprocessor computer the kernel can be handling several context switches at the same time.
Indeed, telling a user process the pid of the process that was run last, could represent a security breach, as not all the processes belong to the same user. Remember today systems are not only multithread/multiprocess/multiprocessor, but also multiuser.

Related

A C program process is waited by some OS routine?

Well, I'm learning about processes using the C language, and I have seen that when you call the exit function a process is terminated and without waiting for it, it will become a zombie process. My question is, if the first process created when executing the program is a process itself, is there a 0S routine that wait for it after an exit() call, avoiding that it becomes a zombie process? I'm curious about it.
For Unix systems at least (and I expect Windows is similar), when the system boots, it creates one special first process. Every process after that is created by some existing process.
When you log into a windowed desktop interface, there is some desktop manager process (that has been created by the first process or one of its descendants) managing windows. When you start a program by clicking on it, that desktop manager or one of its children (maybe some file manager software) creates a process to run the program. When you start a program by executing a command in a terminal window, there is a command line shell process that is interpreting the things you type, and it creates a process to run the program.
So, in all cases, your user program has a parent process, either a command-line shell or some desktop software.
If a child process creates another child (even as the first instruction) then the parent also has to wait for it or it becomes a zombie.
Basically processes always become zombie until they are removed from the process table, the OS (via the process init) will handle and wait() for orphans (zombies without parents), it does that periodically so normally you won't have orphans running for very long.
On Linux, the top most (parent) process is init. This is the only process, which has no parent. Any other process (without any exception) do have a parent and hence is a child of another process.
See:
init
Section NOTES on wait
A child that terminates, but has not been waited for becomes a
"zombie". The kernel maintains a minimal set of information
about the zombie process (PID, termination status, resource usage
information) in order to allow the parent to later perform a wait
to obtain information about the child. As long as a zombie is
not removed from the system via a wait, it will consume a slot in
the kernel process table, and if this table fills, it will not be
possible to create further processes. If a parent process
terminates, then its "zombie" children (if any) are adopted by
init(1), ... init(1) automatically performs a wait to remove the
zombies.

Are my fork processes running parallel or executing one after another?

I am just going to post pseudo code,
but my question is I have a loop like such
for(i<n){
createfork();
if(child)
/*
Exit so I can control exact amount of forks
without children creating more children
*/
exit
}
void createfork(){
fork
//execute other methods
}
Does my fork create a process do what it is suppose to do and exit then create another process and repeat? And if so what are some ways around this, to get the processes running concurrently?
Your pseudocode is correct as written and does not need to be modified.
The processes are already executing in parallel, all six of them or however many you spawn. As written, the parent process does not wait for the children to finish before spawning more children. It calls fork(), checks if (child) (which is skipped), then immediately proceeds to the next for loop iteration and forks again.
Notably, there's no wait() call. If the parent were to call wait() or waitpid() to wait for each child to finish then that would introduce the serialism you're trying to avoid. But there is no such call, so you're good.
When a process successfully performs a POSIX fork(), that process and the new child process are initially both eligible to run. In that sense, they will run concurrently until one or the other blocks. Whether there will be any periods of time when both are executing machine instructions (on different processing units) depends at least on details of hardware capabilities, OS scheduling, the work each process is performing, and what other processes there are in the system and what they are doing.
The parent certainly does not, in general, automatically wait for the child to terminate before it proceeds with its own work (there is a family of functions to make it wait when you want that), nor does the child process automatically wait for any kind of signal from the parent. If the next thing the parent does is fork another child, then that will under many circumstances result in the parent running concurrently with both (all) children, in the sense described above.
I cannot speak to specifics of the behavior of your pseudocode, because it's pseudocode.

Program Priority on Lubuntu

Given a single processor virtual machine running lubuntu, I was wondering if it is possible to tie up the processor so that no other program can run any instructions.
For example, if program A and program B were to be run at nearly the same time, is it possible to set the priority of program A (in its source using the setpriority() function) to run before program B and then tie up the processor so that program B cannot execute?
You could call kill with SIGSTOP and a pid value of -1 to stop every process that you can (i.e., have permission to) stop other than init and the calling process, which, if you are root, should stop every process other than init and the process that calls kill.
You'd want to use a scripting language rather than the kill binary, as the kill binary would exit after sending the signal and not give the shell you ran the kill binary from would have been stopped, preventing you from launching your app.
E.g., in ruby, you could do,
#Broadcast the STOP signal
Process.kill(:STOP, -1)
#Run your process with the playground having been cleared
system('the_high_priority_app')
#Resume the stopped processes
Process.kill(:CONT, -1)
The above is a bit of a hack, though, and not very safe if you have many processes that do some IPC by sending the SIGSTOP and SIGCONT signals among themselvesj -- you could be sending SIGCONT to processes that had been stopped by other processes. You could get a list of processes that were stopped at the time of broadcasting the SIGSTOP signal and skip those when you broadcast the SIGCONT signal, but the set of sigstop processes could theoretically change between your scanning for them and your broadcasting of the SIGSTOP signal.
With the right priviliges it is possible to call 'sched_setscheduler' to give a process real time priority. Such a process will not be interrupted by ordinary processes or other real time processes with lower priority. Such real time processes will only lose CPU when they give it up by doing some call like sleep or waiting for IO. They will also be given the CPU back as soon as they are able to work again and the CPU is not needed by any real time process with higher priority.

Kill all the process from main after specific time

Below is my query. I am having problem with the bold text.
"You will write a program that uses multiple processes to compute the sum of a set of (small) positive integers.
There are two types of processes for this homework:
I). A set of "slaves" processes: Each slave process gets two small integers from its argv, computes its sum and returns the result using the exit system call. So, a slave process is created for every sum.
II) A "master" process: This process is responsible for creating the slave processes, and coordinating the computation. Note that all the computation is done by the "slave" processes. All the numbers are provided in the command line argv. The master process also set a timer at the start of computation to 3 seconds. If the computation has not been finished by this time, the master process kills all the slaves and then exits. You should print an appropriate message(s) in this case. Note that the master process may have to create multiple sets of slave processes. For example, if there are 8 numbers to be added, then the master process will first create 4 slaves and get the result from them. At this point there are 4 numbers, and it creates 2.
slaves. Finally one slave is created to compute the overall sum. To make it simpler, if the number of integers to add is odd, the master adds a 0 to the list of numbers. This may happen at any step during the computation. The code for master process should be compiled separately and its executable code should be called master. The executable code for the slave process should be called slave. So, to compute the sum of the numbers 1 through 7, the command line will look like
master 1 2 3 4 5 6 7
Since the results are passed around by exit system call, keep the numbers small (single digit). Each slave process prints its process id, its operands, and their sum. Each time the master gets a result from a slave, it prints the pid of the slave and the partial sum."
You are asked to use processes. It means you need to fork for every worker that is needed. Also
The master process also set a timer at the start of computation to 3 seconds. If the computation has not been finished by this time, the master process kills all the slaves and then exits.
It would be best to set alarm, which would send you a signal SIGALARM and when it's received you will use kill on specific processes ids (you can get them from fork). If your workers will finish, so will your main process and alarm won't trigger.
It's somehow complicated task if you are new to multiprocess programming. Now just try creating some processes and killing them after for e.g. 3 seconds. If you will have more problems, post your code and ask specific questions.
When creating threads, store their identifiers.
After creating threads in main(), pause using e.g. sleep(3) or whatever.
Loop over the stored thread ID:s, calling pthread_cancel() to kill them. Killing threads that have already terminated will cause this call to fail, but that's fine.
not sure if i get your question right. You may want to start a helper thread for each worker thread that does the computing. Pass the tid of the worker thread to its helper thread and let the helper thread sleep for 3 seconds and then check if the worker thread has exited and if not just kills it.
Or alternatively if you have a dedicated timer module/task, you could start a timer for each worker thread.

Running/pausing child processes in C?

I'm running child processes in C and I want to pause and then run the same child process. Not really sure how to describe my problem in a better way since I'm new at this but here's a shot.
So I know that you can run a process after another process exits by using waitpid. But what if the process I'm waiting on doesn't exist at the creation of the process that does the waiting. So in this case, I'm thinking of pausing the process that does the waiting and when the process that is waited is created and then finishes, it would call on the process that does the waiting to run again. So how would you do this? Again, I'm not familiar with this, so I don't know if this is the proper way to do this.
edit: What I'm trying to do
I'm using child processes to run command via execvp() in parallel so if I have a sequence sleep 1; sleep 1;, the total sleep time will be 1 second. However there are cases where I try to parallel echo blah > file; cat < file; in which case I'm assuming cat reads the file after echo inputs blah into file. Therefore, I have to wait for echo to finish to do cat. There are more specifics to this, but generally assume that for any command with an output to a file must be waited on by any command that reads the file later in the script.
In Linux: You can set an alarm() before you waitpid() so you can wakeup after a certain number of seconds and waitpid() should return EINTR so you would know the situation and can kill the misbehaving one. Another way would be to use a mutex and having a block like this in the waiting process:
if (pthread_mutex_trylock(&mutex) {
sleep(some seconds);
if (pthread_mutex_trylock(&mutex) {
kill the process
}
}
and the process that is monitored:
ENTRY-POINT:
pthread_mutex_lock(&mutex);
do_stuff();
pthread_mutex_unlock(&mutex);
Any application (process) can only wait with waitpid() on its own direct children. It can't wait on grandchildren or more distant descendants, and it can wait on neither siblings nor ancestors nor on unrelated processes.
If your application is single-threaded, you can't wait on a process that will be created after the waitpid() call starts because there is nothing to do the necessary fork() to create the child.
In a multi-threaded process, you could have one thread waiting for dying children and another thread could be creating the children. For example, you could then have the waitpid() call in thread 1 start at time T0, then have thread 2 create a child at T1 (T1 > T0), and then the child dies at T2, and the waitpid() would pick up the corpse of the child at T3, even though the child was created after the waitpid() started.
Your higher level problem is probably not completely tractable. You can't tell which processes are accessing a given file just by inspecting the command lines in a 'shell script'. You can see those that probably are using it (because the file name appears on the command line); but there may be other processes that have the name hardwired into them and you can't see that by inspecting the command line.

Resources