Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dumb C question
#11
You return an int from main because the standard says you should, that way you code will work on any system that complies to the standard without doing wierd things. The value returned from main isn't always returned the operating system either, it can be returned to another process, for example:

Code:
/* Fork.c */
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int main() {

   pid_t child;
   int status = 0;

   /* Fork new process */
   child = fork();

   if(child == 0) {
      /* Child process */
      execlp("child", "child");
   } else {
      /* Parent process */
      wait(&status);
      printf("Child exited with status = %d\n", WEXITSTATUS(status));
   }
   return 0;
}
Code:
/* Child.c */
#include <stdio.h>
#include <stdlib.h>

int main()  {
  int retval = 200;

  printf("Child process, returning %d\n", retval);
  return retval;
}
Code:
$ gcc fork.c -o fork
$ gcc child.c -o child
$ ./fork
Child process, returning 200
Child exited with status = 200

In the case of UNIX the return value of a process will never be returned to the operating system because the first process launched is the init process, everything else is a child of init or one of its descendants, if init does return then you will most likely get a kernel panic. Im not exactly sure how Windows works, but I imagine its similar, the operating system doesn't launch processes, other processes (such as the shell/explorer or init process) do.

Quote:Window expects your program to give it a return value to free its memory space. If you don't return a value windows just simply assume its still running. Yes it may disappear from the task manager.
Thats wrong. Say the return value is stored in the eax register after a process exits, it isn't possible to not have a value in the eax register, so if a return value is not given (ie by main returning void) a process will probably just return whatever was last in the eax register, or it might put something random there. Standards ensure that the behaviour of something is known.
esus saves.... Passes to Moses, shoots, he scores!
Reply
#12
Quote:[code]
And if you ever again post code that contains one space before the end of the line on EVERY SINGLE LINE, I will eat you. You were warned!


I didn't!
Thanks for the tip about the initialising. Indeed LK, it wasn't right... Took me some time to find out, but now it's running all right. That is, with the replacement of == in <.... Till next time, maybe I shall try to find a C forum which is as patient as this one. ....
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)