0

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!

kww
  • 411
  • 4
  • 12
  • 21
  • `ps aux | grep a.out` might surprise you – cleblanc Oct 18 '17 at 20:08
  • just want to know for what purpose you wrote the code? – danglingpointer Oct 18 '17 at 20:09
  • @LethalProgrammer This is from a tutorial as an example of silly code. But I do want to figure it out. – kww Oct 18 '17 at 20:10
  • 1
    If you're an inexperienced C programmer, then `fork()` is *not* the place to start. – John Bollinger Oct 18 '17 at 20:27
  • 1
    Nevertheless, if you're determined to figure this out, then the appropriate thing to do would be to read the documentation for the functions you are calling: [`fork()`](http://man7.org/linux/man-pages/man2/fork.2.html), [`waitpid()`](http://man7.org/linux/man-pages/man2/wait.2.html), and [`printf()`](http://man7.org/linux/man-pages/man3/printf.3.html). If that's too heavy for you, you can likely find tutorial-level information about these scattered across the web. Google is your friend. – John Bollinger Oct 18 '17 at 20:31

1 Answers1

0

the function: fork() can set the pid to any of three different meanings:

  1. -1 means an error occurred.
  2. =0 means currently running the child process.
  3. >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]

user3629249
  • 16,402
  • 1
  • 16
  • 17