Have some code like this:
unsigned pid = waitpid(mPid, &status, WNOHANG);
mExitStatus = WEXITSTATUS(status);
Get the debug print for the variable like:
mExitStatus = 15
status = 3840
For "mExitStatus = WEXITSTATUS(status)", I got following statment which explains
evaluates to the least significant eight bits of the return code of the child which terminated
3840 = F00; F is 15 which is assigned to mExitStatus
But question is how I can use this 15 to judge whether if the child process is terminated correctly or not?
15 is from 3840. But 3840 is return by linux process? Any meaning for that?
In a general description, my main started 4 child_process running 4 tests. I would like to judge in my main if those 4 tests are passed or not. So I think I need to jude on the exit status of my child process.
Thanks
The standard is that an exit status of zero means "success" and anything else is some sort of failure. On *nix systems, a value from 129 to 150 or so can usually be interpreted as "the process was terminated due to a signal" and the signal number is the return value minus 128. A generic failure often returns 1, but sometimes 2 or 3 or some other small number.
In the end, what a program returns is completely up to the program, but those are the typical values.
Related
Sorry for such a noob question, but why the result is not 516?
define i32 #main()
{
%1 = add i32 6, 500
%2 = add i32 5, 5
%3 = add i32 %1, %2
ret i32 %3
}
http://llvm.org/docs/LangRef.html#integer-type
i32 a 32-bit integer.
Usage:
./lli Program.ir; echo $?
4
Thanks in advance
The exit code of a process in Unix is only 8 bits. Any larger value gets truncated, regardless of whether LLVM is involved:
$ ( exit 516 ); echo $?
4
The exit code (I'm going to distinguish the exit value returned by your program, from the exit code made available to the process that started you program) is actually, in UNIX like operating systems, a conglomeration of several different items, one of which is the exit value. See, for example, this link, which contains (with my emphasis and [extra information]):
Don't confuse a program's exit status [value] with a process' termination status [code]. There are lots of ways a process can terminate besides having its program finish. In the event that the process termination is caused by program termination (i.e., exit), though, the program’s exit status [value] becomes part of the process' termination status [code].
The macro to get the actual exit status from the process (see here) states:
If WIFEXITED is true of status, this macro returns the low-order 8 bits of the exit status value from the child process.
That's also indicated by the actual source code of the Linux exit_group syscall, which is the one eventually called by exit:
SYSCALL_DEFINE1(exit_group, int, error_code)
{
do_group_exit((error_code & 0xff) << 8);
/* NOTREACHED */
return 0;
}
You can see there that it only uses the lower eight bits of the exit value, and shifts it left so it can store those other items (control information) in there, all zero in this case. Contrast that with the same call from the signal processor which only sets the control information:
do_group_exit(ksig->info.si_signo)
In other words, it also has to put other things in the process exit code, such as which signal terminated it (if it was terminated by a signal), whether it dumped core, and so on. That's why the exit value is limited to a lesser range than you expect.
The ISO standard (C11) also allows for this, in 7.22.4.4 The exit function /5 (since returning an integer value from main() is equivalent to calling exit() with that value:
Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
I feel like this must have a simple answer, but I really don't know how to approach this.
For background, the stack of things is like this:
Python script -> C++ binary -(fork)-> actual thing we want to measure.
Essentially, we have a python script that simulates an environment by using tmp directories and running multiple instances of this network software stack we're developing. The script calls a host binary (which is unimportant here), and then, after it loads, a helper binary. The helper binary can be passed a parameter to daemonize, and when it does this, it forks in the usual way.
What we need to do is measure the daemon's CPU utilization, but I don't really know how to. What I have done is read the stat file periodically, but since the process daemonizes, I can't use echo $! to get its PID. Using ps aux | grep 'thing' works fine, but I think this is giving me the parent process, because the stat information looks like this:
1472582561 9455 (nlsr) S 1 9455 9455 0 -1 4218944 394 0 0 0 13 0 0 0 20 0 2 0 909820 184770560 3851 18446744073709551615 4194304 5318592 140734694817376 140734694810512 140084250723843 0 0 16781312 0 0 0 0 17 0 0 0 0 0 0 7416544 7421528 16224256 140734694825496 140734694825524 140734694825524 140734694825962 0
I know that the parent process should not be PID1, and definitely the utime field and similar should be greater than 13 clock ticks. This is what is leading me to conclude that this process is really the parent process, and not the forked child that's doing all the work.
I can modify pretty much any file necessary, but because of code review constraints, design specs., etc., the less I have to change along many files, the better.
Get the PID of the child reliably
fork() returns the PID of the child to the parent
Get the CPU stats from /proc/[PID]/stat
#14 utime - CPU time spent in user code, measured in clock ticks
can you tell me, why is output of this program this:
1
2
2
5
5
3
4
5
4
5
3
4
5
4
5
And quick explanation why is that like this? Thanks
main()
{
printf("1\n");
fork();
printf("2\n");
if(fork()==0)
{
printf("3\n");
fork();
printf("4\n");
}
printf("5\n");
}
The output of your program, assuming no calls to fork fail, should be thought of like this:
1
2 2
3 3
4 4 4 4
5 5 5 5 5 5
Each column represents the output of one process. They all get serialized onto stdout in some random order, subject only to the following constraints: within a column, each character cannot appear before the character immediately above it; the topmost character in each column cannot appear before the character above and to the left of it.
Note that right now your program is relying on the C library noticing that stdout is a terminal and therefore setting it to line-buffered. If you run the program with stdout redirected to a file or pipe you are likely to get rather different output, e.g.
$ ./a.out | tr '\n' ' '
1 2 5 1 2 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
... because in that case all of the output is buffered until returning from main, and the buffers are copied into each child process. Adding
setvbuf(stdout, 0, _IONBF, 0);
before the first printf statement will prevent duplication of output. (In this case you could get away with _IOLBF instead, but _IONBF is safer for code like this.)
It would be a little easier to show graphically, but everytime you call fork() you have another process continue through the same code. So:
Process 1 (original process): prints 1, then creates Process 2, prints 2, then creates Process 3 but doesn't return 0, and prints 5.
Process 2: prints 2, then creates Process 4 but doesn't return 0, and prints 5.
Process 3: prints 3, then creates Process 5, prints 4, prints 5
Process 4: prints 3, then creates Process 6, prints 4, prints 5
Process 5: prints 4, prints 5
Process 6: prints 4, prints 5
But they are all happening in similar time so that why you get all those numbers.
Hope that helps. First time answering!
See in some flavor suppose in fedora parent get chance first to execute and then child but in other like ubuntu child get first preference on the basis of that you will see the out put. No relation with printf function in this scope but we can predict how many times the body of the method will execute here I am attaching one image may it is helpful for you.
Here when 1 print only one process. After execution of first fork then two different process each is having fork but inside your if statement. So one again creates two process but only one will get the chance to enter in the if body. Again fork will execute and again new process will generates. The formula is total number of process=2*n. Where n is the number of fork() method inside your function. So total six methods will have some condition to printing any number like 2,3,4 but 5 is common to all so 5 will print six times.
May be my post helpful for you
Thanks
asif aftab
Its since you're not always testing for the fork() calls result. The zero result path will remain the parent process and the else part will be executed as child process. As you're not testing that every code following a fork(); call will be duplicated (and executed) in both processes.
the output is not deterministic due to the order of execution and inheritance of the output buffers, a way to be deterministic is with
#include <stdlib.h>
#include <stdio.h>
main()
{
printf("1\n");
fflush(stdout);
if (fork()) wait(0);
printf("2\n");
fflush(stdout);
if(fork()==0)
{
printf("3\n");
fflush(stdout);
if (fork()) wait(0);
printf("4\n");
} else wait();
printf("5\n");
}
Using fork() we create a child process, and there is no execution pattern gurantee for either parent or child, as discussed here.
If you want to have an execution pattern, its better to put a check on fork() for the parent [pid is not 0] or child [pid is 0] and make either of them to sleep so that scheduler puts the other one on execution.
You can find more information here.
Micheal, I would need to see the code inside of the fork() method to know for sure, but being that it is printing numbers extra numbers, the only possible explanation that I can think of is that your fork() method might have print methods of its own.
Robin
I have managed to fork and exec a different program from within my app. I'm currently working on how to wait until the process called from exec returns a result through a pipe or stdout. However, can I have a group of processes using a single fork, or do I have to fork many times and call the same program again? Can I get a PID for each different process ? I want my app to call the same program I'm currently calling many times but with different parameters: I want a group of 8 processes of the same program running and returning results via pipes. Can someone please point me to the right direction please ? I've gone through the linux.die man pages, but they are quite spartan and cryptic in their description. Is there an ebook or pdf I can find for detailed information ? Thank you!
pid_t pID = fork();
if (pID == 0){
int proc = execl(BOLDAGENT,BOLDAGENT,"-u","2","-c","walkevo.xml",NULL);
std::cout << strerror(errno) << std::endl;
}
For example, how can I control by PID which child (according to the parameter xml file) has obtained which result (by pipe or stdout), and thus act accordingly? Do I have to encapsulate children processes in an object, and work from there, or can I group them altogether?
One Fork syscall make only one new process (one PID). You should organize some data structures (e.g. array of pids, array of parent's ends of pipes, etc), do 8 fork from main program (every child will do exec) and then wait for childs.
After each fork() it will return you a PID of child. You can store this pid and associated information like this:
#define MAX_CHILD=8
pid_t pids[MAX_CHILD];
int pipe_fd[MAX_CHILD];
for(int child=0;child<MAX_CHILD;child++) {
int pipe[2];
/* create a pipe; save one of pipe fd to the pipe_fd[child] */
int ret;
ret = fork();
if(ret) { /* parent */
/* close alien half of pipe */
pids[child] = ret; /* save the pid */
} else { /* child */
/* close alien half of pipe */
/* We are child #child, exec needed program */
exec(...);
/* here can be no more code in the child, as `exec` will not return if there is no error! */
}
}
/* there you can do a `select` to wait data from several pipes; select will give you number of fd with data waiting, you can find a pid from two arrays */
It's mind-bending at first, but you seem to grasp that, when you call fork( ):
the calling process (the "parent") is
essentially duplicated by the
operating system and the duplicate process
becomes the "child"
with a unique PID all its own;
the returned value from the fork( )
call is either: integer
0,1 meaning that the
program receiving the 0 return is the
"child"; or it is the non-zero integer PID
of that forked child; and
the new child process is entered into
the scheduling queue for execution.
The parent remains in the scheduling
queue and continues to execute as
before.
It is this ( 0 .xor. non-0 ) return from fork( ) that tells the program which role it's playing at this instant -- 0 returned, program is the child process; anything else returned, program is the parent process.
If the program playing the parent role wants many children, he has to fork( ) each one separately; there's no such thing as multiple children sharing a fork( ).
Intermediate results certainly can be sent via a pipe.
As for calling each child with different parameters, there's really nothing special to do: you can be sure that, when the child gets control, he will have (copies of) exactly the same variables as does the parent. So communicating parameters to the child is a matter of the parent's setting up variable values he wants the child to operate on; and then calling fork( ).
1 More accurately: fork( ) returns a value of type pid_t, which these days is identical to an integer on quite a few systems.
It's been a while since I've worked in C/C++, but a few points:
The Wikipedia fork-exec page provides a starting point to learn about forking and execing. Google is your friend here too.
As osgx's answer says, fork() can only give you one subprocess, so you'll have to call it 8 times to get 8 processes and then each one will have to exec the other program.
fork() returns the PID of the child process to the main process and 0 to the subprocess, so you should be able to do something like:
int pid = fork();
if (pid == 0) {
/* exec new program here */
} else {
/* continue with parent process stuff */
}
On my system the lowest ID running right now is 1 (init). I'm making a small wrapper function around pidof and I was wondering, what is the lowest possible process ID a process can have?
The reason I ask is because I would like to return an integer from my function indicating "process was not running" (pidof itself returns an empty string in this case). I was thinking of using either 0 or -1, and I just want to make sure a real process could never have such IDs.
PIDs are always positive, so both 0 and -1 are OK as non-PID sentinels. Several PID-related system calls, like wait() and kill(), assign special meaning to these values.