Examples

Fork/Exec

Fork

The fork() Unix function spawns a child process which is an exact duplicate of the parent process.  Fork returns twice, once in the parent and once in the child.  In the child, fork returns 0; in the parent, fork returns the Process ID (pid) of the new child.  After returning from fork, both parent and child continue running simultaneously but with entirely separate address spaces.  This means that neither process will be able to communicate with the other process (at least not thru shared memory).

Keep in mind that the child process is a copy of the parent.  Both will have the same code and will continue running from the same spot (at the return from fork), but they will be distinct processes.

Exec

The exec() Unix function replaces the current process with a new process by running a specified program.  A call to exec will never return (unless there is an error).

Wait

The wait() and waitpid() Unix functions cause the current process to block, waiting until a child process terminates.

Altogether Now

int pid = fork();
int status = 0;

if (pid == 0) {
   // this is the child!

   execvp(cmd, argv);

   // this should never be reached, unless there is an error
   fprintf (stderr, "unknown command: %s\n", cmd);
   exit(0);

} else {
   // this is the parent!

   // wait for child to finish
   waitpid(pid, &status, 0);

   if (status != 0) {
      fprintf  (stderr, "error: %s exited with status code %d\n", cmd, status);
   } else {
      // cmd exec'd successfully
   }
}

// this is the parent still, since the child always terminates from exec or exit

// continue being a shell...


Strtok

One way to tokenize a string in C is to use the stdlib's strtok function.  IT IS DANGEROUS, so be careful when using it.  It has a few major problems:
  • side effect 1: it modifies it's input argument, placing null-characters '\0' between tokens.
  • side effect 2: it keep an internal state.  Each time you call it, it returns a new token.  This means it is NOT REENTRANT and NOT THREAD-SAFE.
Keeping these in mind, it is still possible to use strtok effectively.  Here's how you use it:

char whitechars[] = " \n\t\r";
char *tok = strtok(line, whitechars);
while (tok != NULL) {
   printf ("next token is: %s\n", tok);
...
   tok = strtok(NULL, whitechars);
}

Go (Language)

I have a small website with some example Go code here: golangpatterns.info.  Of particular interest for this class is:
Here's some example implementations in various languages.  They are kinda interesting: http://dada.perl.it/shootout/prodcons_allsrc.html


Comments