Fork concept, dont quite grasp how fork works - c

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

Related

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

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.

How to concatenate two strings in H2O

I have a H2O frame in R with two character columns and I would like to create a new column by concatenating them. I tried the following but it failed as Paste function is not supported by H2O. Any other ideas? I searched for a solution but haven't found one so far. Thank you.
df$Col3 = paste(df$Col1, df$Col2)
One option would be to use the h2o.interaction function. It's not as simple as a paste function and I don't think you can choose the concatenation separator (it uses _), but it may work for your purposes. Here is a brief example.
library(h2o)
h2o.init()
h2oframe <- as.h2o(Titanic)
h2oframe$Col3 <- h2o.interaction(h2oframe,
factors = list(c("Sex", "Age")),
pairwise = T,
max_factors = 100000,
min_occurrence = 1)
head(h2oframe)
Class Sex Age Survived Freq Col3
1 1st Male Child No 0 Male_Child
2 2nd Male Child No 0 Male_Child
3 3rd Male Child No 35 Male_Child
4 Crew Male Child No 0 Male_Child
5 1st Female Child No 0 Female_Child
6 2nd Female Child No 0 Female_Child

AutoHotKey - Receive content from an array using a variables' integer as the index

I want to receive a string from an array using a variables' integer as the array index. But it is not working.
Attempt 1
; Suspended | 0 = No, 1 = Yes
global Suspended := 0
global SuspendedMsg := ["The script has been paused.","The script has been re-activated."]
Pause::
Suspend
if suspended = 0 ; If script is not suspended
{
TrayTip, Paused, SuspendedMsg[Suspended], 3
Suspended++
} else ; If it is suspended
{
TrayTip, Activated, SuspendedMsg[Suspended], 3
Suspended--
}
return
Attempt #1 will just display the string "SuspendedMsg[Suspended]" because I don't know where to set the variable indicator %. Even if I set it to SuspendedMsg[%Suspended%] it will either display [1] or [0].
Attempt 2
; Suspended | 0 = No, 1 = Yes
global Suspended := 0
global SuspendedMsg := ["The script has been paused.","The script has been re-activated."]
global SendSuspendMsg := SuspendedMsg[Suspended]
Pause::
Suspend
if suspended = 0 ; If script is not suspended
{
TrayTip, Paused, %SendSuspendMsg%, 3
Suspended++
} else ; If it is suspended
{
TrayTip, Activated, %SendSuspendMsg%, 3
Suspended--
}
return
Attempt #2 won't do as well, it doesn't even display any message. I tried fiddling arround with % inside the global SendSuspendMsg := SuspendedMsg[Suspended] variable but it won't do no good. Anyone care to help me out?
#Blauhim missed an important point, although his answer is mostly correct. First the Index in an Array when created like you did, always starts at 1, then proceeds to 2 etc, etc... So your code was flawed when you tried to use your Boolean variable to call to an index as a 0 Index does not exist (not to mention that you didn't force and Expression on that TrayTip Command).
; Set our variable to 1 why? Because we are going to use a Logical switch below.
Suspended := 1
; This was correct format and I left it, although I removed Global's as they are not needed
SuspendedMsg := ["The script has been paused.","The script has been re-activated."]
Pause::
; Suspend toggles each time it's called
Suspend
; Here we are toggling the value of our variable using !
; We started with a 1 so that it would be correctly
;Changed to a 0 for the code below.
suspended := !suspended
; Nothing changed here
if suspended = 0 ; If script is not suspended
{
; In order to pass an Array or Object or Expression to a Command you Force it
; using the a Percent Sign with a space on either side.
; Also note you were trying to use your Logical True/False 0 or 1 variable to
; itterate. This didn't work because Array's always start with an Index of 1.
; Below I've accounted for this by simply added a 1 to your suspended so it correctly
; points to the Index in our Array.
TrayTip, Paused, % SuspendedMsg[suspended + 1], 3
} else ; If it is suspended
{
TrayTip, Activated, % SuspendedMsg[suspended + 1], 3
}
return
Instead of TrayTip, Paused, SuspendedMsg[Suspended], 3 or TrayTip, Paused, SuspendedMsg[%Suspended%], 3, try
TrayTip, Paused, % SuspendedMsg[Suspended], 3
. TrayTip asks you for a
specify the message to display
which means as much as a String. So, variables names aren't handled as variables here, but as strings instead (as most of the times in commands). It would make sense to state TrayTip, Paused, %SuspendedMsg[%Suspended%]%, 3
, but you cannot nest variable's percent signs. So, we'll have to use the percent sign to force an expression:
Force an expression: An expression can be used in a parameter that does not directly support it (except OutputVar parameters) by preceding the expression with a percent sign and a space or tab. In [v1.1.21+], this prefix can be used in the InputVar parameters of all commands except the traditional IF commands (use If (expression) instead). This technique is often used to access arrays.
Concerning your second problem: I don't think Arrays can be declared like that, can they..? (but I'm not sure). Also see this short article. So I guess the problem lies within the 3rd line of your code, because the rest of it looks good to me

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.

Explain 1-liner party of a US President from IOCCC 2013

I found this code on ioccc and I have trouble even beginning to understand how it works!
void main(int riguing, char** acters) {
puts(1[acters-~!(*(int*)1[acters]%4796%275%riguing)]);
}
An explanation of how this is valid code and how it actually works would be fantastic!
First, in C (and C++) k[pointer] and pointer[k] mean exactly the same thing, which is *(k + pointer) and *(pointer + k), respectively. Code obfuscators often seem to like to use the first version because many people find it unusual. But it's reasonably obvious that pointer + k and k + pointer are the same computation.
The other little diversion in the snippet is the use of
pointer-~!(something)
which is exactly the same as
pointer + (something == 0 ? 2 : 1)
How this works:
The ! operator turns any true (non-zero) value into 0 and the false (0) value into a boolean true (1):
!something: something == 0 ? 1 : 0
The ~ operator is bitwise inverse, so it turns 0 into the number consisting of all 1 bits, which is -1 and 1 into the number consisting of all 1 bits except the last bit, which is -2. See Wikipedia article on two's complement.
~!something: something == 0 ? -2 : -1
Subtracting that from something is the same as adding the negative (a - -b == a + b)
a-~!something: something == 0 ? a + 2 : a + 1
Finally
1[a-~!something]: something == 0 ? a[3] : a[2]
So it selects either the second or third command line argument based on whether some computation is zero or not.
So now we need to decipher "some computation". We start with the type-punning operator *(T *)(pointer), in this case *(int*)(char*), reads out whatever the pointer points to as though it were a T. So in this case, it reads the first sizeof(int) characters from 1[acters] -- that is, from the first command-line argument (argv[1]) -- as though they were the internal representation of an integer. That will code every president as an integer based on the first four characters of their surname.
While there have been several repeated presidential surnames in US history, it's not a problem as long as the two presidents with the same name shared a political party.
One such pair, the father and son John Adams, Jr. (a Federalist), and John Quincy Adams (elected to the senate as a Federalist and to the presidency as a Democratic-Republican), are eliminated as being prior to the first valid president (Franklin Pierce), as is the elder Harrison (William Henry, a Whig) whose grandson Benjamin was elected as a Republican. The father and son George H.W. and George W. Bush are both Republicans. And the two Johnsons, Andrew and Lyndon Baines (as far as I know, not related to each other), were both Democrats.
So that leaves only the two Roosevelts, Theodore (Republican) and Franklin Delano (Democrat). The great-great-great-great-grandfathers of the two Roosevelt presidents were the brothers Johannes and Jacobus, sons of Nicholas Roosevelt (or Nicholas van Rosenvelt) (1658-1742) and grandsons of the Dutch immigrant Claes Maartenszen Van Rosenvelt, making them fifth cousins. However, the presidents were more closely related to each other through Eleanor Roosevelt, Theodore's niece and FDR's wife. In order for the IOCCC entry to work, it's necessary to represent the younger Roosevelt as "fdr", as he was commonly known.
So that only leaves (integer)%4796%275%riguing, or (integer)%4796%275%4, since riguing (aka argc) is 4. That's a simple hash function, which I imagine was discovered by trial and error using the list of presidential surnames and their affiliations.

Resources