How many child are created by fork() statement in if statements? - c

In the following pseudo code, how many child processes are created?
fork();
if(fork()==0)
fork();
fork();
I did not quite understand how if statement is executed and how many child of child processes are created within if statements.

I'll try to see if we can visualise this
Line 1 - fork() generates parent and child_1
Now both of them start running the code
Line 2 - if(fork()==0) is run both in parent and child 1:
parent: will generate parent and child_2
child_1: will generate child_1 as parent and child_3.
Line 3 - fork() inside if condition, this if condition will be true only for child_2 and child_3, as fork() returns the the id of child when parent is running, and for child id is 0. As child_2 and child_3 are the Childs generated in if condition fork() their id will be 0. After this:
child_2: will generate child_2 as parent and child_4.
child_3: will generate child_3 as parent and child_5.
After this point we have parent, child_1, child_2, child_3, child_4, child_5 running in parallel.
Now the fork() in Line 4 are run by each of them generating
child_6, child_7, child_8, child_9, child_10, child_11 respectively by each of the running process.
That leads to a total of 12 process out of which 1 is parent and 11 are Child processes.
Hence there are a total of 11 child processes.

Related

EOF record missing in file1 during file comparison in cobol

Hi I have written cobol file comparison program .In that both input1 and input2 have duplicates.
I got all the keys in output file and I am missing eof-input1 record in output.as I know I have handle the EOF condition correcly..
My scenario is I have to compare file1 and file2.
If file1=file2
Need to move input 1 record to output after performing some process.
Else
If file1>file2
need to move file1 record to output after performing some process.
In main para..
I did process until end-of-input1.
Please suggest some solution to get my last input1 record.
I didn't use any temp variable to move my IP data and for processing...
Thank you!!
Mainpara.
Read file1.
Read file2.
Process para until end of input1.
Close files.
Process para.
If in1>in2
Perform read file2 until eof2 or in2>=in1
End-if.
If eof2 = 'N'
If In2=in1
Some process
End-if
If In2 >in1
Some process
End-if
Else
Moves
End
Ip1: 111133445
Ip1:11347
Test op: 134
Required op: 1345

Why are multiple threads getting the same "tid?"

http://www.cs.colostate.edu/~cs370/Spring15/Workbook/thread_ex.txt
My professor provided the above sample code (Not duplicating to preserve his IP), and I'm confused by the output.
There are two functions being used as start routines, T1 and T2, and there are two separate for loops starting new threads. There is a tid assigned to each thread that should match the value of t when the thread was created, but there are several threads of the same function with the same tid as seen at the end of his sample output, i.e. there are two T1 threads with the tid 1. Why is this happening? If there are 4 T1 threads, shouldn't it generate tids 0-3?
Your professor designed these incorrectly, t changes its value in the main thread and is accessed by other threads without using mutual exclusion.
Here's what clang's TSan has to say:
==================
WARNING: ThreadSanitizer: data race (pid=5810)
Read of size 4 at 0x7fff193c03e4 by thread T1:
#0 T1(void*) /home/brian/src/so/threading/ex.cpp:16 (exe+0x0000000a0497)
Previous write of size 4 at 0x7fff193c03e4 by main thread:
#0 main /home/brian/src/so/threading/ex.cpp:61 (exe+0x0000000a0881)
Location is stack of main thread.
Thread T1 (tid=5812, running) created by main thread at:
#0 pthread_create ??:0 (exe+0x000000045a8b)
#1 main /home/brian/src/so/threading/ex.cpp:62 (exe+0x0000000a085a)
SUMMARY: ThreadSanitizer: data race /home/brian/src/so/threading/ex.cpp:16 T1(void*)
==================
... followed by ...
T1 [0] count = 12
==================
WARNING: ThreadSanitizer: data race (pid=5810)
Write of size 1 at 0x7ff2f8aa2c80 by main thread:
#0 main /home/brian/src/so/threading/ex.cpp:70 (exe+0x0000000a0964)
Previous read of size 1 at 0x7ff2f8aa2c80 by thread T1:
#0 T1(void*) /home/brian/src/so/threading/ex.cpp:18 (exe+0x0000000a04de)
As if synchronized via sleep:
#0 sleep ??:0 (exe+0x00000003f7bd)
#1 main /home/brian/src/so/threading/ex.cpp:69 (exe+0x0000000a0952)
Thread T1 (tid=5812, running) created by main thread at:
#0 pthread_create ??:0 (exe+0x000000045a8b)
#1 main /home/brian/src/so/threading/ex.cpp:62 (exe+0x0000000a085a)
SUMMARY: ThreadSanitizer: data race /home/brian/src/so/threading/ex.cpp:70 main
==================
T1 thread 1 done.

terminating a function call in python after n seconds

my python code goes like this:
def a():
...
...
subprocess.call()
...
...
def b():
...
...
and so on.
My task:
1) If subprocess.call() returns within 3 seconds, my execution should continue the moment subprocess.call() returns.
2) If subprocess.call() does not return within 3 seconds, the subprocess.call() should be terminated and my execution should continue after 3 seconds.
3) Until subprocess.call() returns or 3 seconds finishes, the further execution should not take place.
This can be done with threads but how?
Relevant part of the real code goes like this:
...
cmd = ["gcc", "-O2", srcname, "-o", execname];
p = subprocess.Popen(cmd,stderr=errfile)//compiling C program
...
...
inputfile=open(input,'w')
inputfile.write(scanf_elements)
inputfile.close()
inputfile=open(input,'r')
tempfile=open(temp,'w')
subprocess.call(["./"+execname,str(commandline_argument)],stdin=inputfile,stdout=tempfile); //executing C program
tempfile.close()
inputfile.close()
...
...
I am trying to compile and execute a C program using python.
When I am executing C program using subprocess.call() and suppose if the C program contains an infinite loop, then the subprocess.call() should be terminated after 3 seconds and the program should continue. I should be able to know whether the subprocess.call() was forcefully terminated or successfully executed so that I can accordingly print the message in the following code.
The back end gcc is of linux.
My task:
1) If subprocess.call() returns within 3 seconds, my
execution should continue the moment subprocess.call() returns.
2) If
subprocess.call() does not return within 3 seconds, the
subprocess.call() should be terminated and my execution should
continue after 3 seconds.
3) Until subprocess.call() returns or 3
seconds finishes, the further execution should not take place.
On *nix, you could use signal.alarm()-based solution:
import signal
import subprocess
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
# start process
process = subprocess.Popen(*your_subprocess_call_args)
# set signal handler
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(3) # produce SIGALRM in 3 seconds
try:
process.wait() # wait for the process to finish
signal.alarm(0) # cancel alarm
except Alarm: # subprocess does not return within 3 seconds
process.terminate() # terminate subprocess
process.wait()
Here's a portable threading.Timer()-based solution:
import subprocess
import threading
# start process
process = subprocess.Popen(*your_subprocess_call_args)
# terminate process in 3 seconds
def terminate():
if process.poll() is None:
try:
process.terminate()
except EnvironmentError:
pass # ignore
timer = threading.Timer(3, terminate)
timer.start()
process.wait()
timer.cancel()
Finally the below code worked:
import subprocess
import threading
import time
def process_tree_kill(process_pid):
subprocess.call(['taskkill', '/F', '/T', '/PID', process_pid])
def main():
cmd = ["gcc", "-O2", "a.c", "-o", "a"];
p = subprocess.Popen(cmd)
p.wait()
print "Compiled"
start = time.time()
process = subprocess.Popen("a",shell=True)
print(str(process.pid))
# terminate process in timeout seconds
timeout = 3 # seconds
timer = threading.Timer(timeout, process_tree_kill,[str(process.pid)])
timer.start()
process.wait()
timer.cancel()
elapsed = (time.time() - start)
print elapsed
if __name__=="__main__":
main()
If you're willing to convert your call to a Popen constructor instead of call (same way you are running gcc), then one way to approach this is to wait 3 seconds, poll the subprocess, and then take action based on whether its returncode attribute is still None or not. Consider the following highly contrived example:
import sys
import time
import logging
import subprocess
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)
if __name__ == '__main__':
logging.info('Main context started')
procCmd = 'sleep %d' % int(sys.argv[1])
proc = subprocess.Popen(procCmd.split())
time.sleep(3)
if proc.poll() is None:
logging.warning('Child process has not ended yet, terminating now')
proc.terminate()
else:
logging.info('Child process ended normally: return code = %s' % str(proc.returncode))
logging.info('Main context doing other things now')
time.sleep(5)
logging.info('Main context ended')
And this results in different logging output depending upon whether the child process completed within 3 seconds or not:
$ python parent.py 1
2015-01-18 07:00:56,639 INFO Main context started
2015-01-18 07:00:59,645 INFO Child process ended normally: return code = 0
2015-01-18 07:00:59,645 INFO Main context doing other things now
2015-01-18 07:01:04,651 INFO Main context ended
$ python parent.py 10
2015-01-18 07:01:05,951 INFO Main context started
2015-01-18 07:01:08,957 WARNING Child process has not ended yet, terminating now
2015-01-18 07:01:08,957 INFO Main context doing other things now
2015-01-18 07:01:13,962 INFO Main context ended
Note that this approach above will always wait 3 seconds even if the subprocess completes sooner than that. You could convert the above into something like a loop that continually polls the child process if you want different behavior - you'll just need to keep track of how much time has elapsed.
#!/usr/bin/python
import thread
import threading
import time
import subprocess
import os
ret=-1
def b(arg):
global ret
ret=subprocess.call(arg,shell=True);
thread.start_new_thread(b,("echo abcd",))
start = time.time()
while (not (ret == 0)) and ((time.time() - start)<=3):
pass
if (not (ret == 0)) :
print "failed"
elapsed = (time.time() - start)
print elapsed
thread.exit()
elif (ret == 0):#ran before 3 sec
print "successful"
elapsed = (time.time() - start)
print elapsed
I have written the above code which is working and satisfying all my contstraints.
The link https://docs.python.org/2/library/thread.html says:
thread.exit()
Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.
So I suppose there should be no problem of orphan processes, blocked resources, etc. Please suggest.

End execution without script closure by keypress?

Question
Basically, the title says it all! How do I stop execution of my hotkey via a hotkey?
How do I do so without closing the script?
How do I explicitly set a hotkey to take priority over a specific loop?
Explanation
I have a loop that executes several hundred times (code attached), and I would like to create a kill switch. I don't want to have to re-open the script if I stop it running, and I need to have lengthy sleeps, so I can fool with the mouse, as it is.
I'm looking at various pages, such as tutorial and break.
What I've tried
For example, should I name my loop somehow? Because Break takes no parameters, I'm thinking: there's no way to specify what to break.
Another example: should I add a hotkey into my loop to break? If so, how do I do that? Just throw ^!p:: into a nest under each hotkey? Or is there another way to add a hotkey to a hotkey (for example, with GetKeyState)?
Answer format
If possible, please show don't tell your answers, using the following code:
^!i::
{
Loop 1300
{
Send ^+{PrintScreen}
Sleep 1500
MouseClickDrag, left, 0, 100, 600, 400
Sleep 1000
Send 1
Sleep 500
}
Return
}
^!o::
{
Loop 1323
{
Send ^+{PrintScreen}
Sleep 1500
MouseClickDrag, left, 0, 200, 600, 400
Sleep 1000
Send 1
}
Return
}
If you want a controlled stop, i.e. at a certain point in the script, then you could use a hotkey to set a variable and test that variable in the script. When the variable has been set and the IF statement is true, you reset that variable and exit the loop. Otherwise, you could kill the script at a random point through the reload command. This way the script is closed, but immediately reopened.
^!i::
MyStopVariable:=0 ; Set the variable to 0
Loop 1300
{
If MyStopVariable
Exit ; Or Break if you want to finish something of after the loop
Send ^+{PrintScreen}
Sleep 1500
MouseClickDrag, left, 0, 200, 600, 400
Sleep 1000
If MyStopVariable
Exit ; Or Break if you want to finish something of after the loop
Sleep 500
}
Return
^!o::
MyStopVariable:=0 ; Set the variable to 0
Loop 1323
{
If MyStopVariable
Exit ; Or Break if you want to finish something of after the loop
Send ^+{PrintScreen}
Sleep 1500
MouseClickDrag, left, 0, 200, 600, 400
Sleep 1000
If MyStopVariable
Exit ; Or Break if you want to finish something of after the loop
Send 1
}
Return
^!s:: ; Ctrl+Alt+s = stop
MyStopVariable:=1
Return
Alternatively, you could use your original code and add a reload.
^!s:: ; Ctrl+Alt+s = stop
Reload
Return

Fork concept, dont quite grasp how fork works

I try to draw out the process according to the code but I really need some explanation in why, here is the question:
B() {
pid_t pid;
if ((pid = fork()) != 0)
waitpid(pid,NULL,0);
printf("2");
if(fork() ==0)
{ printf("3"); exit(0); }
printf("5");
exit(0);
}
Which one are illegals output?
232553, 235325, 232355, 235253, 252533...
This is the process I draw out according to the code and my understanding of fork.
___3 (exit so no more here)
|
__2__|___5 (I guess 5 should be here)
| |
| |
____|____(wait)|(start again since printf 3 process end)
So I'm stuck right there... Any help is appreciated.
Okay, there are two forks. Here is control flow, from left to right, with parents on top and children on the bottom:
+-- B ---- waitpid() --+ +-- "5" -- E
| | |
A --+ fork() +-- C -- "2" -- D -+ fork()
| | |
+----------------------+ +-- "3" -- F
So, what do we know?
"2", "5", and "3" each appear twice (90 possibilities)
No prefix may contain more "3" than "2" (30 possibilities)
No prefix may contain more "5" than "2" (16 possibilities)
The second "2" must be preceded by the first "5" (7 possibilities)
The 7 possibilities are:
2,3,5,2,3,5
2,3,5,2,5,3
2,5,2,3,3,5
2,5,2,3,5,3
2,5,2,5,3,3
2,5,3,2,3,5
2,5,3,2,5,3
This should be the program path (x denotes termination):
---+--(wait)-2-+-5-x
| |
+-2-+-5-x +-3-x
|
+-*3-x
After the first fork, the parent waits for the child to finish. But in case of second fork, it does not wait. So, * marked 3 can be printed anywhere after first 2. The order of printing 5 and 3 after second fork also can not be determined. Therefore, the possible outputs are:
25235*3
25253*3
2523*35
2525*33
252*335
252*353
25*3235
25*3253
2*35235
2*35253
Since the order of execution with fork() is not deterministic, you can only expect that each integer (i.e., 2, 3 and 5) will be printed twice. The order depends on how the scheduler chooses to schedule the processes.
You can force a particular order using sleep commands or some other synchronization primitive.
The first fork() splits the process into 2 parts (parent and child). The parent waits and the child prints 2.
Then the child does fork(); and then child prints 5 and exits (which allows the parent to start running again) while the child's child (grandchild?) prints 3. This can happen in any order.
The parent continues and prints 2 (this may happen before or after the grandchild prints 3; but after the now terminated child printed 5).
Then the parent does fork(); and the parent prints 5 and it's second child prints 2 (which can happen in any order, and may happen before the grandchild prints 5).
The first fork creates a child and waits for it. So the main program only goes on running as soon as the first child exits.
So the first output is "the child's" 2.
Then a 3 and a 5 is printed, in any order. Only after the 3 or the 5 the second 2 can occur, and then the second 3 and/or 5.
So
232553 is ok
235325 is not ok, as the 2nd 3 comes before the 2nd 2
232355 is ok
235253 is ok
252533 is ok

Resources