I wrote the following code and ran it for a couple times. But every time the result is different.
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
pid_t id;
int status;
while (--argc && (id=fork())) {
waitpid(id,&status,0); /* Wait for child*/
}
printf("%d:%s\n", argc, argv[argc]);
return 0;
}
I ran like:
./a.out 1 2 3
Then sometimes I got:
3: 3
2: 2
1: 1
0: ./a.out
$ 0: ./a.out (It seems still running, waiting for my input)
Sometimes I got:
3: 3
$ 3: 3 (It seems still running, waiting for my input)
Any idea? Thanks!
the function: fork()
can set the pid
to any of three different meanings:
-1
means an error occurred. =0
means currently running the child process. >0
means currently running the parent process.So the parent forks children according to the number of command line parameters. Then waits for each consecutive child to exit.
Each child process executes the printf()
function then exits
Finally the parent executes the printf()
function with a argc
of 0
Note: the code should be checking the returned value from the call to waitpid()
Note: the code should be checking the variable id
> 0 to assure the call to fork()
was successful. As it is, a failure of that call (returned -1) will result in the call to waitpid()
to wait forever because there is no child process to wait on
.
Here is a pair of example rund where untitled1
is the name of the executable
rkwill@richard-desktop:~/Documents/forum$ ./untitled1 1 2 3
3:3
2:2
1:1
0:./untitled1
rkwill@richard-desktop:~/Documents/forum$ ./untitled1
0:./untitled1
rkwill@richard-desktop:~/Documents/forum$
As you can see from the above, when given parameters, it lists them in reverse order, then lists the argv[0]
.
When given no parameters, it still lists the argv[0]